UNPKG

ilorest

Version:
275 lines (231 loc) 13.8 kB
'use strict'; /* * Copyright 2018 Hewlett Packard Enterprise Development LP * 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. */ Object.defineProperty(exports, '__esModule', { value: true }); var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i['return']) _i['return'](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } }; })(); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x21, _x22, _x23) { var _again = true; _function: while (_again) { var object = _x21, property = _x22, receiver = _x23; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x21 = parent; _x22 = property; _x23 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _base = require('./base'); var _zlib = require('zlib'); var _zlib2 = _interopRequireDefault(_zlib); // lazy load C++ addon, in case we want this to work in browserify var callRest, parsers, freeParser; /** * CHIF client class * @extends baseClient */ var blobClient = (function (_baseClient) { _inherits(blobClient, _baseClient); /** * This class instance is initiated by helper function {@link restClient} or {@link redfishClient} */ function blobClient(baseUrl) { var userName = arguments.length <= 1 || arguments[1] === undefined ? '' : arguments[1]; var password = arguments.length <= 2 || arguments[2] === undefined ? '' : arguments[2]; var biosPassword = arguments.length <= 3 || arguments[3] === undefined ? null : arguments[3]; var sessionKey = arguments.length <= 4 || arguments[4] === undefined ? null : arguments[4]; var defaultPrefix = arguments.length <= 5 || arguments[5] === undefined ? '/rest/v1' : arguments[5]; var timeout = arguments.length <= 6 || arguments[6] === undefined ? 60 : arguments[6]; var concurrent = arguments.length <= 7 || arguments[7] === undefined ? 5 : arguments[7]; var cacheOptions = arguments.length <= 8 || arguments[8] === undefined ? null : arguments[8]; var isRedfish = arguments.length <= 9 || arguments[9] === undefined ? false : arguments[9]; var proxy = arguments.length <= 10 || arguments[10] === undefined ? null : arguments[10]; _classCallCheck(this, blobClient); _get(Object.getPrototypeOf(blobClient.prototype), 'constructor', this).call(this, baseUrl, userName, password, biosPassword, sessionKey, defaultPrefix, timeout, concurrent, cacheOptions, proxy); parsers = require('_http_common').parsers; freeParser = require('_http_common').freeParser; callRest = require('../../build/Release/addon').callRest; this.http_vsn_str = 'HTTP/1.1'; this.isRedfish = isRedfish; } _createClass(blobClient, [{ key: '__getReqHeaders', value: function __getReqHeaders(headers, providerHeader) { headers = _get(Object.getPrototypeOf(blobClient.prototype), '__getReqHeaders', this).call(this, headers, providerHeader); if (this.isRedfish) { headers['OData-Version'] = '4.0'; } return headers; } }, { key: '__formOptions', value: function __formOptions(path) { var method = arguments.length <= 1 || arguments[1] === undefined ? 'GET' : arguments[1]; var args = arguments.length <= 2 || arguments[2] === undefined ? null : arguments[2]; var body = arguments.length <= 3 || arguments[3] === undefined ? null : arguments[3]; var headers = arguments.length <= 4 || arguments[4] === undefined ? null : arguments[4]; var timeout = arguments.length <= 5 || arguments[5] === undefined ? null : arguments[5]; var optionalPassword = arguments.length <= 6 || arguments[6] === undefined ? null : arguments[6]; var providerHeader = arguments.length <= 7 || arguments[7] === undefined ? null : arguments[7]; if (!this.isRedfish && path && path.indexOf(this.defaultPrefix) >= 0 && path.charAt(path.length - 1) === '/') { path = path.slice(0, path.length - 1); } else if (this.isRedfish && path && path.indexOf(this.defaultPrefix) >= 0 && path.charAt(path.length - 1) !== '/') { path = path + '/'; } return _get(Object.getPrototypeOf(blobClient.prototype), '__formOptions', this).call(this, path, method, args, body, headers, timeout, optionalPassword, providerHeader); } }, { key: '__sendRequest', value: function __sendRequest(options, resolvePromise) { var headers = options.headers || {}; var requestPath = options.uri; var timeout = options.timeout; var packetString; var bodyBuffer; var reqBuffer; var HTTPParser = process.binding('http_parser').HTTPParser; var parser = parsers.alloc(); var originalMessageComplete = parser[HTTPParser.kOnMessageComplete]; var cResponse; if (options.qs && options.method === 'GET') { (function () { var queryString = []; Object.entries(options.qs).forEach(function (_ref) { var _ref2 = _slicedToArray(_ref, 2); var key = _ref2[0]; var value = _ref2[1]; queryString.push(encodeURIComponent(key) + '=' + encodeURIComponent(value)); }); requestPath = requestPath + '?' + queryString.join('&'); })(); } if (options.body != undefined || options.body != null) { var contentType = 'application/json'; if (Buffer.isBuffer(options.body)) { bodyBuffer = options.body; } else { var bodyString = undefined; try { bodyString = JSON.stringify(options.body); } catch (e) { bodyString = options.body.toString(); contentType = 'application/x-www-form-urlencoded'; } bodyBuffer = Buffer.from(bodyString); } headers['Content-Length'] = bodyBuffer.length; headers['Content-Type'] = contentType; } packetString = options.method + ' ' + requestPath + ' ' + this.http_vsn_str + '\r\nHost:\r\nAccept-Encoding: identity\r\n'; var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = Object.entries(headers)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var _step$value = _slicedToArray(_step.value, 2); var key = _step$value[0]; var value = _step$value[1]; packetString += key + ': ' + value + '\r\n'; } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator['return']) { _iterator['return'](); } } finally { if (_didIteratorError) { throw _iteratorError; } } } packetString += '\r\n'; packetString = Buffer.from(packetString); if (bodyBuffer) { reqBuffer = Buffer.concat([packetString, bodyBuffer], packetString.length + bodyBuffer.length); } else { reqBuffer = packetString; } function parse(buffer) { if (buffer.length > 0) { parser.execute(buffer, 0, buffer.length); } else { resolvePromise({ statusCode: 500, headers: {}, body: { error: 'Error from iLO channel' } }); } } function processResponse(res) { var buf = Buffer.concat(res.buffer, res.length); var finalResponse = ''; var jsonRes; try { if (res.statusCode >= 200 && res.statusCode < 300 && res.headers['content-encoding'] === 'gzip' && buf.length > 0) { var unzipBuf = _zlib2['default'].gunzipSync(buf); finalResponse = unzipBuf.toString(); } else { finalResponse = buf.toString(); } jsonRes = JSON.parse(finalResponse); } catch (err) { jsonRes = ''; } parser.finish(); freeParser(parser); resolvePromise({ statusCode: res.statusCode, headers: res.headers, body: jsonRes }); } parser.reinitialize(HTTPParser.RESPONSE); parser.onIncoming = function (res) { var buffers = []; var bufferLength = 0; res.on('data', function (chunk) { if (chunk.length) { bufferLength += chunk.length; buffers.push(chunk); } }); res.on('end', function () { processResponse({ statusCode: res.statusCode, headers: res.headers, buffer: buffers, length: bufferLength }); }); }; // TODO: Call C library here, mock the response here callRest(reqBuffer, reqBuffer.length, timeout, parse); } }, { key: 'login', value: function login() { var userName = arguments.length <= 0 || arguments[0] === undefined ? '' : arguments[0]; var _this = this; var password = arguments.length <= 1 || arguments[1] === undefined ? '' : arguments[1]; var auth = arguments.length <= 2 || arguments[2] === undefined ? _base.authMethod.SESSION : arguments[2]; return this.getRootObject().then(function (res) { _this.root = res.body; _this.loginUrl = _this.isRedfish ? _this.root.Links.Sessions['@odata.id'] : _this.root.links.Sessions.href; }).then(function () { return _this.__doLogin(userName, password, auth); }); } }]); return blobClient; })(_base.baseClient); exports.blobClient = blobClient;