services.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  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 = ['_type'];
  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 'unpinned':
  202. return _.difference(self.ids,_.pluck(_.where(self.list,{pin:true}),'id'));
  203. case 'selected':
  204. return _.intersection(self.ids,config.ids);
  205. default:
  206. return self.ids;
  207. }
  208. };
  209. var nextId = function() {
  210. if(_q.idQueue.length > 0) {
  211. return _q.idQueue.shift();
  212. } else {
  213. return self.ids.length;
  214. }
  215. };
  216. var colorAt = function(id) {
  217. return self.colors[id % self.colors.length];
  218. };
  219. self.init();
  220. })
  221. .service('filterSrv', function(dashboard, ejsResource) {
  222. // Create an object to hold our service state on the dashboard
  223. dashboard.current.services.filter = dashboard.current.services.filter || {};
  224. _.defaults(dashboard.current.services.filter,{
  225. idQueue : [],
  226. list : {},
  227. ids : []
  228. });
  229. // For convenience
  230. var ejs = ejsResource(config.elasticsearch);
  231. var _f = dashboard.current.services.filter;
  232. // Save a reference to this
  233. var self = this;
  234. // Call this whenever we need to reload the important stuff
  235. this.init = function() {
  236. // Accessors
  237. self.list = dashboard.current.services.filter.list;
  238. self.ids = dashboard.current.services.filter.ids;
  239. _f = dashboard.current.services.filter;
  240. _.each(self.getByType('time',true),function(time) {
  241. self.list[time.id].from = new Date(time.from);
  242. self.list[time.id].to = new Date(time.to);
  243. });
  244. };
  245. // This is used both for adding filters and modifying them.
  246. // If an id is passed, the filter at that id is updated
  247. this.set = function(filter,id) {
  248. _.defaults(filter,{mandate:'must'});
  249. filter.active = true;
  250. if(!_.isUndefined(id)) {
  251. if(!_.isUndefined(self.list[id])) {
  252. _.extend(self.list[id],filter);
  253. return id;
  254. } else {
  255. return false;
  256. }
  257. } else {
  258. if(_.isUndefined(filter.type)) {
  259. return false;
  260. } else {
  261. var _id = nextId();
  262. var _filter = {
  263. alias: '',
  264. id: _id
  265. };
  266. _.defaults(filter,_filter);
  267. self.list[_id] = filter;
  268. self.ids.push(_id);
  269. return _id;
  270. }
  271. }
  272. };
  273. this.getBoolFilter = function(ids) {
  274. // A default match all filter, just in case there are no other filters
  275. var bool = ejs.BoolFilter().must(ejs.MatchAllFilter());
  276. var either_bool = ejs.BoolFilter().must(ejs.MatchAllFilter());
  277. _.each(ids,function(id) {
  278. if(self.list[id].active) {
  279. switch(self.list[id].mandate)
  280. {
  281. case 'mustNot':
  282. bool = bool.mustNot(self.getEjsObj(id));
  283. break;
  284. case 'either':
  285. either_bool = either_bool.should(self.getEjsObj(id));
  286. break;
  287. default:
  288. bool = bool.must(self.getEjsObj(id));
  289. }
  290. }
  291. });
  292. return bool.must(either_bool);
  293. };
  294. this.getEjsObj = function(id) {
  295. return self.toEjsObj(self.list[id]);
  296. };
  297. this.toEjsObj = function (filter) {
  298. if(!filter.active) {
  299. return false;
  300. }
  301. switch(filter.type)
  302. {
  303. case 'time':
  304. return ejs.RangeFilter(filter.field)
  305. .from(filter.from.valueOf())
  306. .to(filter.to.valueOf());
  307. case 'range':
  308. return ejs.RangeFilter(filter.field)
  309. .from(filter.from)
  310. .to(filter.to);
  311. case 'querystring':
  312. return ejs.QueryFilter(ejs.QueryStringQuery(filter.query)).cache(true);
  313. case 'terms':
  314. return ejs.TermsFilter(filter.field,filter.value);
  315. case 'exists':
  316. return ejs.ExistsFilter(filter.field);
  317. case 'missing':
  318. return ejs.MissingFilter(filter.field);
  319. default:
  320. return false;
  321. }
  322. };
  323. this.getByType = function(type,inactive) {
  324. return _.pick(self.list,self.idsByType(type,inactive));
  325. };
  326. this.removeByType = function(type) {
  327. var ids = self.idsByType(type);
  328. _.each(ids,function(id) {
  329. self.remove(id);
  330. });
  331. return ids;
  332. };
  333. this.idsByType = function(type,inactive) {
  334. var _require = inactive ? {type:type} : {type:type,active:true};
  335. return _.pluck(_.where(self.list,_require),'id');
  336. };
  337. // This special function looks for all time filters, and returns a time range according to the mode
  338. this.timeRange = function(mode) {
  339. var _t = _.where(self.list,{type:'time',active:true});
  340. if(_t.length === 0) {
  341. return false;
  342. }
  343. switch(mode) {
  344. case "min":
  345. return {
  346. from: new Date(_.max(_.pluck(_t,'from'))),
  347. to: new Date(_.min(_.pluck(_t,'to')))
  348. };
  349. case "max":
  350. return {
  351. from: new Date(_.min(_.pluck(_t,'from'))),
  352. to: new Date(_.max(_.pluck(_t,'to')))
  353. };
  354. default:
  355. return false;
  356. }
  357. };
  358. this.remove = function(id) {
  359. if(!_.isUndefined(self.list[id])) {
  360. delete self.list[id];
  361. // This must happen on the full path also since _.without returns a copy
  362. self.ids = dashboard.current.services.filter.ids = _.without(self.ids,id);
  363. _f.idQueue.unshift(id);
  364. _f.idQueue.sort(function(v,k){return v-k;});
  365. return true;
  366. } else {
  367. return false;
  368. }
  369. };
  370. var nextId = function() {
  371. if(_f.idQueue.length > 0) {
  372. return _f.idQueue.shift();
  373. } else {
  374. return self.ids.length;
  375. }
  376. };
  377. // Now init
  378. self.init();
  379. })
  380. .service('dashboard', function($routeParams, $http, $rootScope, $injector, ejsResource, timer, kbnIndex) {
  381. // A hash of defaults to use when loading a dashboard
  382. var _dash = {
  383. title: "",
  384. editable: true,
  385. rows: [],
  386. services: {},
  387. index: {
  388. interval: 'none',
  389. pattern: '_all',
  390. default: '_all'
  391. },
  392. };
  393. // An elasticJS client to use
  394. var ejs = ejsResource(config.elasticsearch);
  395. var gist_pattern = /(^\d{5,}$)|(^[a-z0-9]{10,}$)|(gist.github.com(\/*.*)\/[a-z0-9]{5,}\/*$)/;
  396. // Store a reference to this
  397. var self = this;
  398. var filterSrv,querySrv;
  399. this.current = {};
  400. this.last = {};
  401. $rootScope.$on('$routeChangeSuccess',function(){
  402. // Clear the current dashboard to prevent reloading
  403. self.current = {};
  404. self.indices = [];
  405. route();
  406. });
  407. var route = function() {
  408. // Is there a dashboard type and id in the URL?
  409. if(!(_.isUndefined($routeParams.type)) && !(_.isUndefined($routeParams.id))) {
  410. var _type = $routeParams.type;
  411. var _id = $routeParams.id;
  412. switch(_type) {
  413. case ('elasticsearch'):
  414. self.elasticsearch_load('dashboard',_id);
  415. break;
  416. case ('temp'):
  417. self.elasticsearch_load('temp',_id);
  418. break;
  419. case ('file'):
  420. self.file_load(_id);
  421. break;
  422. default:
  423. self.file_load('default.json');
  424. }
  425. // No dashboard in the URL
  426. } else {
  427. // Check if browser supports localstorage, and if there's a dashboard
  428. if (window.Modernizr.localstorage &&
  429. !(_.isUndefined(window.localStorage['dashboard'])) &&
  430. window.localStorage['dashboard'] !== ''
  431. ) {
  432. var dashboard = JSON.parse(window.localStorage['dashboard']);
  433. _.defaults(dashboard,_dash);
  434. self.dash_load(dashboard);
  435. // No? Ok, grab default.json, its all we have now
  436. } else {
  437. self.file_load('default.json');
  438. }
  439. }
  440. };
  441. // Since the dashboard is responsible for index computation, we can compute and assign the indices
  442. // here before telling the panels to refresh
  443. this.refresh = function() {
  444. if(self.current.index.interval !== 'none') {
  445. if(filterSrv.idsByType('time').length > 0) {
  446. var _range = filterSrv.timeRange('min');
  447. kbnIndex.indices(_range.from,_range.to,
  448. self.current.index.pattern,self.current.index.interval
  449. ).then(function (p) {
  450. if(p.length > 0) {
  451. self.indices = p;
  452. } else {
  453. self.indices = [self.current.index.default];
  454. }
  455. $rootScope.$broadcast('refresh');
  456. });
  457. } else {
  458. // This is not optimal, we should be getting the entire index list here, or at least every
  459. // index that possibly matches the pattern
  460. self.indices = [self.current.index.default];
  461. $rootScope.$broadcast('refresh');
  462. }
  463. } else {
  464. self.indices = [self.current.index.default];
  465. $rootScope.$broadcast('refresh');
  466. }
  467. };
  468. this.dash_load = function(dashboard) {
  469. // Cancel all timers
  470. timer.cancel_all();
  471. // If not using time based indices, use the default index
  472. if(dashboard.index.interval === 'none') {
  473. self.indices = [dashboard.index.default];
  474. }
  475. self.current = _.clone(dashboard);
  476. // Ok, now that we've setup the current dashboard, we can inject our services
  477. querySrv = $injector.get('querySrv');
  478. filterSrv = $injector.get('filterSrv');
  479. // Make sure these re-init
  480. querySrv.init();
  481. filterSrv.init();
  482. // If there's an index interval set and no existing time filter, send a refresh to set one
  483. if(dashboard.index.interval !== 'none' && filterSrv.idsByType('time').length === 0) {
  484. self.refresh();
  485. }
  486. return true;
  487. };
  488. this.gist_id = function(string) {
  489. if(self.is_gist(string)) {
  490. return string.match(gist_pattern)[0].replace(/.*\//, '');
  491. }
  492. };
  493. this.is_gist = function(string) {
  494. if(!_.isUndefined(string) && string !== '' && !_.isNull(string.match(gist_pattern))) {
  495. return string.match(gist_pattern).length > 0 ? true : false;
  496. } else {
  497. return false;
  498. }
  499. };
  500. this.to_file = function() {
  501. var blob = new Blob([angular.toJson(self.current,true)], {type: "application/json;charset=utf-8"});
  502. // from filesaver.js
  503. window.saveAs(blob, self.current.title+"-"+new Date().getTime());
  504. return true;
  505. };
  506. this.set_default = function(dashboard) {
  507. if (window.Modernizr.localstorage) {
  508. window.localStorage['dashboard'] = angular.toJson(dashboard || self.current);
  509. return true;
  510. } else {
  511. return false;
  512. }
  513. };
  514. this.purge_default = function() {
  515. if (window.Modernizr.localstorage) {
  516. window.localStorage['dashboard'] = '';
  517. return true;
  518. } else {
  519. return false;
  520. }
  521. };
  522. // TOFIX: Pretty sure this breaks when you're on a saved dashboard already
  523. this.share_link = function(title,type,id) {
  524. return {
  525. location : window.location.href.replace(window.location.hash,""),
  526. type : type,
  527. id : id,
  528. link : window.location.href.replace(window.location.hash,"")+"#dashboard/"+type+"/"+id,
  529. title : title
  530. };
  531. };
  532. this.file_load = function(file) {
  533. return $http({
  534. url: "dashboards/"+file,
  535. method: "GET",
  536. }).then(function(result) {
  537. var _dashboard = result.data;
  538. _.defaults(_dashboard,_dash);
  539. self.dash_load(_dashboard);
  540. return true;
  541. },function(result) {
  542. return false;
  543. });
  544. };
  545. this.elasticsearch_load = function(type,id) {
  546. var request = ejs.Request().indices(config.kibana_index).types(type);
  547. var results = request.query(
  548. ejs.IdsQuery(id)
  549. ).doSearch();
  550. return results.then(function(results) {
  551. if(_.isUndefined(results)) {
  552. return false;
  553. } else {
  554. self.dash_load(angular.fromJson(results.hits.hits[0]['_source']['dashboard']));
  555. return true;
  556. }
  557. });
  558. };
  559. this.elasticsearch_save = function(type,title,ttl) {
  560. // Clone object so we can modify it without influencing the existing obejct
  561. var save = _.clone(self.current);
  562. var id;
  563. // Change title on object clone
  564. if (type === 'dashboard') {
  565. id = save.title = _.isUndefined(title) ? self.current.title : title;
  566. }
  567. // Create request with id as title. Rethink this.
  568. var request = ejs.Document(config.kibana_index,type,id).source({
  569. user: 'guest',
  570. group: 'guest',
  571. title: save.title,
  572. dashboard: angular.toJson(save)
  573. });
  574. request = type === 'temp' && ttl ? request.ttl(ttl) : request;
  575. // TOFIX: Implement error handling here
  576. return request.doIndex(
  577. // Success
  578. function(result) {
  579. return result;
  580. },
  581. // Failure
  582. function(result) {
  583. return false;
  584. }
  585. );
  586. };
  587. this.elasticsearch_delete = function(id) {
  588. return ejs.Document(config.kibana_index,'dashboard',id).doDelete(
  589. // Success
  590. function(result) {
  591. return result;
  592. },
  593. // Failure
  594. function(result) {
  595. return false;
  596. }
  597. );
  598. };
  599. this.elasticsearch_list = function(query,count) {
  600. var request = ejs.Request().indices(config.kibana_index).types('dashboard');
  601. return request.query(
  602. ejs.QueryStringQuery(query || '*')
  603. ).size(count).doSearch(
  604. // Success
  605. function(result) {
  606. return result;
  607. },
  608. // Failure
  609. function(result) {
  610. return false;
  611. }
  612. );
  613. };
  614. // TOFIX: Gist functionality
  615. this.save_gist = function(title,dashboard) {
  616. var save = _.clone(dashboard || self.current);
  617. save.title = title || self.current.title;
  618. return $http({
  619. url: "https://api.github.com/gists",
  620. method: "POST",
  621. data: {
  622. "description": save.title,
  623. "public": false,
  624. "files": {
  625. "kibana-dashboard.json": {
  626. "content": angular.toJson(save,true)
  627. }
  628. }
  629. }
  630. }).then(function(data, status, headers, config) {
  631. return data.data.html_url;
  632. }, function(data, status, headers, config) {
  633. return false;
  634. });
  635. };
  636. this.gist_list = function(id) {
  637. return $http.jsonp("https://api.github.com/gists/"+id+"?callback=JSON_CALLBACK"
  638. ).then(function(response) {
  639. var files = [];
  640. _.each(response.data.data.files,function(v,k) {
  641. try {
  642. var file = JSON.parse(v.content);
  643. files.push(file);
  644. } catch(e) {
  645. // Nothing?
  646. }
  647. });
  648. return files;
  649. }, function(data, status, headers, config) {
  650. return false;
  651. });
  652. };
  653. });