module.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. /*
  2. ## Dashcontrol
  3. Dash control allows for saving, loading and sharing of dashboards. Do not
  4. disable the dashcontrol module as a special instance of it allows for loading
  5. the default dashboard from dashboards/default
  6. ### Parameters
  7. * save
  8. ** gist :: Allow saving to gist. Requires registering an oauth domain with Github
  9. ** elasticsearch :: Allow saving to a special Kibana index within Elasticsearch
  10. ** local :: Allow saving to local file
  11. * load
  12. ** gist :: Allow loading from gists
  13. ** elasticsearch :: Allow searching and loading of elasticsearch saved dashboards
  14. ** local :: Allow loading of dashboards from Elasticsearch
  15. * hide_control :: Upon save, hide this panel
  16. * elasticsearch_size :: show this many dashboards under the ES section in the load drop down
  17. * elasticsearch_saveto :: Special kibana index to save to
  18. * temp :: Allow saving of temp dashboards
  19. * temp_ttl :: How long should temp dashboards persist
  20. ### Group Events
  21. #### Sends
  22. * dashboard :: An object containing an entire dashboard to be loaded
  23. */
  24. angular.module('kibana.dashcontrol', [])
  25. .controller('dashcontrol', function($scope, $routeParams, $http, eventBus, timer) {
  26. $scope.panel = $scope.panel || {};
  27. // Set and populate defaults
  28. var _d = {
  29. group : "default",
  30. save : {
  31. gist: false,
  32. elasticsearch: true,
  33. local: true,
  34. 'default': true
  35. },
  36. load : {
  37. gist: true,
  38. elasticsearch: true,
  39. local: true
  40. },
  41. hide_control: false,
  42. elasticsearch_size: 20,
  43. elasticsearch_saveto: $scope.config.kibana_index,
  44. temp: true,
  45. temp_ttl: '30d'
  46. }
  47. _.defaults($scope.panel,_d);
  48. // A hash of defaults for the dashboard object
  49. var _dash = {
  50. title: "",
  51. editable: true,
  52. rows: []
  53. }
  54. $scope.init = function() {
  55. // Long ugly if statement for figuring out which dashboard to load on init
  56. // If there is no dashboard defined, find one
  57. if(_.isUndefined($scope.dashboards)) {
  58. // First check the URL for a path to a dashboard
  59. if(!(_.isUndefined($routeParams.type)) && !(_.isUndefined($routeParams.id))) {
  60. var _type = $routeParams.type;
  61. var _id = $routeParams.id;
  62. if(_type === 'elasticsearch')
  63. $scope.elasticsearch_load('dashboard',_id)
  64. if(_type === 'temp')
  65. $scope.elasticsearch_load('temp',_id)
  66. if(_type === 'file')
  67. $scope.file_load(_id)
  68. // No dashboard in the URL
  69. } else {
  70. // Check if browser supports localstorage, and if there's a dashboard
  71. if (Modernizr.localstorage &&
  72. !(_.isUndefined(localStorage['dashboard'])) &&
  73. localStorage['dashboard'] !== ''
  74. ) {
  75. var dashboard = JSON.parse(localStorage['dashboard']);
  76. _.defaults(dashboard,_dash);
  77. $scope.dash_load(JSON.stringify(dashboard))
  78. // No? Ok, grab default.json, its all we have now
  79. } else {
  80. $scope.file_load('default')
  81. }
  82. }
  83. }
  84. $scope.gist_pattern = /(^\d{5,}$)|(^[a-z0-9]{10,}$)|(gist.github.com(\/*.*)\/[a-z0-9]{5,}\/*$)/;
  85. $scope.gist = {};
  86. $scope.elasticsearch = {};
  87. }
  88. $scope.to_file = function() {
  89. var blob = new Blob([angular.toJson($scope.dashboards,true)], {type: "application/json;charset=utf-8"});
  90. saveAs(blob, $scope.dashboards.title+"-"+new Date().getTime());
  91. }
  92. $scope.default = function() {
  93. if (Modernizr.localstorage) {
  94. localStorage['dashboard'] = angular.toJson($scope.dashboards);
  95. $scope.alert('Success',
  96. $scope.dashboards.title + " has been set as your default dashboard",
  97. 'success',5000)
  98. } else {
  99. $scope.alert('Bummer!',
  100. "Your browser is too old for this functionality",
  101. 'error',5000);
  102. }
  103. }
  104. $scope.share_link = function(title,type,id) {
  105. $scope.share = {
  106. location : location.href.replace(location.hash,""),
  107. type : type,
  108. id : id,
  109. link : location.href.replace(location.hash,"")+"#dashboard/"+type+"/"+id,
  110. title : title
  111. };
  112. }
  113. $scope.purge = function() {
  114. if (Modernizr.localstorage) {
  115. localStorage['dashboard'] = '';
  116. $scope.alert('Success',
  117. 'Default dashboard cleared',
  118. 'success',5000)
  119. } else {
  120. $scope.alert('Doh!',
  121. "Your browser is too old for this functionality",
  122. 'error',5000);
  123. }
  124. }
  125. $scope.file_load = function(file) {
  126. $http({
  127. url: "dashboards/"+file,
  128. method: "GET",
  129. }).success(function(data, status, headers, config) {
  130. var dashboard = data
  131. _.defaults(dashboard,_dash);
  132. $scope.dash_load(JSON.stringify(dashboard))
  133. }).error(function(data, status, headers, config) {
  134. $scope.alert('Default dashboard missing!','Could not locate dashboards/'+file,'error')
  135. });
  136. }
  137. $scope.elasticsearch_save = function(type) {
  138. // Clone object so we can modify it without influencing the existing obejct
  139. if($scope.panel.hide_control) {
  140. $scope.panel.hide = true;
  141. var save = _.clone($scope.dashboards)
  142. } else {
  143. var save = _.clone($scope.dashboards)
  144. }
  145. // Change title on object clone
  146. if(type === 'dashboard')
  147. var id = save.title = $scope.elasticsearch.title;
  148. // Create request with id as title. Rethink this.
  149. var request = $scope.ejs.Document($scope.panel.elasticsearch_saveto,type,id).source({
  150. user: 'guest',
  151. group: 'guest',
  152. title: save.title,
  153. dashboard: angular.toJson(save)
  154. })
  155. if(type === 'temp')
  156. request = request.ttl($scope.panel.temp_ttl)
  157. var result = request.doIndex();
  158. var id = result.then(function(result) {
  159. $scope.alert('Dashboard Saved','This dashboard has been saved to Elasticsearch','success',5000)
  160. $scope.elasticsearch_dblist($scope.elasticsearch.query);
  161. $scope.elasticsearch.title = '';
  162. if(type === 'temp')
  163. $scope.share_link($scope.dashboards.title,'temp',result._id)
  164. })
  165. $scope.panel.hide = false;
  166. }
  167. $scope.elasticsearch_delete = function(dashboard) {
  168. var result = $scope.ejs.Document($scope.panel.elasticsearch_saveto,'dashboard',dashboard._id).doDelete();
  169. result.then(function(result) {
  170. $scope.alert('Dashboard Deleted','','success',5000)
  171. $scope.elasticsearch.dashboards = _.without($scope.elasticsearch.dashboards,dashboard)
  172. })
  173. }
  174. $scope.elasticsearch_load = function(type,id) {
  175. var request = $scope.ejs.Request().indices($scope.panel.elasticsearch_saveto).types(type);
  176. var results = request.query(
  177. $scope.ejs.IdsQuery(id)
  178. ).size($scope.panel.elasticsearch_size).doSearch();
  179. results.then(function(results) {
  180. if(_.isUndefined(results)) {
  181. return;
  182. }
  183. $scope.panel.error = false;
  184. $scope.dash_load(results.hits.hits[0]['_source']['dashboard'])
  185. });
  186. }
  187. $scope.elasticsearch_dblist = function(query) {
  188. if($scope.panel.load.elasticsearch) {
  189. var request = $scope.ejs.Request().indices($scope.panel.elasticsearch_saveto).types('dashboard');
  190. var results = request.query(
  191. $scope.ejs.QueryStringQuery(query || '*')
  192. ).size($scope.panel.elasticsearch_size).doSearch();
  193. results.then(function(results) {
  194. if(_.isUndefined(results.hits)) {
  195. return;
  196. }
  197. $scope.panel.error = false;
  198. $scope.hits = results.hits.total;
  199. $scope.elasticsearch.dashboards = results.hits.hits
  200. });
  201. }
  202. }
  203. $scope.save_gist = function() {
  204. var save = _.clone($scope.dashboards)
  205. save.title = $scope.gist.title;
  206. $http({
  207. url: "https://api.github.com/gists",
  208. method: "POST",
  209. data: {
  210. "description": save.title,
  211. "public": false,
  212. "files": {
  213. "kibana-dashboard.json": {
  214. "content": angular.toJson(save,true)
  215. }
  216. }
  217. }
  218. }).success(function(data, status, headers, config) {
  219. $scope.gist.last = data.html_url;
  220. $scope.alert('Gist saved','You will be able to access your exported dashboard file at <a href="'+data.html_url+'">'+data.html_url+'</a> in a moment','success')
  221. }).error(function(data, status, headers, config) {
  222. $scope.alert('Unable to save','Save to gist failed for some reason','error',5000)
  223. });
  224. }
  225. $scope.gist_dblist = function(id) {
  226. $http.jsonp("https://api.github.com/gists/"+id+"?callback=JSON_CALLBACK"
  227. ).success(function(response) {
  228. $scope.gist.files = []
  229. _.each(response.data.files,function(v,k) {
  230. try {
  231. var file = JSON.parse(v.content)
  232. $scope.gist.files.push(file)
  233. } catch(e) {
  234. $scope.alert('Gist failure','The dashboard file is invalid','warning',5000)
  235. }
  236. });
  237. }).error(function(data, status, headers, config) {
  238. $scope.alert('Gist Failed','Could not retrieve dashboard list from gist','error',5000)
  239. });
  240. }
  241. $scope.dash_load = function(dashboard) {
  242. if(!_.isObject(dashboard))
  243. dashboard = JSON.parse(dashboard)
  244. eventBus.broadcast($scope.$id,'ALL','dashboard',{
  245. dashboard : dashboard,
  246. last : $scope.dashboards
  247. })
  248. timer.cancel_all();
  249. }
  250. $scope.gist_id = function(string) {
  251. if($scope.is_gist(string))
  252. return string.match($scope.gist_pattern)[0].replace(/.*\//, '');
  253. }
  254. $scope.is_gist = function(string) {
  255. if(!_.isUndefined(string) && string != '' && !_.isNull(string.match($scope.gist_pattern)))
  256. return string.match($scope.gist_pattern).length > 0 ? true : false;
  257. else
  258. return false
  259. }
  260. })
  261. .directive('dashUpload', function(timer, eventBus){
  262. return {
  263. restrict: 'A',
  264. link: function(scope, elem, attrs) {
  265. function file_selected(evt) {
  266. var files = evt.target.files; // FileList object
  267. // files is a FileList of File objects. List some properties.
  268. var output = [];
  269. for (var i = 0, f; f = files[i]; i++) {
  270. var reader = new FileReader();
  271. reader.onload = (function(theFile) {
  272. return function(e) {
  273. scope.dash_load(JSON.parse(e.target.result))
  274. scope.$apply();
  275. };
  276. })(f);
  277. reader.readAsText(f);
  278. }
  279. }
  280. // Check for the various File API support.
  281. if (window.File && window.FileReader && window.FileList && window.Blob) {
  282. // Something
  283. document.getElementById('dashupload').addEventListener('change', file_selected, false);
  284. } else {
  285. alert('Sorry, the HTML5 File APIs are not fully supported in this browser.');
  286. }
  287. }
  288. }
  289. }).filter('gistid', function() {
  290. var gist_pattern = /(\d{5,})|([a-z0-9]{10,})|(gist.github.com(\/*.*)\/[a-z0-9]{5,}\/*$)/;
  291. return function(input, scope) {
  292. //return input+"boners"
  293. if(!(_.isUndefined(input))) {
  294. var output = input.match(gist_pattern);
  295. if(!_.isNull(output) && !_.isUndefined(output))
  296. return output[0].replace(/.*\//, '');
  297. }
  298. }
  299. });;