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

564 lines
16 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 p = console.log;
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 sprintf = require('util').format;
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 = sprintf('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 = sprintf(
'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(...)`.
*/
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;
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');
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 01:47:29 +03:00
// ---- accounts
/**
* Get account information
*
* @param {Function} callback of the form `function (err, account, response)`
*/
CloudAPI.prototype.getAccount = function getAccount(callback) {
var self = this;
assert.func(callback, 'callback');
var endpoint = sprintf('/%s', self.user);
this._request(endpoint, function (err, req, res, body) {
callback(err, body, res);
});
};
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)`
*/
CloudAPI.prototype.listImages = function listImages(options, callback) {
var self = this;
if (callback === undefined) {
callback = options;
options = {};
}
assert.object(options, 'options');
assert.func(callback, 'callback');
2015-08-26 01:47:29 +03:00
var endpoint = self._path(format('/%s/images', self.user), options);
self._request(endpoint, function (err, req, res, body) {
callback(err, body, res);
});
};
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
CloudAPI.prototype.listPackages = function listPackages(options, callback) {
var self = this;
if (typeof (options) === 'function') {
callback = options;
options = {};
}
var endpoint = self._path(format('/%s/packages', self.user), options);
self._request(endpoint, function (err, req, res, body) {
callback(err, body, res);
});
};
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-26 03:27:46 +03:00
CloudAPI.prototype.getMachine = function getMachine(uuid, callback) {
2015-07-26 08:45:20 +03:00
var self = this;
2015-08-26 03:27:46 +03:00
assert.string(uuid, 'uuid');
2015-07-26 08:45:20 +03:00
assert.func(callback, 'callback');
2015-08-26 03:27:46 +03:00
var endpoint = sprintf('/%s/machines/%s', self.user, uuid);
this._request(endpoint, function (err, req, res, body) {
callback(err, body, res);
2015-07-26 08:45:20 +03:00
});
};
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: sprintf('/%s/machines/%s', self.user, uuid),
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-08-26 06:53:48 +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() {
self.getMachine(opts.id, function (err, machine) {
if (err) {
callback(err);
return;
}
2015-08-26 06:53:48 +03:00
if (opts.states.indexOf(machine.state) !== -1) {
callback(null, machine);
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;
// 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) {
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',
path: this._path(format('/%s/machines', this.user), options)
}, 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 = sprintf('/%s/machines/%s/audit', self.user, options.id);
//XXX This `client.get` block is duplicated. Add a convenience function for it:
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);
}
};