UNPKG

splunk-sdk

Version:

SDK for usage with the Splunk REST API

1,334 lines (1,182 loc) 1.88 MB
(function() { var __exportName = 'splunkjs'; (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){ /*! * $script.js JS loader & dependency manager * https://github.com/ded/script.js * (c) Dustin Diaz 2014 | License MIT */ (function(e,t){typeof module!="undefined"&&module.exports?module.exports=t():typeof define=="function"&&define.amd?define(t):this[e]=t()})("$script",function(){function p(e,t){for(var n=0,i=e.length;n<i;++n)if(!t(e[n]))return r;return 1}function d(e,t){p(e,function(e){return t(e),1})}function v(e,t,n){function g(e){return e.call?e():u[e]}function y(){if(!--h){u[o]=1,s&&s();for(var e in f)p(e.split("|"),g)&&!d(f[e],g)&&(f[e]=[])}}e=e[i]?e:[e];var r=t&&t.call,s=r?t:n,o=r?e.join(""):t,h=e.length;return setTimeout(function(){d(e,function t(e,n){if(e===null)return y();!n&&!/^https?:\/\//.test(e)&&c&&(e=e.indexOf(".js")===-1?c+e+".js":c+e);if(l[e])return o&&(a[o]=1),l[e]==2?y():setTimeout(function(){t(e,!0)},0);l[e]=1,o&&(a[o]=1),m(e,y)})},0),v}function m(n,r){var i=e.createElement("script"),u;i.onload=i.onerror=i[o]=function(){if(i[s]&&!/^c|loade/.test(i[s])||u)return;i.onload=i[o]=null,u=1,l[n]=2,r()},i.async=1,i.src=h?n+(n.indexOf("?")===-1?"?":"&")+h:n,t.insertBefore(i,t.lastChild)}var e=document,t=e.getElementsByTagName("head")[0],n="string",r=!1,i="push",s="readyState",o="onreadystatechange",u={},a={},f={},l={},c,h;return v.get=m,v.order=function(e,t,n){(function r(i){i=e.shift(),e.length?v(i,r):v(i,t,n)})()},v.path=function(e){c=e},v.urlArgs=function(e){h=e},v.ready=function(e,t,n){e=e[i]?e:[e];var r=[];return!d(e,function(e){u[e]||r[i](e)})&&p(e,function(e){return u[e]})?t():!function(e){f[e]=f[e]||[],f[e][i](t),n&&n(r)}(e.join("|")),v},v.done=function(e){v([null],e)},v}) },{}],2:[function(require,module,exports){ (function (process){(function (){ // Copyright 2011 Splunk, Inc. // // 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. (function() { var root = exports || this; var env = require("dotenv").config(); // Declare a process environment so that we can set // some globals here and have interop with node try { process.env = process.env || {}; } catch (e) { // Depending on the browser implementation process.env may not // be assignable but still accessible, ignore these errors } module.exports = root = { Logger : require('./lib/log').Logger, Context : require('./lib/context'), Service : require('./lib/service'), Http : require('./lib/http'), Utils : require('./lib/utils'), Paths : require('./lib/paths').Paths, Class : require('./lib/jquery.class').Class }; if (typeof(window) === 'undefined') { root.NodeHttp = require('./lib/platform/node/node_http').NodeHttp; } else { let jqueryHttp = require('./lib/platform/client/jquery_http').JQueryHttp; let proxyHttps = require('./lib/platform/client/proxy_http'); root.ProxyHttp = proxyHttps.ProxyHttp; root.JQueryHttp = jqueryHttp; root.SplunkWebHttp = proxyHttps.SplunkWebHttp; } })(); }).call(this)}).call(this,require('_process')) },{"./lib/context":3,"./lib/http":6,"./lib/jquery.class":7,"./lib/log":8,"./lib/paths":9,"./lib/platform/client/jquery_http":10,"./lib/platform/client/proxy_http":11,"./lib/platform/node/node_http":12,"./lib/service":13,"./lib/utils":14,"_process":205,"dotenv":94}],3:[function(require,module,exports){ /*!*/ // Copyright 2012 Splunk, Inc. // // 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. (function() { "use strict"; var Paths = require('./paths').Paths; var Class = require('./jquery.class').Class; var Http = require('./http'); var utils = require('./utils'); var root = exports || this; var prefixMap = { "5": "", "4.3": "/services/json/v2", "default": "" }; /** * An abstraction over the Splunk HTTP-wire protocol that provides the basic * functionality for communicating with a Splunk instance over HTTP, handles * authentication and authorization, and formats HTTP requests (GET, POST, * and DELETE) in the format that Splunk expects. * * @class splunkjs.Context */ module.exports = root = Class.extend({ /** * Constructor for `splunkjs.Context`. * * @constructor * @param {splunkjs.Http} http An instance of a `splunkjs.Http` class. * @param {Object} params A dictionary of optional parameters: * - `scheme` (_string_): The scheme ("http" or "https") for accessing Splunk. * - `host` (_string_): The host name (the default is "localhost"). * - `port` (_integer_): The port number (the default is 8089). * - `username` (_string_): The Splunk account username, which is used to authenticate the Splunk instance. * - `password` (_string_): The password, which is used to authenticate the Splunk instance. * - `owner` (_string_): The owner (username) component of the namespace. * - `app` (_string_): The app component of the namespace. * - `sessionKey` (_string_): The current session token. * - `autologin` (_boolean_): `true` to automatically try to log in again if the session terminates, `false` if not (`true` by default). * - 'timeout' (_integer): The connection timeout in milliseconds. ('0' by default). * - `version` (_string_): The version string for Splunk, for example "4.3.2" (the default is "5.0"). * @return {splunkjs.Context} A new `splunkjs.Context` instance. * * @method splunkjs.Context */ init: function(http, params) { if (!(http instanceof Http) && !params) { // Move over the params params = http; http = null; } params = params || {}; this.scheme = params.scheme || "https"; this.host = params.host || "localhost"; this.port = params.port || 8089; this.username = params.username || null; this.password = params.password || null; this.owner = params.owner; this.app = params.app; this.sessionKey = params.sessionKey || ""; this.authorization = params.authorization || "Splunk"; this.paths = params.paths || Paths; this.version = params.version || "default"; this.timeout = params.timeout || 0; this.autologin = true; this.instanceType = ""; // Initialize autologin // The reason we explicitly check to see if 'autologin' // is actually set is because we need to distinguish the // case of it being set to 'false', and it not being set. // Unfortunately, in JavaScript, these are both false-y if (params.hasOwnProperty("autologin")) { this.autologin = params.autologin; } if (!http) { // If there is no HTTP implementation set, we check what platform // we're running on. If we're running in the browser, then complain, // else, we instantiate NodeHttp. if (typeof(window) !== 'undefined') { throw new Error("Http instance required when creating a Context within a browser."); } else { let NodeHttp = require('./platform/node/node_http').NodeHttp; http = new NodeHttp(); } } // Store the HTTP implementation this.http = http; this.http._setSplunkVersion(this.version); // Store our full prefix, which is just combining together // the scheme with the host let versionPrefix = utils.getWithVersion(this.version, prefixMap); this.prefix = this.scheme + "://" + this.host + ":" + this.port + versionPrefix; // We perform the bindings so that every function works properly this._headers = utils.bind(this, this._headers); this.fullpath = utils.bind(this, this.fullpath); this.urlify = utils.bind(this, this.urlify); this.get = utils.bind(this, this.get); this.del = utils.bind(this, this.del); this.post = utils.bind(this, this.post); this.login = utils.bind(this, this.login); this._shouldAutoLogin = utils.bind(this, this._shouldAutoLogin); this._requestWrapper = utils.bind(this, this._requestWrapper); this.getInfo = utils.bind(this, this.getInfo); this.disableV2SearchApi = utils.bind(this, this.disableV2SearchApi); }, /** * Appends Splunk-specific headers. * * @param {Object} headers A dictionary of headers (optional). * @return {Object} An augmented dictionary of headers. * * @method splunkjs.Context * @private */ _headers: function (headers) { headers = headers || {}; if (this.sessionKey) { headers["Authorization"] = this.authorization + " " + this.sessionKey; } return headers; }, /*!*/ _shouldAutoLogin: function() { return this.username && this.password && this.autologin; }, /*!*/ /** * This internal function aids with the autologin feature. * It takes one parameters: `task`, which is a function describing an * HTTP request. * * @param {Function} task A function with no arguments which returns a promise. */ _requestWrapper:function (task){ var that = this; if (!this._shouldAutoLogin() || this.sessionKey) { // Since we are not auto-logging in, just execute our task, // but intercept any 401s so we can login then return task().then((res)=>{ return res; }) .catch((err)=>{ if(err && err.status===401 && that._shouldAutoLogin()){ that.sessionKey = null; return that.login().then((response)=>{ return task(); }).catch((error)=>{ throw error; }); } throw err; }); } return this.login() .then((res)=>{ return task(); }) .catch((err)=>{ throw err; }); }, /** * Converts a partial path to a fully-qualified path to a REST endpoint, * and if necessary includes the namespace owner and app. * * @param {String} path The partial path. * @param {String} namespace The namespace, in the format "_owner_/_app_". * @return {String} The fully-qualified path. * * @method splunkjs.Context */ fullpath: function(path, namespace) { namespace = namespace || {}; if (utils.startsWith(path, "/")) { return path; } // If we don't have an app name (explicitly or implicitly), we default to /services/ if (!namespace.app && !this.app && namespace.sharing !== root.Sharing.SYSTEM) { return "/services/" + path; } // Get the app and owner, first from the passed in namespace, then the service, // finally defaulting to wild cards let owner = namespace.owner || this.owner || "-"; let app = namespace.app || this.app || "-"; namespace.sharing = (namespace.sharing || "").toLowerCase(); // Modify the owner and app appropriately based on the sharing parameter if (namespace.sharing === root.Sharing.APP || namespace.sharing === root.Sharing.GLOBAL) { owner = "nobody"; } else if (namespace.sharing === root.Sharing.SYSTEM) { owner = "nobody"; app = "system"; } return utils.trim("/servicesNS/" + encodeURIComponent(owner) + "/" + encodeURIComponent(app) + "/" + path); }, /** * Converts a partial path to a fully-qualified URL. * * @param {String} path The partial path. * @return {String} The fully-qualified URL. * * @method splunkjs.Context * @private */ urlify: function(path) { return this.prefix + this.fullpath(path); }, /** * Get Splunk version during login phase. * * @param {Number} response_timeout A timeout period for aborting a request in milisecs (0 means no timeout). * * @method splunkjs.Context * @private */ getInfo: function (response_timeout) { var that = this; let url = this.paths.info; return this.http.get( this.urlify(url), this._headers(), "", this.timeout, response_timeout ).then((response)=>{ let hasVersion = !!(response.data && response.data.generator.version); let hasInstanceType = !!(response.data && response.data.generator["instance_type"]); if (!hasVersion) { return Promise.reject("No version found"); } else{ that.instanceType = hasInstanceType ? response.data.generator["instance_type"] : ""; that.version = response.data.generator.version; that.http.version = that.version; return Promise.resolve(true); } }); }, /** * Authenticates and logs in to a Splunk instance, then stores the * resulting session key. * * @param {Number} response_timeout A timeout period for aborting a request in milisecs (0 means no timeout). * * @method splunkjs.Context * @private */ login: function(response_timeout) { var that = this; let url = this.paths.login; let params = { username: this.username, password: this.password, cookie : '1' }; return this.http.post( this.urlify(url), this._headers(), params, this.timeout, response_timeout ).then((response)=>{ let hasSessionKey = !!(response.data && response.data.sessionKey); if (!hasSessionKey) { return Promise.reject("No session key available"); } else { that.sessionKey = response.data.sessionKey; return that.getInfo(); } }) }, /** * Logs the session out resulting in the removal of all cookies and the * session key. * * @method splunkjs.Context * @private */ logout: function() { this.sessionKey = null; this.http._cookieStore = {}; }, /** * Performs a GET request. * * @param {String} path The REST endpoint path of the GET request. * @param {Object} params The entity-specific parameters for this request. * @param {Number} response_timeout A timeout period for aborting a request in milisecs (0 means no timeout). * * @method splunkjs.Context */ get: function(path, params, response_timeout, isAsync) { var that = this; if(isAsync) { return that.http.get( that.urlify(path), that._headers(), params, that.timeout, response_timeout, true ); } else { let request = function() { return that.http.get( that.urlify(path), that._headers(), params, that.timeout, response_timeout ); }; return this._requestWrapper(request); } }, /** * Performs a DELETE request. * * @param {String} path The REST endpoint path of the DELETE request. * @param {Object} params The entity-specific parameters for this request. * @param {Number} response_timeout A timeout period for aborting a request in milisecs (0 means no timeout). * @method splunkjs.Context */ del: function(path, params,response_timeout) { var that = this; let request = function() { return that.http.del( that.urlify(path), that._headers(), params, that.timeout, response_timeout ); }; return this._requestWrapper(request); }, /** * Performs a POST request. * * @param {String} path The REST endpoint path of the POST request. * @param {Object} params The entity-specific parameters for this request. * @param {Number} response_timeout A timeout period for aborting a request in milisecs (0 means no timeout). * @method splunkjs.Context */ post: function(path, params, response_timeout) { var that = this; let request = function() { return that.http.post( that.urlify(path), that._headers(), params, that.timeout, response_timeout ); }; return this._requestWrapper(request); }, /** * Issues an arbitrary HTTP request to the REST endpoint path segment. * * @param {String} path The REST endpoint path segment (with any query parameters already appended and encoded). * @param {String} method The HTTP method (can be `GET`, `POST`, or `DELETE`). * @param {Object} query The entity-specific parameters for this request. * @param {Object} post A dictionary of POST argument that will get form encoded. * @param {Object} body The body of the request, mutually exclusive with `post`. * @param {Object} headers Headers for this request. * @param {Number} response_timeout A timeout period for aborting a request in milisecs (0 means no timeout). * * @method splunkjs.Context */ request: function(path, method, query, post, body, headers,response_timeout) { var that = this; let request = function() { return that.http.request( that.urlify(path), { method: method, headers: that._headers(headers), query: query, post: post, body: body, timeout: that.timeout } ,response_timeout); }; return this._requestWrapper(request); }, /** * Compares the Splunk server's version to the specified version string. * Returns -1 if (this.version < otherVersion), * 0 if (this.version == otherVersion), * 1 if (this.version > otherVersion). * * @param {String} otherVersion The other version string, for example "5.0". * * @method splunkjs.Context */ versionCompare: function (otherVersion) { let thisVersion = this.version; if (thisVersion === "default") { thisVersion = "5.0"; } let components1 = thisVersion.split("."); let components2 = otherVersion.split("."); let numComponents = Math.max(components1.length, components2.length); for (let i = 0; i < numComponents; i++) { let c1 = (i < components1.length) ? parseInt(components1[i], 10) : 0; let c2 = (i < components2.length) ? parseInt(components2[i], 10) : 0; if (c1 < c2) { return -1; } else if (c1 > c2) { return 1; } } return 0; }, disableV2SearchApi: function(){ let val; if(this.instanceType.toLowerCase() == "cloud"){ val = this.versionCompare("9.0.2209"); }else{ val = this.versionCompare("9.0.2") } return val < 0; } }); /*!*/ root.Sharing = { USER: "user", APP: "app", GLOBAL: "global", SYSTEM: "system" }; })(); },{"./http":6,"./jquery.class":7,"./paths":9,"./platform/node/node_http":12,"./utils":14}],4:[function(require,module,exports){ // Copyright 2011 Splunk, Inc. // // 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. // This file is the entry point for client-side code, so it "exports" the // important functionality to the "window", such that others can easily // include it. (function(exportName) { var previousSplunk = window[exportName]; var ourSplunk = require('../../index'); var jqueryHttp = require('../../lib/platform/client/jquery_http').JQueryHttp; var proxyHttps = require('../../lib/platform/client/proxy_http'); var proxyHttp = proxyHttps.ProxyHttp; var splunkwebHttp = proxyHttps.SplunkWebHttp; window[exportName] = ourSplunk; window[exportName].ProxyHttp = proxyHttp; window[exportName].JQueryHttp = jqueryHttp; window[exportName].SplunkWebHttp = splunkwebHttp; // Add no conflict capabilities window[exportName].noConflict = function(name) { // Reset the window[exportName] reference window[exportName] = previousSplunk; return ourSplunk; }; // Load the UI component loader require("../../lib/entries/browser.ui.entry"); })(__exportName); },{"../../index":2,"../../lib/entries/browser.ui.entry":5,"../../lib/platform/client/jquery_http":10,"../../lib/platform/client/proxy_http":11}],5:[function(require,module,exports){ // Copyright 2011 Splunk, Inc. // // 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. // This file is the entry point for client-side code, so it "exports" the // important functionality to the "window", such that others can easily // include it. (function(exportName) { var $script = require('../../contrib/script'); if (!window[exportName]) { window[exportName] = {}; } if (!window[exportName].UI) { window[exportName].UI = {}; } var UI = window[exportName].UI; var root = exports || this; var token = 0; var loadComponent = function(path, token, callback) { if (!path) { throw new Error("Must specify a path to load from."); } callback = callback || function() {}; $script(path, token, callback); }; UI.loadTimeline = function(path, callback) { var timelineToken = 'timeline' + (token++); loadComponent(path, timelineToken, callback); return timelineToken; }; UI.loadCharting = function(path, callback) { var chartToken = 'charting' + (token++); loadComponent(path, chartToken, callback); return chartToken; }; UI.load = function(paths, callback) { if (!paths) { throw new Error("Must specify paths to load components from"); } callback = callback || function() {}; var token = "all" + (token++); $script(paths, token, function() { callback(); }); return token; }; UI.ready = function(token, callback) { callback = callback || function() {}; $script.ready(token, callback); }; })(__exportName); },{"../../contrib/script":1}],6:[function(require,module,exports){ /*!*/ // Copyright 2012 Splunk, Inc. // // 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. (function() { "use strict"; var Class = require('./jquery.class').Class; var logger = require('./log').Logger; var utils = require('./utils'); var CookieHandler = require('cookie'); var root = exports || this; var Http = null; var queryBuilderMap = { "5": function(message) { var query = message.query || {}; var post = message.post || {}; var outputMode = query.output_mode || post.output_mode || "json"; query.output_mode = outputMode; return query; }, "4": function(message) { return message.query || {}; }, "default": function(message) { return queryBuilderMap["5"](message); }, "none": function(message) { return message.query || {}; } }; /** * A base class for HTTP abstraction that provides the basic functionality * for performing GET, POST, DELETE, and REQUEST operations, and provides * utilities to construct uniform responses. * * Base classes should only override `makeRequest` and `parseJSON`. * * @class splunkjs.Http */ module.exports = root = Http = Class.extend({ /** * Constructor for `splunkjs.Http`. * * @constructor * @return {splunkjs.Http} A new `splunkjs.Http` instance. * * @method splunkjs.Http */ init: function() { // We perform the bindings so that every function works properly this.get = utils.bind(this, this.get); this.del = utils.bind(this, this.del); this.post = utils.bind(this, this.post); this.request = utils.bind(this, this.request); this._buildResponse = utils.bind(this, this._buildResponse); // Set our default version to "none" this._setSplunkVersion("none"); // Cookie store for cookie based authentication. this._cookieStore = {}; }, /*!*/ _setSplunkVersion: function(version) { this.version = version; }, /** * Returns all cookies formatted as a string to be put into the Cookie Header. */ _getCookieString: function() { let cookieString = ""; utils.forEach(this._cookieStore, function (cookieValue, cookieKey) { cookieString += cookieKey; cookieString += '='; cookieString += cookieValue; cookieString += '; '; }); return cookieString; }, /** * Takes a cookie header and returns an object of form { key: $cookieKey value: $cookieValue } */ _parseCookieHeader: function(cookieHeader) { // Returns an object of form { $cookieKey: $cookieValue, $optionalCookieAttributeName: $""value, ... } let parsedCookieObject = CookieHandler.parse(cookieHeader); let cookie = {}; // This gets the first key value pair into an object and just repeatedly returns thereafter utils.forEach(parsedCookieObject, function(cookieValue, cookieKey) { if(cookie.key) { return; } cookie.key = cookieKey; cookie.value = cookieValue; }); return cookie; }, /** * Performs a GET request. * * @param {String} url The URL of the GET request. * @param {Object} headers An object of headers for this request. * @param {Object} params Parameters for this request. * @param {Number} timeout A timeout period. * @param {Number} response_timeout A timeout period for aborting a request in milisecs (0 means no timeout). * * @method splunkjs.Http */ get: function(url, headers, params, timeout, response_timeout, isAsync) { let message = { method: "GET", headers: headers, timeout: timeout, response_timeout: response_timeout, query: params, }; return this.request(url, message, isAsync); }, /** * Performs a POST request. * * @param {String} url The URL of the POST request. * @param {Object} headers An object of headers for this request. * @param {Object} params Parameters for this request. * @param {Number} timeout A timeout period. * @param {Number} response_timeout A timeout period for aborting a request in milisecs (0 means no timeout). * * @method splunkjs.Http */ post: function(url, headers, params, timeout, response_timeout) { headers["Content-Type"] = "application/x-www-form-urlencoded"; let message = { method: "POST", headers: headers, timeout: timeout, response_timeout: response_timeout, post: params }; return this.request(url, message); }, /** * Performs a DELETE request. * * @param {String} url The URL of the DELETE request. * @param {Object} headers An object of headers for this request. * @param {Object} params Query parameters for this request. * @param {Number} timeout A timeout period. * @param {Number} response_timeout A timeout period for aborting a request in milisecs (0 means no timeout). * * @method splunkjs.Http */ del: function(url, headers, params, timeout, response_timeout) { let message = { method: "DELETE", headers: headers, timeout: timeout, response_timeout: response_timeout, query: params }; return this.request(url, message); }, /** * Performs a request. * * This function sets up how to handle a response from a request, but * delegates calling the request to the `makeRequest` subclass. * * @param {String} url The encoded URL of the request. * @param {Object} message An object with values for method, headers, timeout, and encoded body. * * @method splunkjs.Http * @see makeRequest */ request: function(url, message, isAsync) { var that = this; let query = utils.getWithVersion(this.version, queryBuilderMap)(message); let post = message.post || {}; let encodedUrl = url + "?" + Http.encode(query); let body = message.body ? message.body : Http.encode(post); let cookieString = that._getCookieString(); if (cookieString.length !== 0) { message.headers["Cookie"] = cookieString; } let options = { method: message.method, headers: message.headers, timeout: message.timeout, response_timeout: message.response_timeout, query: message.query, body: body }; if(isAsync) { return this.makeRequestAsync(encodedUrl, options); } else { let res = this.makeRequest(encodedUrl, options); return res.then((response) => { if(!response){ return; } // Handle cookies if 'set-cookie' header is in the response let cookieHeaders = response.response.headers['set-cookie']; if (cookieHeaders) { utils.forEach(cookieHeaders, function (cookieHeader) { let cookie = that._parseCookieHeader(cookieHeader); that._cookieStore[cookie.key] = cookie.value; }); } if (response.status < 400 && response.status !== "abort") { return response; } else { throw response; } }).catch((error) => { throw error; }); } }, /** * Encapsulates the client-specific logic for performing a request. This * function is meant to be overriden by subclasses. * * @param {String} url The encoded URL of the request. * @param {Object} message An object with values for method, headers, timeout, and encoded body. * * @method splunkjs.Http */ makeRequest: function(url, message) { throw new Error("UNDEFINED FUNCTION - OVERRIDE REQUIRED"); }, /** * Encapsulates the client-specific logic for parsing the JSON response. * * @param {String} json The JSON response to parse. * @return {Object} The parsed JSON. * * @method splunkjs.Http */ parseJson: function(json) { throw new Error("UNDEFINED FUNCTION - OVERRIDE REQUIRED"); }, /** * Generates a unified response with the given parameters. * * @param {Object} error An error object, if one exists for the request. * @param {Object} response The response object. * @param {Object} data The response data. * @return {Object} A unified response object. * * @method splunkjs.Http */ _buildResponse: function(error, response, data) { let complete_response, json = {}; let contentType = null; if (response && response.headers) { contentType = utils.trim(response.headers["content-type"] || response.headers["Content-Type"] || response.headers["Content-type"] || response.headers["contentType"]); } if (utils.startsWith(contentType, "application/json") && data) { try { json = this.parseJson(data) || {}; } catch(e) { logger.error("Error in parsing JSON:", data, e); json = data; } } else { json = data; } if (json) { logger.printMessages(json.messages); } complete_response = { response: response, status: (response ? response.statusCode : 0), data: json, error: error }; return complete_response; } }); /** * Encodes a dictionary of values into a URL-encoded format. * * @example * * // should be a=1&b=2&b=3&b=4 * encode({a: 1, b: [2,3,4]}) * * @param {Object} params The parameters to URL encode. * @return {String} The URL-encoded string. * * @function splunkjs.Http */ Http.encode = function(params) { let encodedStr = ""; // We loop over all the keys so we encode them. for (let key in params) { if (params.hasOwnProperty(key)) { // Only append the ampersand if we already have // something encoded, and the last character isn't // already an ampersand if (encodedStr && encodedStr[encodedStr.length - 1] !== "&") { encodedStr = encodedStr + "&"; } // Get the value let value = params[key]; // If it's an array, we loop over each value // and encode it in the form &key=value[i] if (value instanceof Array) { for (let i = 0; i < value.length; i++) { encodedStr = encodedStr + key + "=" + encodeURIComponent(value[i]) + "&"; } } else if (typeof value === "object") { for(let innerKey in value) { if (value.hasOwnProperty(innerKey)) { let innerValue = value[innerKey]; encodedStr = encodedStr + key + "=" + encodeURIComponent(value[innerKey]) + "&"; } } } else { // If it's not an array, we just encode it encodedStr = encodedStr + key + "=" + encodeURIComponent(value); } } } if (encodedStr[encodedStr.length - 1] === '&') { encodedStr = encodedStr.substr(0, encodedStr.length - 1); } return encodedStr; }; })(); },{"./jquery.class":7,"./log":8,"./utils":14,"cookie":75}],7:[function(require,module,exports){ /*! Simple JavaScript Inheritance * By John Resig http://ejohn.org/ * MIT Licensed. * Inspired by base2 and Prototype */ (function(){ var root = exports || this; var initializing = false; var fnTest = (/xyz/.test(function() { return xyz; }) ? /\b_super\b/ : /.*/); // The base Class implementation (does nothing) root.Class = function(){}; // Create a new Class that inherits from this class root.Class.extend = function(prop) { var _super = this.prototype; // Instantiate a base class (but only create the instance, // don't run the init constructor) initializing = true; var prototype = new this(); initializing = false; // Copy the properties over onto the new prototype for (var name in prop) { // Check if we're overwriting an existing function prototype[name] = typeof prop[name] == "function" && typeof _super[name] == "function" && fnTest.test(prop[name]) ? (function(name, fn){ return function() { var tmp = this._super; // Add a new ._super() method that is the same method // but on the super-class this._super = _super[name]; // The method only need to be bound temporarily, so we // remove it when we're done executing var ret = fn.apply(this, arguments); this._super = tmp; return ret; }; })(name, prop[name]) : prop[name]; } // The dummy class constructor function Class() { // All construction is actually done in the init method if ( !initializing && this.init ) this.init.apply(this, arguments); } // Populate our constructed prototype object Class.prototype = prototype; // Enforce the constructor to be what we expect Class.constructor = Class; // And make this class extendable Class.extend = arguments.callee; return Class; }; })(); },{}],8:[function(require,module,exports){ (function (process){(function (){ /*!*/ // Copyright 2012 Splunk, Inc. // // 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. (function() { "use strict"; var utils = require('./utils'); var root = exports || this; var levels = { "ALL": 4, "INFO": 3, "WARN": 2, "ERROR": 1, "NONE": 0 }; // Normalize the value of the environment variable $LOG_LEVEL to // an integer (look up named levels like "ERROR" in levels above), // and default to "ERROR" if there is no value or an invalid value // set. var setLevel = function(level) { if (utils.isString(level) && levels.hasOwnProperty(level)) { process.env.LOG_LEVEL = levels[level]; } else if (!isNaN(parseInt(level, 10)) && utils.keyOf(parseInt(level, 10), levels)) { process.env.LOG_LEVEL = level; } else { process.env.LOG_LEVEL = levels["ERROR"]; } }; if (process.env.LOG_LEVEL) { setLevel(process.env.LOG_LEVEL); } else { process.env.LOG_LEVEL = levels["ERROR"]; } // Set the actual output functions // This section is not covered by unit tests, since there's no // straightforward way to control what the console object will be. var _log, _warn, _error, _info; _log = _warn = _error = _info = function() {}; if (typeof(console) !== "undefined") { var logAs = function(level) { return function(str) { try { console[level].apply(console, arguments); } catch(ex) { console[level](str); } }; }; if (console.log) { _log = logAs("log"); } if (console.error) { _error = logAs("error"); } if (console.warn) { _warn = logAs("warn"); } if (console.info) { _info = logAs("info"); } } /** * A controllable logging module that lets you display different types of * debugging information to the console. * * @module splunkjs.Logger */ exports.Logger = { /** * Logs debug messages to the console. This function is the same as * `console.log`. * * @function splunkjs.Logger */ log: function() { if (process.env.LOG_LEVEL >= levels.ALL) { _log.apply(null, arguments); } }, /** * Logs debug errors to the console. This function is the same as * `console.error`. * * @function splunkjs.Logger */ error: function() { if (process.env.LOG_LEVEL >= levels.ERROR) { _error.apply(null, arguments); } }, /** * Logs debug warnings to the console. This function is the same as * `console.warn`. * * @function splunkjs.Logger */ warn: function() { if (process.env.LOG_LEVEL >= levels.WARN) { _warn.apply(null, arguments); } }, /** * Logs debug info to the console. This function is the same as * `console.info`. * * @function splunkjs.Logger */ info: function() { if (process.env.LOG_LEVEL >= levels.INFO) { _info.apply(null, arguments); } }, /** * Prints all messages that are retrieved from the splunkd server to the * console. * * @function splunkjs.Logger */ printMessages: function(allMessages) { allMessages = allMessages || []; for(var i = 0; i < allMessages.length; i++) { var message = allMessages[i]; var type = message["type"]; var text = message["text"]; var msg = '[SPLUNKD] ' + text; switch (type) { case 'HTTP': case 'FATAL': case 'ERROR': this.error(msg); break; case 'WARN': this.warn(msg); break; case 'INFO': this.info(msg); break; case 'HTTP': this.error(msg); break; default: this.info(msg); break; } } }, /** * Sets the global logging level to indicate which information to log. * * @example * * splunkjs.Logger.setLevel("WARN"); * splunkjs.Logger.setLevel(0); // equivalent to NONE * * @param {String|Number} level A string or number ("ALL" = 4 | "INFO" = 3 | "WARN" = 2 | "ERROR" = 1 | "NONE" = 0) indicating the logging level. * * @function splunkjs.Logger */ setLevel: function(level) { setLevel.apply(this, arguments); }, /*!*/ levels: levels }; })(); }).call(this)}).call(this,require('_process')) },{"./utils":14,"_process":205}],9:[function(require,module,exports){ /*!*/ // Copyright 2012 Splunk, Inc. // // 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 // //