services.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735
  1. /*jshint globalstrict:true */
  2. /*global angular:true */
  3. /*global Blob:false*/
  4. 'use strict';
  5. angular.module('kibana.services', [])
  6. .service('fields', function() {
  7. // Save a reference to this
  8. var self = this;
  9. this.list = [];
  10. this.add_fields = function(f) {
  11. self.list = _.union(f,self.list);
  12. };
  13. })
  14. .service('kbnIndex',function($http) {
  15. // returns a promise containing an array of all indices matching the index
  16. // pattern that exist in a given range
  17. this.indices = function(from,to,pattern,interval) {
  18. var possible = [];
  19. _.each(expand_range(fake_utc(from),fake_utc(to),interval),function(d){
  20. possible.push(d.format(pattern));
  21. });
  22. return all_indices().then(function(p) {
  23. var indices = _.intersection(possible,p);
  24. indices.reverse();
  25. return indices;
  26. });
  27. };
  28. // returns a promise containing an array of all indices in an elasticsearch
  29. // cluster
  30. function all_indices() {
  31. var something = $http({
  32. url: config.elasticsearch + "/_aliases",
  33. method: "GET"
  34. }).error(function(data, status, headers, config) {
  35. // Handle error condition somehow?
  36. });
  37. return something.then(function(p) {
  38. var indices = [];
  39. _.each(p.data, function(v,k) {
  40. indices.push(k);
  41. // Also add the aliases. Could be expensive on systems with a lot of them
  42. _.each(v.aliases, function(v, k) {
  43. indices.push(k);
  44. });
  45. });
  46. return indices;
  47. });
  48. }
  49. // this is stupid, but there is otherwise no good way to ensure that when
  50. // I extract the date from an object that I get the UTC date. Stupid js.
  51. // I die a little inside every time I call this function.
  52. // Update: I just read this again. I died a little more inside.
  53. // Update2: More death.
  54. function fake_utc(date) {
  55. date = moment(date).clone().toDate();
  56. return moment(new Date(date.getTime() + date.getTimezoneOffset() * 60000));
  57. }
  58. // Create an array of date objects by a given interval
  59. function expand_range(start, end, interval) {
  60. if(_.contains(['hour','day','week','month','year'],interval)) {
  61. var range;
  62. start = moment(start).clone();
  63. range = [];
  64. while (start.isBefore(end)) {
  65. range.push(start.clone());
  66. switch (interval) {
  67. case 'hour':
  68. start.add('hours',1);
  69. break;
  70. case 'day':
  71. start.add('days',1);
  72. break;
  73. case 'week':
  74. start.add('weeks',1);
  75. break;
  76. case 'month':
  77. start.add('months',1);
  78. break;
  79. case 'year':
  80. start.add('years',1);
  81. break;
  82. }
  83. }
  84. range.push(moment(end).clone());
  85. return range;
  86. } else {
  87. return false;
  88. }
  89. }
  90. })
  91. .service('timer', function($timeout) {
  92. // This service really just tracks a list of $timeout promises to give us a
  93. // method for cancelling them all when we need to
  94. var timers = [];
  95. this.register = function(promise) {
  96. timers.push(promise);
  97. return promise;
  98. };
  99. this.cancel = function(promise) {
  100. timers = _.without(timers,promise);
  101. $timeout.cancel(promise);
  102. };
  103. this.cancel_all = function() {
  104. _.each(timers, function(t){
  105. $timeout.cancel(t);
  106. });
  107. timers = [];
  108. };
  109. })
  110. .service('querySrv', function(dashboard, ejsResource) {
  111. // Create an object to hold our service state on the dashboard
  112. dashboard.current.services.query = dashboard.current.services.query || {};
  113. _.defaults(dashboard.current.services.query,{
  114. idQueue : [],
  115. list : {},
  116. ids : [],
  117. });
  118. // For convenience
  119. var ejs = ejsResource(config.elasticsearch);
  120. var _q = dashboard.current.services.query;
  121. this.colors = [
  122. "#7EB26D","#EAB839","#6ED0E0","#EF843C","#E24D42","#1F78C1","#BA43A9","#705DA0", //1
  123. "#508642","#CCA300","#447EBC","#C15C17","#890F02","#0A437C","#6D1F62","#584477", //2
  124. "#B7DBAB","#F4D598","#70DBED","#F9BA8F","#F29191","#82B5D8","#E5A8E2","#AEA2E0", //3
  125. "#629E51","#E5AC0E","#64B0C8","#E0752D","#BF1B00","#0A50A1","#962D82","#614D93", //4
  126. "#9AC48A","#F2C96D","#65C5DB","#F9934E","#EA6460","#5195CE","#D683CE","#806EB7", //5
  127. "#3F6833","#967302","#2F575E","#99440A","#58140C","#052B51","#511749","#3F2B5B", //6
  128. "#E0F9D7","#FCEACA","#CFFAFF","#F9E2D2","#FCE2DE","#BADFF4","#F9D9F9","#DEDAF7" //7
  129. ];
  130. // Save a reference to this
  131. var self = this;
  132. this.init = function() {
  133. _q = dashboard.current.services.query;
  134. self.list = dashboard.current.services.query.list;
  135. self.ids = dashboard.current.services.query.ids;
  136. if (self.ids.length === 0) {
  137. self.set({});
  138. }
  139. };
  140. // This is used both for adding queries and modifying them. If an id is passed, the query at that id is updated
  141. this.set = function(query,id) {
  142. if(!_.isUndefined(id)) {
  143. if(!_.isUndefined(self.list[id])) {
  144. _.extend(self.list[id],query);
  145. return id;
  146. } else {
  147. return false;
  148. }
  149. } else {
  150. var _id = nextId();
  151. var _query = {
  152. query: '*',
  153. alias: '',
  154. color: colorAt(_id),
  155. pin: false,
  156. id: _id,
  157. type: 'lucene'
  158. };
  159. _.defaults(query,_query);
  160. self.list[_id] = query;
  161. self.ids.push(_id);
  162. return _id;
  163. }
  164. };
  165. this.remove = function(id) {
  166. if(!_.isUndefined(self.list[id])) {
  167. delete self.list[id];
  168. // This must happen on the full path also since _.without returns a copy
  169. self.ids = dashboard.current.services.query.ids = _.without(self.ids,id);
  170. _q.idQueue.unshift(id);
  171. _q.idQueue.sort(function(v,k){
  172. return v-k;
  173. });
  174. return true;
  175. } else {
  176. return false;
  177. }
  178. };
  179. this.getEjsObj = function(id) {
  180. return self.toEjsObj(self.list[id]);
  181. };
  182. this.toEjsObj = function (q) {
  183. switch(q.type)
  184. {
  185. case 'lucene':
  186. return ejs.QueryStringQuery(q.query || '*');
  187. default:
  188. return _.isUndefined(q.query) ? false : ejs.QueryStringQuery(q.query || '*');
  189. }
  190. };
  191. this.findQuery = function(queryString) {
  192. return _.findWhere(self.list,{query:queryString});
  193. };
  194. this.idsByMode = function(config) {
  195. switch(config.mode)
  196. {
  197. case 'all':
  198. return self.ids;
  199. case 'pinned':
  200. return _.pluck(_.where(self.list,{pin:true}),'id');
  201. case 'selected':
  202. return _.intersection(self.ids,config.ids);
  203. default:
  204. return self.ids;
  205. }
  206. };
  207. var nextId = function() {
  208. if(_q.idQueue.length > 0) {
  209. return _q.idQueue.shift();
  210. } else {
  211. return self.ids.length;
  212. }
  213. };
  214. var colorAt = function(id) {
  215. return self.colors[id % self.colors.length];
  216. };
  217. self.init();
  218. })
  219. .service('filterSrv', function(dashboard, ejsResource) {
  220. // Create an object to hold our service state on the dashboard
  221. dashboard.current.services.filter = dashboard.current.services.filter || {};
  222. _.defaults(dashboard.current.services.filter,{
  223. idQueue : [],
  224. list : {},
  225. ids : []
  226. });
  227. // For convenience
  228. var ejs = ejsResource(config.elasticsearch);
  229. var _f = dashboard.current.services.filter;
  230. // Save a reference to this
  231. var self = this;
  232. // Call this whenever we need to reload the important stuff
  233. this.init = function() {
  234. // Accessors
  235. self.list = dashboard.current.services.filter.list;
  236. self.ids = dashboard.current.services.filter.ids;
  237. _f = dashboard.current.services.filter;
  238. _.each(self.getByType('time',true),function(time) {
  239. self.list[time.id].from = new Date(time.from);
  240. self.list[time.id].to = new Date(time.to);
  241. });
  242. };
  243. // This is used both for adding filters and modifying them.
  244. // If an id is passed, the filter at that id is updated
  245. this.set = function(filter,id) {
  246. _.defaults(filter,{mandate:'must'});
  247. filter.active = true;
  248. if(!_.isUndefined(id)) {
  249. if(!_.isUndefined(self.list[id])) {
  250. _.extend(self.list[id],filter);
  251. return id;
  252. } else {
  253. return false;
  254. }
  255. } else {
  256. if(_.isUndefined(filter.type)) {
  257. return false;
  258. } else {
  259. var _id = nextId();
  260. var _filter = {
  261. alias: '',
  262. id: _id
  263. };
  264. _.defaults(filter,_filter);
  265. self.list[_id] = filter;
  266. self.ids.push(_id);
  267. return _id;
  268. }
  269. }
  270. };
  271. this.getBoolFilter = function(ids) {
  272. // A default match all filter, just in case there are no other filters
  273. var bool = ejs.BoolFilter().must(ejs.MatchAllFilter());
  274. var either_bool = ejs.BoolFilter().must(ejs.MatchAllFilter());
  275. _.each(ids,function(id) {
  276. if(self.list[id].active) {
  277. switch(self.list[id].mandate)
  278. {
  279. case 'mustNot':
  280. bool = bool.mustNot(self.getEjsObj(id));
  281. break;
  282. case 'either':
  283. either_bool = either_bool.should(self.getEjsObj(id));
  284. break;
  285. default:
  286. bool = bool.must(self.getEjsObj(id));
  287. }
  288. }
  289. });
  290. return bool.must(either_bool);
  291. };
  292. this.getEjsObj = function(id) {
  293. return self.toEjsObj(self.list[id]);
  294. };
  295. this.toEjsObj = function (filter) {
  296. if(!filter.active) {
  297. return false;
  298. }
  299. switch(filter.type)
  300. {
  301. case 'time':
  302. return ejs.RangeFilter(filter.field)
  303. .from(filter.from.valueOf())
  304. .to(filter.to.valueOf());
  305. case 'range':
  306. return ejs.RangeFilter(filter.field)
  307. .from(filter.from)
  308. .to(filter.to);
  309. case 'querystring':
  310. return ejs.QueryFilter(ejs.QueryStringQuery(filter.query)).cache(true);
  311. case 'terms':
  312. return ejs.TermsFilter(filter.field,filter.value);
  313. case 'exists':
  314. return ejs.ExistsFilter(filter.field);
  315. case 'missing':
  316. return ejs.MissingFilter(filter.field);
  317. default:
  318. return false;
  319. }
  320. };
  321. this.getByType = function(type,inactive) {
  322. return _.pick(self.list,self.idsByType(type,inactive));
  323. };
  324. this.removeByType = function(type) {
  325. var ids = self.idsByType(type);
  326. _.each(ids,function(id) {
  327. self.remove(id);
  328. });
  329. return ids;
  330. };
  331. this.idsByType = function(type,inactive) {
  332. var _require = inactive ? {type:type} : {type:type,active:true};
  333. return _.pluck(_.where(self.list,_require),'id');
  334. };
  335. // This special function looks for all time filters, and returns a time range according to the mode
  336. this.timeRange = function(mode) {
  337. var _t = _.where(self.list,{type:'time',active:true});
  338. if(_t.length === 0) {
  339. return false;
  340. }
  341. switch(mode) {
  342. case "min":
  343. return {
  344. from: new Date(_.max(_.pluck(_t,'from'))),
  345. to: new Date(_.min(_.pluck(_t,'to')))
  346. };
  347. case "max":
  348. return {
  349. from: new Date(_.min(_.pluck(_t,'from'))),
  350. to: new Date(_.max(_.pluck(_t,'to')))
  351. };
  352. default:
  353. return false;
  354. }
  355. };
  356. this.remove = function(id) {
  357. if(!_.isUndefined(self.list[id])) {
  358. delete self.list[id];
  359. // This must happen on the full path also since _.without returns a copy
  360. self.ids = dashboard.current.services.filter.ids = _.without(self.ids,id);
  361. _f.idQueue.unshift(id);
  362. _f.idQueue.sort(function(v,k){return v-k;});
  363. return true;
  364. } else {
  365. return false;
  366. }
  367. };
  368. var nextId = function() {
  369. if(_f.idQueue.length > 0) {
  370. return _f.idQueue.shift();
  371. } else {
  372. return self.ids.length;
  373. }
  374. };
  375. // Now init
  376. self.init();
  377. })
  378. .service('dashboard', function($routeParams, $http, $rootScope, $injector, ejsResource, timer, kbnIndex) {
  379. // A hash of defaults to use when loading a dashboard
  380. var _dash = {
  381. title: "",
  382. editable: true,
  383. rows: [],
  384. services: {},
  385. index: {
  386. interval: 'none',
  387. pattern: '_all',
  388. default: '_all'
  389. },
  390. };
  391. // An elasticJS client to use
  392. var ejs = ejsResource(config.elasticsearch);
  393. var gist_pattern = /(^\d{5,}$)|(^[a-z0-9]{10,}$)|(gist.github.com(\/*.*)\/[a-z0-9]{5,}\/*$)/;
  394. // Store a reference to this
  395. var self = this;
  396. var filterSrv,querySrv;
  397. this.current = {};
  398. this.last = {};
  399. $rootScope.$on('$routeChangeSuccess',function(){
  400. // Clear the current dashboard to prevent reloading
  401. self.current = {};
  402. self.indices = [];
  403. route();
  404. });
  405. var route = function() {
  406. // Is there a dashboard type and id in the URL?
  407. if(!(_.isUndefined($routeParams.type)) && !(_.isUndefined($routeParams.id))) {
  408. var _type = $routeParams.type;
  409. var _id = $routeParams.id;
  410. switch(_type) {
  411. case ('elasticsearch'):
  412. self.elasticsearch_load('dashboard',_id);
  413. break;
  414. case ('temp'):
  415. self.elasticsearch_load('temp',_id);
  416. break;
  417. case ('file'):
  418. self.file_load(_id);
  419. break;
  420. default:
  421. self.file_load('default.json');
  422. }
  423. // No dashboard in the URL
  424. } else {
  425. // Check if browser supports localstorage, and if there's a dashboard
  426. if (window.Modernizr.localstorage &&
  427. !(_.isUndefined(window.localStorage['dashboard'])) &&
  428. window.localStorage['dashboard'] !== ''
  429. ) {
  430. var dashboard = JSON.parse(window.localStorage['dashboard']);
  431. _.defaults(dashboard,_dash);
  432. self.dash_load(dashboard);
  433. // No? Ok, grab default.json, its all we have now
  434. } else {
  435. self.file_load('default.json');
  436. }
  437. }
  438. };
  439. // Since the dashboard is responsible for index computation, we can compute and assign the indices
  440. // here before telling the panels to refresh
  441. this.refresh = function() {
  442. if(self.current.index.interval !== 'none') {
  443. if(filterSrv.idsByType('time').length > 0) {
  444. var _range = filterSrv.timeRange('min');
  445. kbnIndex.indices(_range.from,_range.to,
  446. self.current.index.pattern,self.current.index.interval
  447. ).then(function (p) {
  448. if(p.length > 0) {
  449. self.indices = p;
  450. } else {
  451. self.indices = [self.current.index.default];
  452. }
  453. $rootScope.$broadcast('refresh');
  454. });
  455. } else {
  456. // This is not optimal, we should be getting the entire index list here, or at least every
  457. // index that possibly matches the pattern
  458. self.indices = [self.current.index.default];
  459. $rootScope.$broadcast('refresh');
  460. }
  461. } else {
  462. self.indices = [self.current.index.default];
  463. $rootScope.$broadcast('refresh');
  464. }
  465. };
  466. this.dash_load = function(dashboard) {
  467. // Cancel all timers
  468. timer.cancel_all();
  469. // If not using time based indices, use the default index
  470. if(dashboard.index.interval === 'none') {
  471. self.indices = [dashboard.index.default];
  472. }
  473. self.current = _.clone(dashboard);
  474. // Ok, now that we've setup the current dashboard, we can inject our services
  475. querySrv = $injector.get('querySrv');
  476. filterSrv = $injector.get('filterSrv');
  477. // Make sure these re-init
  478. querySrv.init();
  479. filterSrv.init();
  480. if(dashboard.index.interval !== 'none' && filterSrv.idsByType('time').length === 0) {
  481. self.refresh();
  482. }
  483. return true;
  484. };
  485. this.gist_id = function(string) {
  486. if(self.is_gist(string)) {
  487. return string.match(gist_pattern)[0].replace(/.*\//, '');
  488. }
  489. };
  490. this.is_gist = function(string) {
  491. if(!_.isUndefined(string) && string !== '' && !_.isNull(string.match(gist_pattern))) {
  492. return string.match(gist_pattern).length > 0 ? true : false;
  493. } else {
  494. return false;
  495. }
  496. };
  497. this.to_file = function() {
  498. var blob = new Blob([angular.toJson(self.current,true)], {type: "application/json;charset=utf-8"});
  499. // from filesaver.js
  500. window.saveAs(blob, self.current.title+"-"+new Date().getTime());
  501. return true;
  502. };
  503. this.set_default = function(dashboard) {
  504. if (window.Modernizr.localstorage) {
  505. window.localStorage['dashboard'] = angular.toJson(dashboard || self.current);
  506. return true;
  507. } else {
  508. return false;
  509. }
  510. };
  511. this.purge_default = function() {
  512. if (window.Modernizr.localstorage) {
  513. window.localStorage['dashboard'] = '';
  514. return true;
  515. } else {
  516. return false;
  517. }
  518. };
  519. // TOFIX: Pretty sure this breaks when you're on a saved dashboard already
  520. this.share_link = function(title,type,id) {
  521. return {
  522. location : window.location.href.replace(window.location.hash,""),
  523. type : type,
  524. id : id,
  525. link : window.location.href.replace(window.location.hash,"")+"#dashboard/"+type+"/"+id,
  526. title : title
  527. };
  528. };
  529. this.file_load = function(file) {
  530. return $http({
  531. url: "dashboards/"+file,
  532. method: "GET",
  533. }).then(function(result) {
  534. var _dashboard = result.data;
  535. _.defaults(_dashboard,_dash);
  536. self.dash_load(_dashboard);
  537. return true;
  538. },function(result) {
  539. return false;
  540. });
  541. };
  542. this.elasticsearch_load = function(type,id) {
  543. var request = ejs.Request().indices(config.kibana_index).types(type);
  544. var results = request.query(
  545. ejs.IdsQuery(id)
  546. ).doSearch();
  547. return results.then(function(results) {
  548. if(_.isUndefined(results)) {
  549. return false;
  550. } else {
  551. self.dash_load(angular.fromJson(results.hits.hits[0]['_source']['dashboard']));
  552. return true;
  553. }
  554. });
  555. };
  556. this.elasticsearch_save = function(type,title,ttl) {
  557. // Clone object so we can modify it without influencing the existing obejct
  558. var save = _.clone(self.current);
  559. var id;
  560. // Change title on object clone
  561. if (type === 'dashboard') {
  562. id = save.title = _.isUndefined(title) ? self.current.title : title;
  563. }
  564. // Create request with id as title. Rethink this.
  565. var request = ejs.Document(config.kibana_index,type,id).source({
  566. user: 'guest',
  567. group: 'guest',
  568. title: save.title,
  569. dashboard: angular.toJson(save)
  570. });
  571. request = type === 'temp' && ttl ? request.ttl(ttl) : request;
  572. // TOFIX: Implement error handling here
  573. return request.doIndex(
  574. // Success
  575. function(result) {
  576. return result;
  577. },
  578. // Failure
  579. function(result) {
  580. return false;
  581. }
  582. );
  583. };
  584. this.elasticsearch_delete = function(id) {
  585. return ejs.Document(config.kibana_index,'dashboard',id).doDelete(
  586. // Success
  587. function(result) {
  588. return result;
  589. },
  590. // Failure
  591. function(result) {
  592. return false;
  593. }
  594. );
  595. };
  596. this.elasticsearch_list = function(query,count) {
  597. var request = ejs.Request().indices(config.kibana_index).types('dashboard');
  598. return request.query(
  599. ejs.QueryStringQuery(query || '*')
  600. ).size(count).doSearch(
  601. // Success
  602. function(result) {
  603. return result;
  604. },
  605. // Failure
  606. function(result) {
  607. return false;
  608. }
  609. );
  610. };
  611. // TOFIX: Gist functionality
  612. this.save_gist = function(title,dashboard) {
  613. var save = _.clone(dashboard || self.current);
  614. save.title = title || self.current.title;
  615. return $http({
  616. url: "https://api.github.com/gists",
  617. method: "POST",
  618. data: {
  619. "description": save.title,
  620. "public": false,
  621. "files": {
  622. "kibana-dashboard.json": {
  623. "content": angular.toJson(save,true)
  624. }
  625. }
  626. }
  627. }).then(function(data, status, headers, config) {
  628. return data.data.html_url;
  629. }, function(data, status, headers, config) {
  630. return false;
  631. });
  632. };
  633. this.gist_list = function(id) {
  634. return $http.jsonp("https://api.github.com/gists/"+id+"?callback=JSON_CALLBACK"
  635. ).then(function(response) {
  636. var files = [];
  637. _.each(response.data.data.files,function(v,k) {
  638. try {
  639. var file = JSON.parse(v.content);
  640. files.push(file);
  641. } catch(e) {
  642. // Nothing?
  643. }
  644. });
  645. return files;
  646. }, function(data, status, headers, config) {
  647. return false;
  648. });
  649. };
  650. });