services.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966
  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. loader: {
  515. save_gist: false,
  516. save_elasticsearch: true,
  517. save_local: true,
  518. save_default: true,
  519. save_temp: true,
  520. save_temp_ttl_enable: true,
  521. save_temp_ttl: '30d',
  522. load_gist: true,
  523. load_elasticsearch: true,
  524. load_elasticsearch_size: 20,
  525. load_local: true,
  526. hide: false
  527. },
  528. index: {
  529. interval: 'none',
  530. pattern: '_all',
  531. default: 'INDEX_MISSING'
  532. },
  533. };
  534. // An elasticJS client to use
  535. var ejs = ejsResource(config.elasticsearch);
  536. var gist_pattern = /(^\d{5,}$)|(^[a-z0-9]{10,}$)|(gist.github.com(\/*.*)\/[a-z0-9]{5,}\/*$)/;
  537. // Store a reference to this
  538. var self = this;
  539. var filterSrv,querySrv;
  540. this.current = _.clone(_dash);
  541. this.last = {};
  542. $rootScope.$on('$routeChangeSuccess',function(){
  543. // Clear the current dashboard to prevent reloading
  544. self.current = {};
  545. self.indices = [];
  546. route();
  547. });
  548. var route = function() {
  549. // Is there a dashboard type and id in the URL?
  550. if(!(_.isUndefined($routeParams.kbnType)) && !(_.isUndefined($routeParams.kbnId))) {
  551. var _type = $routeParams.kbnType;
  552. var _id = $routeParams.kbnId;
  553. switch(_type) {
  554. case ('elasticsearch'):
  555. self.elasticsearch_load('dashboard',_id);
  556. break;
  557. case ('temp'):
  558. self.elasticsearch_load('temp',_id);
  559. break;
  560. case ('file'):
  561. self.file_load(_id);
  562. break;
  563. case('script'):
  564. self.script_load(_id);
  565. break;
  566. default:
  567. self.file_load('default.json');
  568. }
  569. // No dashboard in the URL
  570. } else {
  571. // Check if browser supports localstorage, and if there's a dashboard
  572. if (window.Modernizr.localstorage &&
  573. !(_.isUndefined(window.localStorage['dashboard'])) &&
  574. window.localStorage['dashboard'] !== ''
  575. ) {
  576. var dashboard = JSON.parse(window.localStorage['dashboard']);
  577. self.dash_load(dashboard);
  578. // No? Ok, grab default.json, its all we have now
  579. } else {
  580. self.file_load('default.json');
  581. }
  582. }
  583. };
  584. // Since the dashboard is responsible for index computation, we can compute and assign the indices
  585. // here before telling the panels to refresh
  586. this.refresh = function() {
  587. if(self.current.index.interval !== 'none') {
  588. if(filterSrv.idsByType('time').length > 0) {
  589. var _range = filterSrv.timeRange('min');
  590. kbnIndex.indices(_range.from,_range.to,
  591. self.current.index.pattern,self.current.index.interval
  592. ).then(function (p) {
  593. if(p.length > 0) {
  594. self.indices = p;
  595. } else {
  596. //TODO: Option to not failover
  597. if(self.current.failover) {
  598. self.indices = [self.current.index.default];
  599. } else {
  600. // Do not issue refresh if no indices match. This should be removed when panels
  601. // properly understand when no indices are present
  602. return false;
  603. }
  604. }
  605. $rootScope.$broadcast('refresh');
  606. });
  607. } else {
  608. if(self.current.failover) {
  609. self.indices = [self.current.index.default];
  610. $rootScope.$broadcast('refresh');
  611. } else {
  612. alertSrv.set("No time filter",
  613. 'Timestamped indices are configured without a failover. Waiting for time filter.',
  614. 'info',5000);
  615. }
  616. }
  617. } else {
  618. self.indices = [self.current.index.default];
  619. $rootScope.$broadcast('refresh');
  620. }
  621. };
  622. var dash_defaults = function(dashboard) {
  623. _.defaults(dashboard,_dash);
  624. _.defaults(dashboard.index,_dash.index);
  625. _.defaults(dashboard.loader,_dash.loader);
  626. return dashboard;
  627. };
  628. this.dash_load = function(dashboard) {
  629. // Cancel all timers
  630. timer.cancel_all();
  631. // Make sure the dashboard being loaded has everything required
  632. dashboard = dash_defaults(dashboard);
  633. // If not using time based indices, use the default index
  634. if(dashboard.index.interval === 'none') {
  635. self.indices = [dashboard.index.default];
  636. }
  637. self.current = _.clone(dashboard);
  638. // Ok, now that we've setup the current dashboard, we can inject our services
  639. querySrv = $injector.get('querySrv');
  640. filterSrv = $injector.get('filterSrv');
  641. // Make sure these re-init
  642. querySrv.init();
  643. filterSrv.init();
  644. // If there's an index interval set and no existing time filter, send a refresh to set one
  645. if(dashboard.index.interval !== 'none' && filterSrv.idsByType('time').length === 0) {
  646. self.refresh();
  647. }
  648. return true;
  649. };
  650. this.gist_id = function(string) {
  651. if(self.is_gist(string)) {
  652. return string.match(gist_pattern)[0].replace(/.*\//, '');
  653. }
  654. };
  655. this.is_gist = function(string) {
  656. if(!_.isUndefined(string) && string !== '' && !_.isNull(string.match(gist_pattern))) {
  657. return string.match(gist_pattern).length > 0 ? true : false;
  658. } else {
  659. return false;
  660. }
  661. };
  662. this.to_file = function() {
  663. var blob = new Blob([angular.toJson(self.current,true)], {type: "application/json;charset=utf-8"});
  664. // from filesaver.js
  665. window.saveAs(blob, self.current.title+"-"+new Date().getTime());
  666. return true;
  667. };
  668. this.set_default = function(dashboard) {
  669. if (window.Modernizr.localstorage) {
  670. window.localStorage['dashboard'] = angular.toJson(dashboard || self.current);
  671. return true;
  672. } else {
  673. return false;
  674. }
  675. };
  676. this.purge_default = function() {
  677. if (window.Modernizr.localstorage) {
  678. window.localStorage['dashboard'] = '';
  679. return true;
  680. } else {
  681. return false;
  682. }
  683. };
  684. // TOFIX: Pretty sure this breaks when you're on a saved dashboard already
  685. this.share_link = function(title,type,id) {
  686. return {
  687. location : window.location.href.replace(window.location.hash,""),
  688. type : type,
  689. id : id,
  690. link : window.location.href.replace(window.location.hash,"")+"#dashboard/"+type+"/"+id,
  691. title : title
  692. };
  693. };
  694. var renderTemplate = function(json,params) {
  695. var _r;
  696. _.templateSettings = {interpolate : /\{\{(.+?)\}\}/g};
  697. var template = _.template(json);
  698. var rendered = template({ARGS:params});
  699. try {
  700. _r = angular.fromJson(rendered);
  701. } catch(e) {
  702. _r = false;
  703. }
  704. return _r;
  705. };
  706. this.file_load = function(file) {
  707. return $http({
  708. url: "dashboards/"+file,
  709. method: "GET",
  710. transformResponse: function(response) {
  711. return renderTemplate(response,$routeParams);
  712. }
  713. }).then(function(result) {
  714. if(!result) {
  715. return false;
  716. }
  717. self.dash_load(dash_defaults(result.data));
  718. return true;
  719. },function(result) {
  720. alertSrv.set('Error',"Could not load <i>dashboards/"+file+"</i>. Please make sure it exists" ,'error');
  721. return false;
  722. });
  723. };
  724. this.elasticsearch_load = function(type,id) {
  725. return $http({
  726. url: config.elasticsearch + "/" + config.kibana_index + "/"+type+"/"+id,
  727. method: "GET",
  728. transformResponse: function(response) {
  729. return renderTemplate(angular.fromJson(response)['_source']['dashboard'],$routeParams);
  730. }
  731. }).error(function(data, status, headers, conf) {
  732. if(status === 0) {
  733. alertSrv.set('Error',"Could not contact Elasticsearch at "+config.elasticsearch+
  734. ". Please ensure that Elasticsearch is reachable from your system." ,'error');
  735. } else {
  736. alertSrv.set('Error',"Could not find "+id+". If you"+
  737. " are using a proxy, ensure it is configured correctly",'error');
  738. }
  739. return false;
  740. }).success(function(data, status, headers) {
  741. self.dash_load(data);
  742. });
  743. };
  744. this.script_load = function(file) {
  745. return $http({
  746. url: "dashboards/"+file,
  747. method: "GET",
  748. transformResponse: function(response) {
  749. /*jshint -W054 */
  750. var _f = new Function("ARGS",response);
  751. return _f($routeParams);
  752. }
  753. }).then(function(result) {
  754. if(!result) {
  755. return false;
  756. }
  757. self.dash_load(dash_defaults(result.data));
  758. return true;
  759. },function(result) {
  760. alertSrv.set('Error',
  761. "Could not load <i>scripts/"+file+"</i>. Please make sure it exists and returns a valid dashboard" ,
  762. 'error');
  763. return false;
  764. });
  765. };
  766. this.elasticsearch_save = function(type,title,ttl) {
  767. // Clone object so we can modify it without influencing the existing obejct
  768. var save = _.clone(self.current);
  769. var id;
  770. // Change title on object clone
  771. if (type === 'dashboard') {
  772. id = save.title = _.isUndefined(title) ? self.current.title : title;
  773. }
  774. // Create request with id as title. Rethink this.
  775. var request = ejs.Document(config.kibana_index,type,id).source({
  776. user: 'guest',
  777. group: 'guest',
  778. title: save.title,
  779. dashboard: angular.toJson(save)
  780. });
  781. request = type === 'temp' && ttl ? request.ttl(ttl) : request;
  782. return request.doIndex(
  783. // Success
  784. function(result) {
  785. return result;
  786. },
  787. // Failure
  788. function(result) {
  789. return false;
  790. }
  791. );
  792. };
  793. this.elasticsearch_delete = function(id) {
  794. return ejs.Document(config.kibana_index,'dashboard',id).doDelete(
  795. // Success
  796. function(result) {
  797. return result;
  798. },
  799. // Failure
  800. function(result) {
  801. return false;
  802. }
  803. );
  804. };
  805. this.elasticsearch_list = function(query,count) {
  806. var request = ejs.Request().indices(config.kibana_index).types('dashboard');
  807. return request.query(
  808. ejs.QueryStringQuery(query || '*')
  809. ).size(count).doSearch(
  810. // Success
  811. function(result) {
  812. return result;
  813. },
  814. // Failure
  815. function(result) {
  816. return false;
  817. }
  818. );
  819. };
  820. this.save_gist = function(title,dashboard) {
  821. var save = _.clone(dashboard || self.current);
  822. save.title = title || self.current.title;
  823. return $http({
  824. url: "https://api.github.com/gists",
  825. method: "POST",
  826. data: {
  827. "description": save.title,
  828. "public": false,
  829. "files": {
  830. "kibana-dashboard.json": {
  831. "content": angular.toJson(save,true)
  832. }
  833. }
  834. }
  835. }).then(function(data, status, headers, config) {
  836. return data.data.html_url;
  837. }, function(data, status, headers, config) {
  838. return false;
  839. });
  840. };
  841. this.gist_list = function(id) {
  842. return $http.jsonp("https://api.github.com/gists/"+id+"?callback=JSON_CALLBACK"
  843. ).then(function(response) {
  844. var files = [];
  845. _.each(response.data.data.files,function(v,k) {
  846. try {
  847. var file = JSON.parse(v.content);
  848. files.push(file);
  849. } catch(e) {
  850. return false;
  851. }
  852. });
  853. return files;
  854. }, function(data, status, headers, config) {
  855. return false;
  856. });
  857. };
  858. });