dashboard.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  1. define([
  2. 'angular',
  3. 'jquery',
  4. 'kbn',
  5. 'underscore',
  6. 'config',
  7. 'moment',
  8. 'modernizr',
  9. 'filesaver'
  10. ],
  11. function (angular, $, kbn, _, config, moment, Modernizr) {
  12. 'use strict';
  13. var module = angular.module('kibana.services');
  14. module.service('dashboard', function(
  15. $routeParams, $http, $rootScope, $injector, $location, $timeout,
  16. ejsResource, timer, kbnIndex, alertSrv
  17. ) {
  18. // A hash of defaults to use when loading a dashboard
  19. var _dash = {
  20. title: "",
  21. style: "dark",
  22. editable: true,
  23. failover: false,
  24. panel_hints: true,
  25. rows: [],
  26. pulldowns: [
  27. {
  28. type: 'query',
  29. },
  30. {
  31. type: 'filtering'
  32. }
  33. ],
  34. nav: [
  35. {
  36. type: 'timepicker'
  37. }
  38. ],
  39. services: {},
  40. loader: {
  41. save_gist: false,
  42. save_elasticsearch: true,
  43. save_local: true,
  44. save_default: true,
  45. save_temp: true,
  46. save_temp_ttl_enable: true,
  47. save_temp_ttl: '30d',
  48. load_gist: false,
  49. load_elasticsearch: true,
  50. load_elasticsearch_size: 20,
  51. load_local: false,
  52. hide: false
  53. },
  54. index: {
  55. interval: 'none',
  56. pattern: '_all',
  57. default: 'INDEX_MISSING',
  58. warm_fields: true
  59. },
  60. refresh: false
  61. };
  62. // An elasticJS client to use
  63. var ejs = ejsResource(config.elasticsearch);
  64. var gist_pattern = /(^\d{5,}$)|(^[a-z0-9]{10,}$)|(gist.github.com(\/*.*)\/[a-z0-9]{5,}\/*$)/;
  65. // Store a reference to this
  66. var self = this;
  67. var filterSrv,querySrv;
  68. this.current = _.clone(_dash);
  69. this.last = {};
  70. this.availablePanels = [];
  71. $rootScope.$on('$routeChangeSuccess',function(){
  72. // Clear the current dashboard to prevent reloading
  73. self.current = {};
  74. self.indices = [];
  75. route();
  76. });
  77. var route = function() {
  78. // Is there a dashboard type and id in the URL?
  79. if(!(_.isUndefined($routeParams.kbnType)) && !(_.isUndefined($routeParams.kbnId))) {
  80. var _type = $routeParams.kbnType;
  81. var _id = $routeParams.kbnId;
  82. switch(_type) {
  83. case ('elasticsearch'):
  84. self.elasticsearch_load('dashboard',_id);
  85. break;
  86. case ('temp'):
  87. self.elasticsearch_load('temp',_id);
  88. break;
  89. case ('file'):
  90. self.file_load(_id);
  91. break;
  92. case('script'):
  93. self.script_load(_id);
  94. break;
  95. case('local'):
  96. self.local_load();
  97. break;
  98. default:
  99. $location.path(config.default_route);
  100. }
  101. // No dashboard in the URL
  102. } else {
  103. // Check if browser supports localstorage, and if there's an old dashboard. If there is,
  104. // inform the user that they should save their dashboard to Elasticsearch and then set that
  105. // as their default
  106. if (Modernizr.localstorage) {
  107. if(!(_.isUndefined(window.localStorage['dashboard'])) && window.localStorage['dashboard'] !== '') {
  108. $location.path(config.default_route);
  109. alertSrv.set('Saving to browser storage has been replaced',' with saving to Elasticsearch.'+
  110. ' Click <a href="#/dashboard/local/deprecated">here</a> to load your old dashboard anyway.');
  111. } else if(!(_.isUndefined(window.localStorage.kibanaDashboardDefault))) {
  112. $location.path(window.localStorage.kibanaDashboardDefault);
  113. } else {
  114. $location.path(config.default_route);
  115. }
  116. // No? Ok, grab the default route, its all we have now
  117. } else {
  118. $location.path(config.default_route);
  119. }
  120. }
  121. };
  122. // Since the dashboard is responsible for index computation, we can compute and assign the indices
  123. // here before telling the panels to refresh
  124. this.refresh = function() {
  125. if(self.current.index.interval !== 'none') {
  126. if(_.isUndefined(filterSrv)) {
  127. return;
  128. }
  129. if(filterSrv.idsByType('time').length > 0) {
  130. var _range = filterSrv.timeRange('last');
  131. kbnIndex.indices(_range.from,_range.to,
  132. self.current.index.pattern,self.current.index.interval
  133. ).then(function (p) {
  134. if(p.length > 0) {
  135. self.indices = p;
  136. } else {
  137. // Option to not failover
  138. if(self.current.failover) {
  139. self.indices = [self.current.index.default];
  140. } else {
  141. // Do not issue refresh if no indices match. This should be removed when panels
  142. // properly understand when no indices are present
  143. alertSrv.set('No results','There were no results because no indices were found that match your'+
  144. ' selected time span','info',5000);
  145. return false;
  146. }
  147. }
  148. // Don't resolve queries until indices are updated
  149. querySrv.resolve().then(function(){$rootScope.$broadcast('refresh');});
  150. });
  151. } else {
  152. if(self.current.failover) {
  153. self.indices = [self.current.index.default];
  154. querySrv.resolve().then(function(){$rootScope.$broadcast('refresh');});
  155. } else {
  156. alertSrv.set("No time filter",
  157. 'Timestamped indices are configured without a failover. Waiting for time filter.',
  158. 'info',5000);
  159. }
  160. }
  161. } else {
  162. self.indices = [self.current.index.default];
  163. querySrv.resolve().then(function(){$rootScope.$broadcast('refresh');});
  164. }
  165. };
  166. var dash_defaults = function(dashboard) {
  167. _.defaults(dashboard,_dash);
  168. _.defaults(dashboard.index,_dash.index);
  169. _.defaults(dashboard.loader,_dash.loader);
  170. return dashboard;
  171. };
  172. this.dash_load = function(dashboard) {
  173. // Cancel all timers
  174. timer.cancel_all();
  175. // Make sure the dashboard being loaded has everything required
  176. dashboard = dash_defaults(dashboard);
  177. // If not using time based indices, use the default index
  178. if(dashboard.index.interval === 'none') {
  179. self.indices = [dashboard.index.default];
  180. }
  181. // Set the current dashboard
  182. self.current = _.clone(dashboard);
  183. // Delay this until we're sure that querySrv and filterSrv are ready
  184. $timeout(function() {
  185. // Ok, now that we've setup the current dashboard, we can inject our services
  186. querySrv = $injector.get('querySrv');
  187. filterSrv = $injector.get('filterSrv');
  188. // Make sure these re-init
  189. querySrv.init();
  190. filterSrv.init();
  191. },0).then(function() {
  192. // Call refresh to calculate the indices and notify the panels that we're ready to roll
  193. self.refresh();
  194. });
  195. if(dashboard.refresh) {
  196. self.set_interval(dashboard.refresh);
  197. }
  198. // Set the available panels for the "Add Panel" drop down
  199. self.availablePanels = _.difference(config.panel_names,
  200. _.pluck(_.union(self.current.nav,self.current.pulldowns),'type'));
  201. // Take out any that we're not allowed to add from the gui.
  202. self.availablePanels = _.difference(self.availablePanels,config.hidden_panels);
  203. return true;
  204. };
  205. this.gist_id = function(string) {
  206. if(self.is_gist(string)) {
  207. return string.match(gist_pattern)[0].replace(/.*\//, '');
  208. }
  209. };
  210. this.is_gist = function(string) {
  211. if(!_.isUndefined(string) && string !== '' && !_.isNull(string.match(gist_pattern))) {
  212. return string.match(gist_pattern).length > 0 ? true : false;
  213. } else {
  214. return false;
  215. }
  216. };
  217. this.to_file = function() {
  218. var blob = new Blob([angular.toJson(self.current,true)], {type: "application/json;charset=utf-8"});
  219. // from filesaver.js
  220. window.saveAs(blob, self.current.title+"-"+new Date().getTime());
  221. return true;
  222. };
  223. this.set_default = function(route) {
  224. if (Modernizr.localstorage) {
  225. // Purge any old dashboards
  226. if(!_.isUndefined(window.localStorage['dashboard'])) {
  227. delete window.localStorage['dashboard'];
  228. }
  229. window.localStorage.kibanaDashboardDefault = route;
  230. return true;
  231. } else {
  232. return false;
  233. }
  234. };
  235. this.purge_default = function() {
  236. if (Modernizr.localstorage) {
  237. // Purge any old dashboards
  238. if(!_.isUndefined(window.localStorage['dashboard'])) {
  239. delete window.localStorage['dashboard'];
  240. }
  241. delete window.localStorage.kibanaDashboardDefault;
  242. return true;
  243. } else {
  244. return false;
  245. }
  246. };
  247. // TOFIX: Pretty sure this breaks when you're on a saved dashboard already
  248. this.share_link = function(title,type,id) {
  249. return {
  250. location : window.location.href.replace(window.location.hash,""),
  251. type : type,
  252. id : id,
  253. link : window.location.href.replace(window.location.hash,"")+"#dashboard/"+type+"/"+id,
  254. title : title
  255. };
  256. };
  257. var renderTemplate = function(json,params) {
  258. var _r;
  259. _.templateSettings = {interpolate : /\{\{(.+?)\}\}/g};
  260. var template = _.template(json);
  261. var rendered = template({ARGS:params});
  262. try {
  263. _r = angular.fromJson(rendered);
  264. } catch(e) {
  265. _r = false;
  266. }
  267. return _r;
  268. };
  269. this.local_load = function() {
  270. var dashboard = JSON.parse(window.localStorage['dashboard']);
  271. dashboard.rows.unshift({
  272. height: "30",
  273. title: "Deprecation Notice",
  274. panels: [
  275. {
  276. title: 'WARNING: Legacy dashboard',
  277. type: 'text',
  278. span: 12,
  279. mode: 'html',
  280. content: 'This dashboard has been loaded from the browsers local cache. If you use '+
  281. 'another brower or computer you will not be able to access it! '+
  282. '\n\n <h4>Good news!</h4> Kibana'+
  283. ' now stores saved dashboards in Elasticsearch. Click the <i class="icon-save"></i> '+
  284. 'button in the top left to save this dashboard. Then select "Set as Home" from'+
  285. ' the "advanced" sub menu to automatically use the stored dashboard as your Kibana '+
  286. 'landing page afterwards'+
  287. '<br><br><strong>Tip:</strong> You may with to remove this row before saving!'
  288. }
  289. ]
  290. });
  291. self.dash_load(dashboard);
  292. };
  293. this.file_load = function(file) {
  294. return $http({
  295. url: "app/dashboards/"+file.replace(/\.(?!json)/,"/")+'?' + new Date().getTime(),
  296. method: "GET",
  297. transformResponse: function(response) {
  298. return renderTemplate(response,$routeParams);
  299. }
  300. }).then(function(result) {
  301. if(!result) {
  302. return false;
  303. }
  304. self.dash_load(dash_defaults(result.data));
  305. return true;
  306. },function() {
  307. alertSrv.set('Error',"Could not load <i>dashboards/"+file+"</i>. Please make sure it exists" ,'error');
  308. return false;
  309. });
  310. };
  311. this.elasticsearch_load = function(type,id) {
  312. return $http({
  313. url: config.elasticsearch + "/" + config.kibana_index + "/"+type+"/"+id+'?' + new Date().getTime(),
  314. method: "GET",
  315. transformResponse: function(response) {
  316. return renderTemplate(angular.fromJson(response)._source.dashboard, $routeParams);
  317. }
  318. }).error(function(data, status) {
  319. if(status === 0) {
  320. alertSrv.set('Error',"Could not contact Elasticsearch at "+config.elasticsearch+
  321. ". Please ensure that Elasticsearch is reachable from your system." ,'error');
  322. } else {
  323. alertSrv.set('Error',"Could not find "+id+". If you"+
  324. " are using a proxy, ensure it is configured correctly",'error');
  325. }
  326. return false;
  327. }).success(function(data) {
  328. self.dash_load(data);
  329. });
  330. };
  331. this.script_load = function(file) {
  332. return $http({
  333. url: "app/dashboards/"+file.replace(/\.(?!js)/,"/"),
  334. method: "GET",
  335. transformResponse: function(response) {
  336. /*jshint -W054 */
  337. var _f = new Function('ARGS','kbn','_','moment','window','document','angular','require','define','$','jQuery',response);
  338. return _f($routeParams,kbn,_,moment);
  339. }
  340. }).then(function(result) {
  341. if(!result) {
  342. return false;
  343. }
  344. self.dash_load(dash_defaults(result.data));
  345. return true;
  346. },function() {
  347. alertSrv.set('Error',
  348. "Could not load <i>scripts/"+file+"</i>. Please make sure it exists and returns a valid dashboard" ,
  349. 'error');
  350. return false;
  351. });
  352. };
  353. this.elasticsearch_save = function(type,title,ttl) {
  354. // Clone object so we can modify it without influencing the existing obejct
  355. var save = _.clone(self.current);
  356. var id;
  357. // Change title on object clone
  358. if (type === 'dashboard') {
  359. id = save.title = _.isUndefined(title) ? self.current.title : title;
  360. }
  361. // Create request with id as title. Rethink this.
  362. var request = ejs.Document(config.kibana_index,type,id).source({
  363. user: 'guest',
  364. group: 'guest',
  365. title: save.title,
  366. dashboard: angular.toJson(save)
  367. });
  368. request = type === 'temp' && ttl ? request.ttl(ttl) : request;
  369. return request.doIndex(
  370. // Success
  371. function(result) {
  372. if(type === 'dashboard') {
  373. $location.path('/dashboard/elasticsearch/'+title);
  374. }
  375. return result;
  376. },
  377. // Failure
  378. function() {
  379. return false;
  380. }
  381. );
  382. };
  383. this.elasticsearch_delete = function(id) {
  384. return ejs.Document(config.kibana_index,'dashboard',id).doDelete(
  385. // Success
  386. function(result) {
  387. return result;
  388. },
  389. // Failure
  390. function() {
  391. return false;
  392. }
  393. );
  394. };
  395. this.elasticsearch_list = function(query,count) {
  396. var request = ejs.Request().indices(config.kibana_index).types('dashboard');
  397. return request.query(
  398. ejs.QueryStringQuery(query || '*')
  399. ).size(count).doSearch(
  400. // Success
  401. function(result) {
  402. return result;
  403. },
  404. // Failure
  405. function() {
  406. return false;
  407. }
  408. );
  409. };
  410. this.save_gist = function(title,dashboard) {
  411. var save = _.clone(dashboard || self.current);
  412. save.title = title || self.current.title;
  413. return $http({
  414. url: "https://api.github.com/gists",
  415. method: "POST",
  416. data: {
  417. "description": save.title,
  418. "public": false,
  419. "files": {
  420. "kibana-dashboard.json": {
  421. "content": angular.toJson(save,true)
  422. }
  423. }
  424. }
  425. }).then(function(data) {
  426. return data.data.html_url;
  427. }, function() {
  428. return false;
  429. });
  430. };
  431. this.gist_list = function(id) {
  432. return $http.jsonp("https://api.github.com/gists/"+id+"?callback=JSON_CALLBACK"
  433. ).then(function(response) {
  434. var files = [];
  435. _.each(response.data.data.files,function(v) {
  436. try {
  437. var file = JSON.parse(v.content);
  438. files.push(file);
  439. } catch(e) {
  440. return false;
  441. }
  442. });
  443. return files;
  444. }, function() {
  445. return false;
  446. });
  447. };
  448. this.set_interval = function (interval) {
  449. self.current.refresh = interval;
  450. if(interval) {
  451. var _i = kbn.interval_to_ms(interval);
  452. timer.cancel(self.refresh_timer);
  453. self.refresh_timer = timer.register($timeout(function() {
  454. self.set_interval(interval);
  455. self.refresh();
  456. },_i));
  457. self.refresh();
  458. } else {
  459. timer.cancel(self.refresh_timer);
  460. }
  461. };
  462. });
  463. });