This repository has been archived on 2020-01-20. You can view files and clone it, but cannot push or open issues or pull requests.
node-spearhead/lib/cloudapi2.js

651 lines
19 KiB
JavaScript
Raw Normal View History

/*
* Copyright (c) 2015, Joyent, Inc. All rights reserved.
*
* Client library for the SmartDataCenter Cloud API (cloudapi).
* http://apidocs.joyent.com/cloudapi/
*
* Usage example::
*
* var auth = require('smartdc-auth');
* var cloudapi = require('./lib/cloudapi2');
* var client = cloudapi.createClient({
* url: <URL>, // 'https://us-sw-1.api.joyent.com',
* user: <USER>, // 'bob'
* log: <BUNYAN-LOGGER>,
* sign: auth.cliSigner({
* keyId: <KEY-ID>, // ssh fingerprint
* user: <USER>, // 'bob'
* log: <BUNYAN-LOGGER>,
* }),
* ...
* });
* client.listImages(function (err, images) { ... });
* ...
*
*/
var assert = require('assert-plus');
var auth = require('smartdc-auth');
2015-08-26 00:25:30 +03:00
var format = require('util').format;
2015-08-26 02:46:14 +03:00
var LOMStream = require('lomstream').LOMStream;
var os = require('os');
var querystring = require('querystring');
var restifyClients = require('restify-clients');
var vasync = require('vasync');
var errors = require('./errors');
// ---- globals
var VERSION = require('../package.json').version;
var OS_ARCH = os.arch();
var OS_PLATFORM = os.platform();
// ---- internal support stuff
// A no-op bunyan logger shim.
function BunyanNoopLogger() {}
BunyanNoopLogger.prototype.trace = function () {};
BunyanNoopLogger.prototype.debug = function () {};
BunyanNoopLogger.prototype.info = function () {};
BunyanNoopLogger.prototype.warn = function () {};
BunyanNoopLogger.prototype.error = function () {};
BunyanNoopLogger.prototype.fatal = function () {};
BunyanNoopLogger.prototype.child = function () { return this; };
BunyanNoopLogger.prototype.end = function () {};
// ---- client API
/**
* Create a cloudapi client.
*
* @param options {Object}
* - {String} url (required) Cloud API base url
* - {String} user (required) The user login name.
* For backward compat, 'options.account' is accepted as a synonym.
* - {Function} sign (required) An http-signature auth signing function
* - {String} version (optional) Used for the accept-version header. This
* defaults to '*', meaning that over time you could experience breaking
* changes. Specifying a value is strongly recommended. E.g. '~7.1'.
* - {Bunyan Logger} log (optional)
* - ... and any other standard restify client options, e.g.:
* {String} userAgent
* {Boolean} rejectUnauthorized
* {Boolean} agent Set to `false` to not get KeepAlive. You want
* this for CLIs.
* TODO doc the backoff/retry available options
* @throws {TypeError} on bad input.
* @constructor
*
* TODO: caching options (copy node-manta/node-moray/node-smartdc?)
* - {Boolean} noCache (optional) disable client caching (default false).
* - {Boolean} cacheSize (optional) number of cache entries (default 1k).
* - {Boolean} cacheExpiry (optional) entry age in seconds (default 60).
*/
function CloudAPI(options) {
assert.object(options, 'options');
assert.string(options.url, 'options.url');
assert.string(options.user || options.account, 'options.user');
assert.func(options.sign, 'options.sign');
assert.optionalString(options.version, 'options.version');
assert.optionalObject(options.log, 'options.log');
this.url = options.url;
this.user = options.user || options.account;
this.sign = options.sign;
this.log = options.log || new BunyanNoopLogger();
if (!options.version) {
options.version = '*';
}
if (!options.userAgent) {
options.userAgent = format('triton/%s (%s-%s; node/%s)',
VERSION, OS_ARCH, OS_PLATFORM, process.versions.node);
}
// XXX relevant?
//options.retryCallback = function checkFor500(code) {
// return (code === 500);
//};
// XXX relevant?
//this.token = options.token;
this.client = restifyClients.createJsonClient(options);
}
CloudAPI.prototype._getAuthHeaders = function _getAuthHeaders(callback) {
assert.func(callback, 'callback');
var self = this;
var headers = {};
headers.date = new Date().toUTCString();
var sigstr = 'date: ' + headers.date;
//XXX
//if (this.token !== undefined) {
// obj.headers['X-Auth-Token'] = this.token;
//}
self.sign(sigstr, function (err, sig) {
if (err || !sig) {
callback(new errors.SigningError(err));
return;
}
headers.authorization = format(
'Signature keyId="/%s/keys/%s",algorithm="%s",signature="%s"',
self.user, sig.keyId, sig.algorithm, sig.signature);
callback(null, headers);
});
};
2015-08-26 00:25:30 +03:00
/**
* Return an appropriate query string *with the leading '?'* from the given
* fields. If any of the field values are undefined or null, then they will
* be excluded.
*/
CloudAPI.prototype._qs = function _qs(/* fields1, ...*/) {
var fields = Array.prototype.slice.call(arguments);
2015-08-26 00:25:30 +03:00
var query = {};
fields.forEach(function (field) {
Object.keys(field).forEach(function (key) {
var value = field[key];
2015-08-26 00:25:30 +03:00
if (value !== undefined && value !== null) {
query[key] = value;
}
});
});
2015-08-26 00:25:30 +03:00
if (Object.keys(query).length === 0) {
return '';
} else {
return '?' + querystring.stringify(query);
}
};
/**
* Return an appropriate full URL *path* given an CloudAPI subpath.
* This handles prepending the API's base path, if any: e.g. if the configured
* URL is "https://example.com/base/path".
*
* Optionally an object of query params can be passed in to include a query
* string. This just calls `this._qs(...)`.
*/
2015-09-02 20:47:06 +03:00
CloudAPI.prototype._path = function _path(subpath /* , qparams, ... */) {
2015-08-26 00:25:30 +03:00
assert.string(subpath, 'subpath');
assert.ok(subpath[0] === '/');
var path = subpath;
var qparams = Array.prototype.slice.call(arguments, 1);
path += this._qs.apply(this, qparams);
2015-08-26 00:25:30 +03:00
return path;
};
/**
2015-08-26 01:47:29 +03:00
* Cloud API request wrapper - modeled after http.request
*
* @param {Object|String} options - object or string for endpoint
* - {String} path - URL endpoint to hit
* - {String} method - HTTP(s) request method
2015-08-26 04:09:32 +03:00
* - {Object} data - data to be passed
* @param {Function} callback passed via the restify client
*/
2015-08-26 01:47:29 +03:00
CloudAPI.prototype._request = function _request(options, callback) {
var self = this;
2015-09-01 22:03:52 +03:00
if (typeof (options) === 'string')
options = {path: options};
assert.object(options, 'options');
assert.func(callback, 'callback');
2015-08-26 04:09:32 +03:00
assert.optionalObject(options.data, 'options.data');
var method = (options.method || 'GET').toLowerCase();
assert.ok(['get', 'post', 'delete', 'head'].indexOf(method) >= 0,
'invalid method given');
2015-08-26 08:25:26 +03:00
switch (method) {
2015-09-01 22:03:52 +03:00
case 'delete':
method = 'del';
2015-09-01 19:00:45 +03:00
break;
default:
break;
2015-08-26 08:25:26 +03:00
}
2015-09-01 19:00:45 +03:00
self._getAuthHeaders(function (err, headers) {
if (err) {
callback(err);
return;
}
var opts = {
path: options.path,
headers: headers
};
2015-08-26 04:09:32 +03:00
if (options.data)
self.client[method](opts, options.data, callback);
else
self.client[method](opts, callback);
});
};
2015-08-26 23:40:50 +03:00
/**
* A simple wrapper around making a GET request to an endpoint and
* passing back the body returned
*/
CloudAPI.prototype._passThrough =
function _passThrough(endpoint, opts, cb) {
if (typeof (opts) === 'function') {
cb = opts;
opts = null;
}
opts = opts || {};
2015-08-26 01:47:29 +03:00
2015-08-26 23:40:50 +03:00
assert.string(endpoint, 'endpoint');
assert.object(opts, 'opts');
assert.func(cb, 'cb');
2015-08-26 01:47:29 +03:00
2015-08-26 23:40:50 +03:00
var p = this._path(endpoint, opts);
this._request(p, function (err, req, res, body) {
cb(err, body, res);
});
};
2015-08-26 23:40:50 +03:00
// ---- networks
/**
* Get network information
*
* @param {Function} callback of the form `function (err, networks, response)`
*/
CloudAPI.prototype.listNetworks = function listNetworks(opts, cb) {
var endpoint = format('/%s/networks', this.user);
this._passThrough(endpoint, opts, cb);
};
2015-08-27 00:09:50 +03:00
/**
* <http://apidocs.joyent.com/cloudapi/#GetNetwork>
*
* @param {String} - UUID
* @param {Function} callback of the form `function (err, network, res)`
*/
CloudAPI.prototype.getNetwork = function getNetwork(id, cb) {
assert.uuid(id, 'id');
assert.func(cb, 'cb');
var endpoint = this._path(format('/%s/networks/%s', this.user, id));
this._request(endpoint, function (err, req, res, body) {
cb(err, body, res);
});
};
2015-08-27 02:56:18 +03:00
// ---- datacenters
/**
* Get services information
*
* @param {Function} callback of the form `function (err, services, response)`
*/
CloudAPI.prototype.listServices = function listServices(opts, cb) {
var endpoint = format('/%s/services', this.user);
2015-08-27 02:56:18 +03:00
this._passThrough(endpoint, opts, cb);
};
2015-08-27 02:59:28 +03:00
/**
* Get datacenters information
*
2015-09-02 20:47:06 +03:00
* @param {Function} callback of the form
* `function (err, datacenters, response)`
2015-08-27 02:59:28 +03:00
*/
CloudAPI.prototype.listDatacenters = function listDatacenters(opts, cb) {
var endpoint = format('/%s/datacenters', this.user);
2015-08-27 02:59:28 +03:00
this._passThrough(endpoint, opts, cb);
};
2015-08-26 23:40:50 +03:00
// ---- accounts
/**
* Get account information
*
* @param {Function} callback of the form `function (err, account, response)`
*/
2015-08-26 23:40:50 +03:00
CloudAPI.prototype.getAccount = function getAccount(opts, cb) {
var endpoint = format('/%s', this.user);
2015-08-26 23:40:50 +03:00
this._passThrough(endpoint, opts, cb);
};
2015-08-26 07:40:32 +03:00
/**
* Get public key information
*
* @param {Function} callback of the form `function (err, keys, response)`
*/
2015-08-26 23:40:50 +03:00
CloudAPI.prototype.listKeys = function listKeys(opts, cb) {
var endpoint = format('/%s/keys', this.user);
2015-08-26 23:40:50 +03:00
this._passThrough(endpoint, opts, cb);
2015-08-26 07:40:32 +03:00
};
2015-08-26 00:25:30 +03:00
// ---- images
/**
* <http://apidocs.joyent.com/cloudapi/#ListImages>
*
* @param {Object} options (optional)
* XXX document this, see the api doc above :)
* @param {Function} callback of the form `function (err, images, res)`
*/
2015-08-26 23:44:11 +03:00
CloudAPI.prototype.listImages = function listImages(opts, cb) {
var endpoint = format('/%s/images', this.user);
2015-08-26 23:44:11 +03:00
this._passThrough(endpoint, opts, cb);
2015-08-26 01:47:29 +03:00
};
2015-08-26 00:25:30 +03:00
2015-08-26 01:47:29 +03:00
/**
* <http://apidocs.joyent.com/cloudapi/#ListImages>
*
* @param {Object} options
* - id {UUID}
* @param {Function} callback of the form `function (err, image, res)`
*/
CloudAPI.prototype.getImage = function getImage(options, callback) {
if (callback === undefined) {
callback = options;
options = {};
}
assert.object(options, 'options');
assert.uuid(options.id, 'options.id');
2015-08-26 01:47:29 +03:00
assert.func(callback, 'callback');
var endpoint = this._path(format('/%s/images/%s', this.user, options.id));
this._request(endpoint, function (err, req, res, body) {
callback(err, body, res);
2015-08-26 00:25:30 +03:00
});
};
// ---- packages
2015-08-26 23:44:11 +03:00
CloudAPI.prototype.listPackages = function listPackages(opts, cb) {
var endpoint = format('/%s/packages', this.user);
2015-08-26 23:44:11 +03:00
this._passThrough(endpoint, opts, cb);
};
CloudAPI.prototype.getPackage = function getPackage(options, callback) {
if (callback === undefined) {
callback = options;
options = {};
}
assert.object(options, 'options');
assert.uuid(options.id, 'options.id');
assert.func(callback, 'callback');
var endpoint = this._path(format('/%s/packages/%s', this.user, options.id));
this._request(endpoint, function (err, req, res, body) {
callback(err, body, res);
});
};
// ---- machines
2015-07-26 08:45:20 +03:00
/**
* Get a machine by id.
*
* XXX add getCredentials equivalent
* XXX cloudapi docs don't doc the credentials=true option
*
2015-08-26 04:09:32 +03:00
* @param {String} uuid (required) The machine id.
2015-07-26 08:45:20 +03:00
* @param {Function} callback of the form `function (err, machine, response)`
*/
2015-08-27 00:09:50 +03:00
CloudAPI.prototype.getMachine = function getMachine(id, cb) {
assert.uuid(id, 'id');
assert.func(cb, 'cb');
2015-07-26 08:45:20 +03:00
var endpoint = format('/%s/machines/%s', this.user, id);
2015-08-26 03:27:46 +03:00
this._request(endpoint, function (err, req, res, body) {
2015-08-27 03:08:52 +03:00
cb(err, body, res);
2015-07-26 08:45:20 +03:00
});
};
2015-08-26 08:25:26 +03:00
/**
* delete a machine by id.
*
* @param {String} uuid (required) The machine id.
* @param {Function} callback of the form `function (err, machine, response)`
*/
CloudAPI.prototype.deleteMachine = function deleteMachine(uuid, callback) {
var self = this;
assert.string(uuid, 'uuid');
assert.func(callback, 'callback');
var opts = {
path: format('/%s/machines/%s', self.user, uuid),
2015-08-26 08:25:26 +03:00
method: 'DELETE'
};
this._request(opts, function (err, req, res, body) {
callback(err, body, res);
});
};
2015-08-26 04:09:32 +03:00
/**
* start a machine by id.
*
* @param {String} uuid (required) The machine id.
* @param {Function} callback of the form `function (err, machine, response)`
*/
CloudAPI.prototype.startMachine = function startMachine(uuid, callback) {
return this._doMachine('start', uuid, callback);
};
/**
* stop a machine by id.
*
* @param {String} uuid (required) The machine id.
* @param {Function} callback of the form `function (err, machine, response)`
*/
CloudAPI.prototype.stopMachine = function stopMachine(uuid, callback) {
return this._doMachine('stop', uuid, callback);
};
/**
* reboot a machine by id.
*
* @param {String} uuid (required) The machine id.
* @param {Function} callback of the form `function (err, machine, response)`
*/
CloudAPI.prototype.rebootMachine = function rebootMachine(uuid, callback) {
return this._doMachine('reboot', uuid, callback);
};
/**
* internal function for start/stop/reboot
*/
CloudAPI.prototype._doMachine = function _doMachine(action, uuid, callback) {
var self = this;
assert.string(action, 'action');
2015-08-26 04:09:32 +03:00
assert.string(uuid, 'uuid');
assert.func(callback, 'callback');
var opts = {
path: format('/%s/machines/%s', self.user, uuid),
2015-08-26 04:09:32 +03:00
method: 'POST',
data: {
action: action
}
};
this._request(opts, function (err, req, res, body) {
callback(err, body, res);
});
};
/**
2015-08-26 06:53:48 +03:00
* Wait for a machine to go one of a set of specfic states.
*
* @param {Object} options
* - {String} id - machine UUID
2015-08-26 06:53:48 +03:00
* - {Array of String} states - desired state
* - {Number} interval (optional) - time in ms to poll
* @param {Function} callback - called when state is reached or on error
*/
2015-09-02 20:47:06 +03:00
CloudAPI.prototype.waitForMachineStates =
function waitForMachineStates(opts, callback) {
var self = this;
assert.object(opts, 'opts');
assert.string(opts.id, 'opts.id');
2015-08-26 06:53:48 +03:00
assert.arrayOfString(opts.states, 'opts.states');
assert.optionalNumber(opts.interval, 'opts.interval');
assert.func(callback, 'callback');
var interval = (opts.interval === undefined ? 1000 : opts.interval);
poll();
function poll() {
2015-08-26 08:25:26 +03:00
self.getMachine(opts.id, function (err, machine, res) {
if (err) {
2015-08-26 08:25:26 +03:00
callback(err, null, res);
return;
}
2015-08-26 06:53:48 +03:00
if (opts.states.indexOf(machine.state) !== -1) {
2015-08-26 08:25:26 +03:00
callback(null, machine, res);
return;
}
setTimeout(poll, interval);
});
}
};
2015-07-26 08:45:20 +03:00
/**
* List the user's machines.
* <http://apidocs.joyent.com/cloudapi/#ListMachines>
*
2015-08-26 02:46:14 +03:00
* @param {Object} options
* See document above
* @return {LOMStream} a stream for each machine entry
*/
2015-08-26 02:46:14 +03:00
CloudAPI.prototype.createListMachinesStream =
function createListMachinesStream(options) {
var self = this;
2015-08-26 07:16:41 +03:00
options = options || {};
2015-08-26 02:46:14 +03:00
// if the user specifies an offset we don't paginate
var once = options.limit !== undefined;
return new LOMStream({
fetch: fetch,
limit: 1000,
offset: true
});
function fetch(fetcharg, limitObj, datacb, donecb) {
options.limit = limitObj.limit;
options.offset = limitObj.offset;
var endpoint = self._path(format('/%s/machines', self.user), options);
self._request(endpoint, function (err, req, res, body) {
var resourcecount = res.headers['x-resource-count'];
var done = once || resourcecount < options.limit;
donecb(err, {done: done, results: body});
});
}
2015-08-26 02:46:14 +03:00
};
2015-08-26 02:46:14 +03:00
/**
* List the user's machines.
* <http://apidocs.joyent.com/cloudapi/#ListMachines>
*
* @param {Object} options
* See document above
* @param {Function} callback - called like `function (err, machines)`
*/
CloudAPI.prototype.listMachines = function listMachines(options, callback) {
2015-08-26 07:16:41 +03:00
if (typeof (options) === 'function') {
callback = options;
options = {};
}
2015-08-26 02:46:14 +03:00
var machines = [];
var s = this.createListMachinesStream(options);
s.on('error', function (e) {
callback(e);
});
s.on('readable', function () {
var machine;
while ((machine = s.read()) !== null) {
machines.push(machine);
}
2015-08-26 02:46:14 +03:00
});
s.on('end', function () {
callback(null, machines);
});
};
2015-08-26 06:53:48 +03:00
CloudAPI.prototype.createMachine = function createMachine(options, callback) {
assert.object(options, 'options');
assert.optionalString(options.name, 'options.name');
assert.uuid(options.image, 'options.image');
assert.uuid(options.package, 'options.package');
assert.optionalArrayOfUuid(options.networks, 'options.networks');
// TODO: assert the other fields
assert.func(callback, 'callback');
// XXX how does options.networks array work here?
this._request({
method: 'POST',
2015-09-03 07:02:09 +03:00
path: format('/%s/machines', this.user),
data: options
2015-08-26 06:53:48 +03:00
}, function (err, req, res, body) {
callback(err, body, res);
});
};
2015-07-26 08:45:20 +03:00
/**
* List machine audit (successful actions on the machine).
*
* XXX IMO this endpoint should be called ListMachineAudit in cloudapi.
*
* @param {Object} options
* - {String} id (required) The machine id.
* @param {Function} callback of the form `function (err, audit, response)`
*/
CloudAPI.prototype.machineAudit = function machineAudit(options, callback) {
var self = this;
assert.object(options, 'options');
assert.string(options.id, 'options.id');
assert.func(callback, 'callback');
var path = format('/%s/machines/%s/audit', self.user, options.id);
2015-09-02 20:47:06 +03:00
// XXX This `client.get` block is duplicated. Add a convenience func for it:
2015-07-26 08:45:20 +03:00
self._getAuthHeaders(function (hErr, headers) {
if (hErr) {
callback(hErr);
return;
}
var opts = {
path: path,
headers: headers
};
self.client.get(opts, function (err, req, res, body) {
if (err) {
callback(err, null, res);
} else {
callback(null, body, res);
}
});
});
};
// --- Exports
module.exports = {
createClient: function (options) {
return new CloudAPI(options);
}
};