services.js 20 KB

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