services.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950
  1. /*jshint globalstrict:true, forin:false */
  2. /*global angular:true */
  3. /*global Blob:false*/
  4. 'use strict';
  5. angular.module('kibana.services', [])
  6. .service('alertSrv', function($timeout) {
  7. var self = this;
  8. // List of all alert objects
  9. this.list = [];
  10. this.set = function(title,text,severity,timeout) {
  11. var
  12. _a = {
  13. title: title || '',
  14. text: text || '',
  15. severity: severity || 'info',
  16. },
  17. _ca = angular.toJson(_a),
  18. _clist = _.map(self.list,function(alert){return angular.toJson(alert);});
  19. // If we already have this alert, remove it and add a new one
  20. // Why do this instead of skipping the add because it resets the timer
  21. if(_.contains(_clist,_ca)) {
  22. _.remove(self.list,_.indexOf(_clist,_ca));
  23. }
  24. self.list.push(_a);
  25. if (timeout > 0) {
  26. $timeout(function() {
  27. self.list = _.without(self.list,_a);
  28. }, timeout);
  29. }
  30. };
  31. this.clear = function(alert) {
  32. self.list = _.without(self.list,alert);
  33. };
  34. this.clearAll = function() {
  35. self.list = [];
  36. };
  37. })
  38. .service('fields', function(dashboard, $rootScope, $http, alertSrv) {
  39. // Save a reference to this
  40. var self = this;
  41. this.list = ['_type'];
  42. this.mapping = {};
  43. this.add_fields = function(f) {
  44. //self.list = _.union(f,self.list);
  45. };
  46. $rootScope.$watch(function(){return dashboard.indices;},function(n) {
  47. if(!_.isUndefined(n) && n.length) {
  48. // Only get the mapping for indices we don't know it for
  49. var indices = _.difference(n,_.keys(self.mapping));
  50. // Only get the mapping if there are indices
  51. if(indices.length > 0) {
  52. self.map(indices).then(function(result) {
  53. self.mapping = _.extend(self.mapping,result);
  54. self.list = mapFields(self.mapping);
  55. });
  56. // Otherwise just use the cached mapping
  57. } else {
  58. self.list = mapFields(_.pick(self.mapping,n));
  59. }
  60. }
  61. });
  62. var mapFields = function (m) {
  63. var fields = [];
  64. _.each(m, function(types,index) {
  65. _.each(types, function(v,k) {
  66. fields = _.union(fields,_.keys(v));
  67. });
  68. });
  69. return fields;
  70. };
  71. this.map = function(indices) {
  72. var request = $http({
  73. url: config.elasticsearch + "/" + indices.join(',') + "/_mapping",
  74. method: "GET"
  75. }).error(function(data, status, headers, conf) {
  76. if(status === 0) {
  77. alertSrv.set('Error',"Could not contact Elasticsearch at "+config.elasticsearch+
  78. ". Please ensure that Elasticsearch is reachable from your system." ,'error');
  79. } else {
  80. alertSrv.set('Error',"Could not find "+config.elasticsearch+"/"+indices.join(',')+"/_mapping. If you"+
  81. " are using a proxy, ensure it is configured correctly",'error');
  82. }
  83. });
  84. return request.then(function(p) {
  85. var mapping = {};
  86. _.each(p.data, function(v,k) {
  87. mapping[k] = {};
  88. _.each(v, function (v,f) {
  89. mapping[k][f] = flatten(v);
  90. });
  91. });
  92. return mapping;
  93. });
  94. };
  95. var flatten = function(obj,prefix) {
  96. var propName = (prefix) ? prefix : '',
  97. dot = (prefix) ? '.':'',
  98. ret = {};
  99. for(var attr in obj){
  100. // For now only support multi field on the top level
  101. // and if if there is a default field set.
  102. if(obj[attr]['type'] === 'multi_field') {
  103. ret[attr] = obj[attr]['fields'][attr] || obj[attr];
  104. continue;
  105. }
  106. if (attr === 'properties') {
  107. _.extend(ret,flatten(obj[attr], propName));
  108. } else if(typeof obj[attr] === 'object'){
  109. _.extend(ret,flatten(obj[attr], propName + dot + attr));
  110. } else {
  111. ret[propName] = obj;
  112. }
  113. }
  114. return ret;
  115. };
  116. })
  117. .service('kbnIndex',function($http,alertSrv) {
  118. // returns a promise containing an array of all indices matching the index
  119. // pattern that exist in a given range
  120. this.indices = function(from,to,pattern,interval) {
  121. var possible = [];
  122. _.each(expand_range(fake_utc(from),fake_utc(to),interval),function(d){
  123. possible.push(d.format(pattern));
  124. });
  125. return all_indices().then(function(p) {
  126. var indices = _.intersection(possible,p);
  127. indices.reverse();
  128. return indices;
  129. });
  130. };
  131. // returns a promise containing an array of all indices in an elasticsearch
  132. // cluster
  133. function all_indices() {
  134. var something = $http({
  135. url: config.elasticsearch + "/_aliases",
  136. method: "GET"
  137. }).error(function(data, status, headers, conf) {
  138. if(status === 0) {
  139. alertSrv.set('Error',"Could not contact Elasticsearch at "+config.elasticsearch+
  140. ". Please ensure that Elasticsearch is reachable from your system." ,'error');
  141. } else {
  142. alertSrv.set('Error',"Could not reach "+config.elasticsearch+"/_aliases. If you"+
  143. " are using a proxy, ensure it is configured correctly",'error');
  144. }
  145. });
  146. return something.then(function(p) {
  147. var indices = [];
  148. _.each(p.data, function(v,k) {
  149. indices.push(k);
  150. // Also add the aliases. Could be expensive on systems with a lot of them
  151. _.each(v.aliases, function(v, k) {
  152. indices.push(k);
  153. });
  154. });
  155. return indices;
  156. });
  157. }
  158. // this is stupid, but there is otherwise no good way to ensure that when
  159. // I extract the date from an object that I get the UTC date. Stupid js.
  160. // I die a little inside every time I call this function.
  161. // Update: I just read this again. I died a little more inside.
  162. // Update2: More death.
  163. function fake_utc(date) {
  164. date = moment(date).clone().toDate();
  165. return moment(new Date(date.getTime() + date.getTimezoneOffset() * 60000));
  166. }
  167. // Create an array of date objects by a given interval
  168. function expand_range(start, end, interval) {
  169. if(_.contains(['hour','day','week','month','year'],interval)) {
  170. var range;
  171. start = moment(start).clone();
  172. range = [];
  173. while (start.isBefore(end)) {
  174. range.push(start.clone());
  175. switch (interval) {
  176. case 'hour':
  177. start.add('hours',1);
  178. break;
  179. case 'day':
  180. start.add('days',1);
  181. break;
  182. case 'week':
  183. start.add('weeks',1);
  184. break;
  185. case 'month':
  186. start.add('months',1);
  187. break;
  188. case 'year':
  189. start.add('years',1);
  190. break;
  191. }
  192. }
  193. range.push(moment(end).clone());
  194. return range;
  195. } else {
  196. return false;
  197. }
  198. }
  199. })
  200. .service('timer', function($timeout) {
  201. // This service really just tracks a list of $timeout promises to give us a
  202. // method for cancelling them all when we need to
  203. var timers = [];
  204. this.register = function(promise) {
  205. timers.push(promise);
  206. return promise;
  207. };
  208. this.cancel = function(promise) {
  209. timers = _.without(timers,promise);
  210. $timeout.cancel(promise);
  211. };
  212. this.cancel_all = function() {
  213. _.each(timers, function(t){
  214. $timeout.cancel(t);
  215. });
  216. timers = [];
  217. };
  218. })
  219. .service('querySrv', function(dashboard, ejsResource) {
  220. // Create an object to hold our service state on the dashboard
  221. dashboard.current.services.query = dashboard.current.services.query || {};
  222. _.defaults(dashboard.current.services.query,{
  223. idQueue : [],
  224. list : {},
  225. ids : [],
  226. });
  227. // Defaults for query objects
  228. var _query = {
  229. query: '*',
  230. alias: '',
  231. pin: false,
  232. type: 'lucene'
  233. };
  234. // For convenience
  235. var ejs = ejsResource(config.elasticsearch);
  236. var _q = dashboard.current.services.query;
  237. this.colors = [
  238. "#7EB26D","#EAB839","#6ED0E0","#EF843C","#E24D42","#1F78C1","#BA43A9","#705DA0", //1
  239. "#508642","#CCA300","#447EBC","#C15C17","#890F02","#0A437C","#6D1F62","#584477", //2
  240. "#B7DBAB","#F4D598","#70DBED","#F9BA8F","#F29191","#82B5D8","#E5A8E2","#AEA2E0", //3
  241. "#629E51","#E5AC0E","#64B0C8","#E0752D","#BF1B00","#0A50A1","#962D82","#614D93", //4
  242. "#9AC48A","#F2C96D","#65C5DB","#F9934E","#EA6460","#5195CE","#D683CE","#806EB7", //5
  243. "#3F6833","#967302","#2F575E","#99440A","#58140C","#052B51","#511749","#3F2B5B", //6
  244. "#E0F9D7","#FCEACA","#CFFAFF","#F9E2D2","#FCE2DE","#BADFF4","#F9D9F9","#DEDAF7" //7
  245. ];
  246. // Save a reference to this
  247. var self = this;
  248. this.init = function() {
  249. _q = dashboard.current.services.query;
  250. self.list = dashboard.current.services.query.list;
  251. self.ids = dashboard.current.services.query.ids;
  252. // Check each query object, populate its defaults
  253. _.each(self.list,function(query,id) {
  254. _.defaults(query,_query);
  255. query.color = colorAt(id);
  256. });
  257. if (self.ids.length === 0) {
  258. self.set({});
  259. }
  260. };
  261. // This is used both for adding queries and modifying them. If an id is passed, the query at that id is updated
  262. this.set = function(query,id) {
  263. if(!_.isUndefined(id)) {
  264. if(!_.isUndefined(self.list[id])) {
  265. _.extend(self.list[id],query);
  266. return id;
  267. } else {
  268. return false;
  269. }
  270. } else {
  271. var _id = query.id || nextId();
  272. query.id = _id;
  273. query.color = query.color || colorAt(_id);
  274. _.defaults(query,_query);
  275. self.list[_id] = query;
  276. self.ids.push(_id);
  277. return _id;
  278. }
  279. };
  280. this.remove = function(id) {
  281. if(!_.isUndefined(self.list[id])) {
  282. delete self.list[id];
  283. // This must happen on the full path also since _.without returns a copy
  284. self.ids = dashboard.current.services.query.ids = _.without(self.ids,id);
  285. _q.idQueue.unshift(id);
  286. _q.idQueue.sort(function(v,k){
  287. return v-k;
  288. });
  289. return true;
  290. } else {
  291. return false;
  292. }
  293. };
  294. this.getEjsObj = function(id) {
  295. return self.toEjsObj(self.list[id]);
  296. };
  297. this.toEjsObj = function (q) {
  298. switch(q.type)
  299. {
  300. case 'lucene':
  301. return ejs.QueryStringQuery(q.query || '*');
  302. default:
  303. return _.isUndefined(q.query) ? false : ejs.QueryStringQuery(q.query || '*');
  304. }
  305. };
  306. this.findQuery = function(queryString) {
  307. return _.findWhere(self.list,{query:queryString});
  308. };
  309. this.idsByMode = function(config) {
  310. switch(config.mode)
  311. {
  312. case 'all':
  313. return self.ids;
  314. case 'pinned':
  315. return _.pluck(_.where(self.list,{pin:true}),'id');
  316. case 'unpinned':
  317. return _.difference(self.ids,_.pluck(_.where(self.list,{pin:true}),'id'));
  318. case 'selected':
  319. return _.intersection(self.ids,config.ids);
  320. default:
  321. return self.ids;
  322. }
  323. };
  324. var nextId = function() {
  325. if(_q.idQueue.length > 0) {
  326. return _q.idQueue.shift();
  327. } else {
  328. return self.ids.length;
  329. }
  330. };
  331. var colorAt = function(id) {
  332. return self.colors[id % self.colors.length];
  333. };
  334. self.init();
  335. })
  336. .service('filterSrv', function(dashboard, ejsResource) {
  337. // Create an object to hold our service state on the dashboard
  338. dashboard.current.services.filter = dashboard.current.services.filter || {};
  339. // Defaults for it
  340. var _d = {
  341. idQueue : [],
  342. list : {},
  343. ids : []
  344. };
  345. // For convenience
  346. var ejs = ejsResource(config.elasticsearch);
  347. var _f = dashboard.current.services.filter;
  348. // Save a reference to this
  349. var self = this;
  350. // Call this whenever we need to reload the important stuff
  351. this.init = function() {
  352. // Populate defaults
  353. _.defaults(dashboard.current.services.filter,_d);
  354. // Accessors
  355. self.list = dashboard.current.services.filter.list;
  356. self.ids = dashboard.current.services.filter.ids;
  357. _f = dashboard.current.services.filter;
  358. _.each(self.getByType('time',true),function(time) {
  359. self.list[time.id].from = new Date(time.from);
  360. self.list[time.id].to = new Date(time.to);
  361. });
  362. };
  363. // This is used both for adding filters and modifying them.
  364. // If an id is passed, the filter at that id is updated
  365. this.set = function(filter,id) {
  366. _.defaults(filter,{mandate:'must'});
  367. filter.active = true;
  368. if(!_.isUndefined(id)) {
  369. if(!_.isUndefined(self.list[id])) {
  370. _.extend(self.list[id],filter);
  371. return id;
  372. } else {
  373. return false;
  374. }
  375. } else {
  376. if(_.isUndefined(filter.type)) {
  377. return false;
  378. } else {
  379. var _id = nextId();
  380. var _filter = {
  381. alias: '',
  382. id: _id
  383. };
  384. _.defaults(filter,_filter);
  385. self.list[_id] = filter;
  386. self.ids.push(_id);
  387. return _id;
  388. }
  389. }
  390. };
  391. this.getBoolFilter = function(ids) {
  392. // A default match all filter, just in case there are no other filters
  393. var bool = ejs.BoolFilter().must(ejs.MatchAllFilter());
  394. var either_bool = ejs.BoolFilter().must(ejs.MatchAllFilter());
  395. _.each(ids,function(id) {
  396. if(self.list[id].active) {
  397. switch(self.list[id].mandate)
  398. {
  399. case 'mustNot':
  400. bool = bool.mustNot(self.getEjsObj(id));
  401. break;
  402. case 'either':
  403. either_bool = either_bool.should(self.getEjsObj(id));
  404. break;
  405. default:
  406. bool = bool.must(self.getEjsObj(id));
  407. }
  408. }
  409. });
  410. return bool.must(either_bool);
  411. };
  412. this.getEjsObj = function(id) {
  413. return self.toEjsObj(self.list[id]);
  414. };
  415. this.toEjsObj = function (filter) {
  416. if(!filter.active) {
  417. return false;
  418. }
  419. switch(filter.type)
  420. {
  421. case 'time':
  422. return ejs.RangeFilter(filter.field)
  423. .from(filter.from.valueOf())
  424. .to(filter.to.valueOf());
  425. case 'range':
  426. return ejs.RangeFilter(filter.field)
  427. .from(filter.from)
  428. .to(filter.to);
  429. case 'querystring':
  430. return ejs.QueryFilter(ejs.QueryStringQuery(filter.query)).cache(true);
  431. case 'field':
  432. return ejs.QueryFilter(ejs.FieldQuery(filter.field,filter.query)).cache(true);
  433. case 'terms':
  434. return ejs.TermsFilter(filter.field,filter.value);
  435. case 'exists':
  436. return ejs.ExistsFilter(filter.field);
  437. case 'missing':
  438. return ejs.MissingFilter(filter.field);
  439. default:
  440. return false;
  441. }
  442. };
  443. this.getByType = function(type,inactive) {
  444. return _.pick(self.list,self.idsByType(type,inactive));
  445. };
  446. this.removeByType = function(type) {
  447. var ids = self.idsByType(type);
  448. _.each(ids,function(id) {
  449. self.remove(id);
  450. });
  451. return ids;
  452. };
  453. this.idsByType = function(type,inactive) {
  454. var _require = inactive ? {type:type} : {type:type,active:true};
  455. return _.pluck(_.where(self.list,_require),'id');
  456. };
  457. // TOFIX: Error handling when there is more than one field
  458. this.timeField = function() {
  459. return _.pluck(self.getByType('time'),'field');
  460. };
  461. // This special function looks for all time filters, and returns a time range according to the mode
  462. // No idea when max would actually be used
  463. this.timeRange = function(mode) {
  464. var _t = _.where(self.list,{type:'time',active:true});
  465. if(_t.length === 0) {
  466. return false;
  467. }
  468. switch(mode) {
  469. case "min":
  470. return {
  471. from: new Date(_.max(_.pluck(_t,'from'))),
  472. to: new Date(_.min(_.pluck(_t,'to')))
  473. };
  474. case "max":
  475. return {
  476. from: new Date(_.min(_.pluck(_t,'from'))),
  477. to: new Date(_.max(_.pluck(_t,'to')))
  478. };
  479. default:
  480. return false;
  481. }
  482. };
  483. this.remove = function(id) {
  484. if(!_.isUndefined(self.list[id])) {
  485. delete self.list[id];
  486. // This must happen on the full path also since _.without returns a copy
  487. self.ids = dashboard.current.services.filter.ids = _.without(self.ids,id);
  488. _f.idQueue.unshift(id);
  489. _f.idQueue.sort(function(v,k){return v-k;});
  490. return true;
  491. } else {
  492. return false;
  493. }
  494. };
  495. var nextId = function() {
  496. if(_f.idQueue.length > 0) {
  497. return _f.idQueue.shift();
  498. } else {
  499. return self.ids.length;
  500. }
  501. };
  502. // Now init
  503. self.init();
  504. })
  505. .service('dashboard', function($routeParams, $http, $rootScope, $injector, ejsResource, timer, kbnIndex, alertSrv) {
  506. // A hash of defaults to use when loading a dashboard
  507. var _dash = {
  508. title: "",
  509. style: "dark",
  510. editable: true,
  511. failover: false,
  512. rows: [],
  513. services: {},
  514. index: {
  515. interval: 'none',
  516. pattern: '_all',
  517. default: 'INDEX_MISSING'
  518. },
  519. };
  520. // An elasticJS client to use
  521. var ejs = ejsResource(config.elasticsearch);
  522. var gist_pattern = /(^\d{5,}$)|(^[a-z0-9]{10,}$)|(gist.github.com(\/*.*)\/[a-z0-9]{5,}\/*$)/;
  523. // Store a reference to this
  524. var self = this;
  525. var filterSrv,querySrv;
  526. this.current = _.clone(_dash);
  527. this.last = {};
  528. $rootScope.$on('$routeChangeSuccess',function(){
  529. // Clear the current dashboard to prevent reloading
  530. self.current = {};
  531. self.indices = [];
  532. route();
  533. });
  534. var route = function() {
  535. // Is there a dashboard type and id in the URL?
  536. if(!(_.isUndefined($routeParams.kbnType)) && !(_.isUndefined($routeParams.kbnId))) {
  537. var _type = $routeParams.kbnType;
  538. var _id = $routeParams.kbnId;
  539. switch(_type) {
  540. case ('elasticsearch'):
  541. self.elasticsearch_load('dashboard',_id);
  542. break;
  543. case ('temp'):
  544. self.elasticsearch_load('temp',_id);
  545. break;
  546. case ('file'):
  547. self.file_load(_id);
  548. break;
  549. case('script'):
  550. self.script_load(_id);
  551. break;
  552. default:
  553. self.file_load('default.json');
  554. }
  555. // No dashboard in the URL
  556. } else {
  557. // Check if browser supports localstorage, and if there's a dashboard
  558. if (window.Modernizr.localstorage &&
  559. !(_.isUndefined(window.localStorage['dashboard'])) &&
  560. window.localStorage['dashboard'] !== ''
  561. ) {
  562. var dashboard = JSON.parse(window.localStorage['dashboard']);
  563. self.dash_load(dashboard);
  564. // No? Ok, grab default.json, its all we have now
  565. } else {
  566. self.file_load('default.json');
  567. }
  568. }
  569. };
  570. // Since the dashboard is responsible for index computation, we can compute and assign the indices
  571. // here before telling the panels to refresh
  572. this.refresh = function() {
  573. if(self.current.index.interval !== 'none') {
  574. if(filterSrv.idsByType('time').length > 0) {
  575. var _range = filterSrv.timeRange('min');
  576. kbnIndex.indices(_range.from,_range.to,
  577. self.current.index.pattern,self.current.index.interval
  578. ).then(function (p) {
  579. if(p.length > 0) {
  580. self.indices = p;
  581. } else {
  582. //TODO: Option to not failover
  583. if(self.current.failover) {
  584. self.indices = [self.current.index.default];
  585. } else {
  586. // Do not issue refresh if no indices match. This should be removed when panels
  587. // properly understand when no indices are present
  588. return false;
  589. }
  590. }
  591. $rootScope.$broadcast('refresh');
  592. });
  593. } else {
  594. if(self.current.failover) {
  595. self.indices = [self.current.index.default];
  596. $rootScope.$broadcast('refresh');
  597. } else {
  598. alertSrv.set("No time filter",
  599. 'Timestamped indices are configured without a failover. Waiting for time filter.',
  600. 'info',5000);
  601. }
  602. }
  603. } else {
  604. self.indices = [self.current.index.default];
  605. $rootScope.$broadcast('refresh');
  606. }
  607. };
  608. this.dash_load = function(dashboard) {
  609. // Cancel all timers
  610. timer.cancel_all();
  611. // Make sure the dashboard being loaded has everything required
  612. _.defaults(dashboard,_dash);
  613. // If not using time based indices, use the default index
  614. if(dashboard.index.interval === 'none') {
  615. self.indices = [dashboard.index.default];
  616. }
  617. self.current = _.clone(dashboard);
  618. // Ok, now that we've setup the current dashboard, we can inject our services
  619. querySrv = $injector.get('querySrv');
  620. filterSrv = $injector.get('filterSrv');
  621. // Make sure these re-init
  622. querySrv.init();
  623. filterSrv.init();
  624. // If there's an index interval set and no existing time filter, send a refresh to set one
  625. if(dashboard.index.interval !== 'none' && filterSrv.idsByType('time').length === 0) {
  626. self.refresh();
  627. }
  628. return true;
  629. };
  630. this.gist_id = function(string) {
  631. if(self.is_gist(string)) {
  632. return string.match(gist_pattern)[0].replace(/.*\//, '');
  633. }
  634. };
  635. this.is_gist = function(string) {
  636. if(!_.isUndefined(string) && string !== '' && !_.isNull(string.match(gist_pattern))) {
  637. return string.match(gist_pattern).length > 0 ? true : false;
  638. } else {
  639. return false;
  640. }
  641. };
  642. this.to_file = function() {
  643. var blob = new Blob([angular.toJson(self.current,true)], {type: "application/json;charset=utf-8"});
  644. // from filesaver.js
  645. window.saveAs(blob, self.current.title+"-"+new Date().getTime());
  646. return true;
  647. };
  648. this.set_default = function(dashboard) {
  649. if (window.Modernizr.localstorage) {
  650. window.localStorage['dashboard'] = angular.toJson(dashboard || self.current);
  651. return true;
  652. } else {
  653. return false;
  654. }
  655. };
  656. this.purge_default = function() {
  657. if (window.Modernizr.localstorage) {
  658. window.localStorage['dashboard'] = '';
  659. return true;
  660. } else {
  661. return false;
  662. }
  663. };
  664. // TOFIX: Pretty sure this breaks when you're on a saved dashboard already
  665. this.share_link = function(title,type,id) {
  666. return {
  667. location : window.location.href.replace(window.location.hash,""),
  668. type : type,
  669. id : id,
  670. link : window.location.href.replace(window.location.hash,"")+"#dashboard/"+type+"/"+id,
  671. title : title
  672. };
  673. };
  674. var renderTemplate = function(json,params) {
  675. var _r;
  676. _.templateSettings = {interpolate : /\{\{(.+?)\}\}/g};
  677. var template = _.template(json);
  678. var rendered = template({ARGS:params});
  679. try {
  680. _r = angular.fromJson(rendered);
  681. } catch(e) {
  682. _r = false;
  683. }
  684. return _r;
  685. };
  686. this.file_load = function(file) {
  687. return $http({
  688. url: "dashboards/"+file,
  689. method: "GET",
  690. transformResponse: function(response) {
  691. return renderTemplate(response,$routeParams);
  692. }
  693. }).then(function(result) {
  694. if(!result) {
  695. return false;
  696. }
  697. var _dashboard = result.data;
  698. _.defaults(_dashboard,_dash);
  699. self.dash_load(_dashboard);
  700. return true;
  701. },function(result) {
  702. alertSrv.set('Error',"Could not load <i>dashboards/"+file+"</i>. Please make sure it exists" ,'error');
  703. return false;
  704. });
  705. };
  706. this.elasticsearch_load = function(type,id) {
  707. return $http({
  708. url: config.elasticsearch + "/" + config.kibana_index + "/"+type+"/"+id,
  709. method: "GET",
  710. transformResponse: function(response) {
  711. return renderTemplate(angular.fromJson(response)['_source']['dashboard'],$routeParams);
  712. }
  713. }).error(function(data, status, headers, conf) {
  714. if(status === 0) {
  715. alertSrv.set('Error',"Could not contact Elasticsearch at "+config.elasticsearch+
  716. ". Please ensure that Elasticsearch is reachable from your system." ,'error');
  717. } else {
  718. alertSrv.set('Error',"Could not find "+id+". If you"+
  719. " are using a proxy, ensure it is configured correctly",'error');
  720. }
  721. return false;
  722. }).success(function(data, status, headers) {
  723. self.dash_load(data);
  724. });
  725. };
  726. this.script_load = function(file) {
  727. return $http({
  728. url: "dashboards/"+file,
  729. method: "GET",
  730. transformResponse: function(response) {
  731. /*jshint -W054 */
  732. var _f = new Function("ARGS",response);
  733. return _f($routeParams);
  734. }
  735. }).then(function(result) {
  736. if(!result) {
  737. return false;
  738. }
  739. var _dashboard = result.data;
  740. _.defaults(_dashboard,_dash);
  741. self.dash_load(_dashboard);
  742. return true;
  743. },function(result) {
  744. alertSrv.set('Error',
  745. "Could not load <i>scripts/"+file+"</i>. Please make sure it exists and returns a valid dashboard" ,
  746. 'error');
  747. return false;
  748. });
  749. };
  750. this.elasticsearch_save = function(type,title,ttl) {
  751. // Clone object so we can modify it without influencing the existing obejct
  752. var save = _.clone(self.current);
  753. var id;
  754. // Change title on object clone
  755. if (type === 'dashboard') {
  756. id = save.title = _.isUndefined(title) ? self.current.title : title;
  757. }
  758. // Create request with id as title. Rethink this.
  759. var request = ejs.Document(config.kibana_index,type,id).source({
  760. user: 'guest',
  761. group: 'guest',
  762. title: save.title,
  763. dashboard: angular.toJson(save)
  764. });
  765. request = type === 'temp' && ttl ? request.ttl(ttl) : request;
  766. return request.doIndex(
  767. // Success
  768. function(result) {
  769. return result;
  770. },
  771. // Failure
  772. function(result) {
  773. return false;
  774. }
  775. );
  776. };
  777. this.elasticsearch_delete = function(id) {
  778. return ejs.Document(config.kibana_index,'dashboard',id).doDelete(
  779. // Success
  780. function(result) {
  781. return result;
  782. },
  783. // Failure
  784. function(result) {
  785. return false;
  786. }
  787. );
  788. };
  789. this.elasticsearch_list = function(query,count) {
  790. var request = ejs.Request().indices(config.kibana_index).types('dashboard');
  791. return request.query(
  792. ejs.QueryStringQuery(query || '*')
  793. ).size(count).doSearch(
  794. // Success
  795. function(result) {
  796. return result;
  797. },
  798. // Failure
  799. function(result) {
  800. return false;
  801. }
  802. );
  803. };
  804. // TOFIX: Gist functionality
  805. this.save_gist = function(title,dashboard) {
  806. var save = _.clone(dashboard || self.current);
  807. save.title = title || self.current.title;
  808. return $http({
  809. url: "https://api.github.com/gists",
  810. method: "POST",
  811. data: {
  812. "description": save.title,
  813. "public": false,
  814. "files": {
  815. "kibana-dashboard.json": {
  816. "content": angular.toJson(save,true)
  817. }
  818. }
  819. }
  820. }).then(function(data, status, headers, config) {
  821. return data.data.html_url;
  822. }, function(data, status, headers, config) {
  823. return false;
  824. });
  825. };
  826. this.gist_list = function(id) {
  827. return $http.jsonp("https://api.github.com/gists/"+id+"?callback=JSON_CALLBACK"
  828. ).then(function(response) {
  829. var files = [];
  830. _.each(response.data.data.files,function(v,k) {
  831. try {
  832. var file = JSON.parse(v.content);
  833. files.push(file);
  834. } catch(e) {
  835. // Nothing?
  836. }
  837. });
  838. return files;
  839. }, function(data, status, headers, config) {
  840. return false;
  841. });
  842. };
  843. });