services.js 24 KB

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