dashboard_model.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  1. import moment from 'moment';
  2. import _ from 'lodash';
  3. import {GRID_COLUMN_COUNT, REPEAT_DIR_VERTICAL} from 'app/core/constants';
  4. import {DEFAULT_ANNOTATION_COLOR} from 'app/core/utils/colors';
  5. import {Emitter} from 'app/core/utils/emitter';
  6. import {contextSrv} from 'app/core/services/context_srv';
  7. import sortByKeys from 'app/core/utils/sort_by_keys';
  8. import {PanelModel} from './panel_model';
  9. import {DashboardMigrator} from './dashboard_migration';
  10. export class DashboardModel {
  11. id: any;
  12. title: any;
  13. autoUpdate: any;
  14. description: any;
  15. tags: any;
  16. style: any;
  17. timezone: any;
  18. editable: any;
  19. graphTooltip: any;
  20. time: any;
  21. timepicker: any;
  22. hideControls: any;
  23. templating: any;
  24. annotations: any;
  25. refresh: any;
  26. snapshot: any;
  27. schemaVersion: number;
  28. version: number;
  29. revision: number;
  30. links: any;
  31. gnetId: any;
  32. folderId: number;
  33. panels: PanelModel[];
  34. // ------------------
  35. // not persisted
  36. // ------------------
  37. // repeat process cycles
  38. iteration: number;
  39. meta: any;
  40. events: Emitter;
  41. static nonPersistedProperties: {[str: string]: boolean} = {
  42. events: true,
  43. meta: true,
  44. panels: true, // needs special handling
  45. templating: true, // needs special handling
  46. };
  47. constructor(data, meta?) {
  48. if (!data) {
  49. data = {};
  50. }
  51. this.events = new Emitter();
  52. this.id = data.id || null;
  53. this.revision = data.revision;
  54. this.title = data.title || 'No Title';
  55. this.autoUpdate = data.autoUpdate;
  56. this.description = data.description;
  57. this.tags = data.tags || [];
  58. this.style = data.style || 'dark';
  59. this.timezone = data.timezone || '';
  60. this.editable = data.editable !== false;
  61. this.graphTooltip = data.graphTooltip || 0;
  62. this.hideControls = data.hideControls || false;
  63. this.time = data.time || {from: 'now-6h', to: 'now'};
  64. this.timepicker = data.timepicker || {};
  65. this.templating = this.ensureListExist(data.templating);
  66. this.annotations = this.ensureListExist(data.annotations);
  67. this.refresh = data.refresh;
  68. this.snapshot = data.snapshot;
  69. this.schemaVersion = data.schemaVersion || 0;
  70. this.version = data.version || 0;
  71. this.links = data.links || [];
  72. this.gnetId = data.gnetId || null;
  73. this.folderId = data.folderId || null;
  74. this.panels = _.map(data.panels || [], panelData => new PanelModel(panelData));
  75. this.initMeta(meta);
  76. this.updateSchema(data);
  77. this.addBuiltInAnnotationQuery();
  78. this.sortPanelsByGridPos();
  79. }
  80. addBuiltInAnnotationQuery() {
  81. let found = false;
  82. for (let item of this.annotations.list) {
  83. if (item.builtIn === 1) {
  84. found = true;
  85. break;
  86. }
  87. }
  88. if (found) {
  89. return;
  90. }
  91. this.annotations.list.unshift({
  92. datasource: '-- Grafana --',
  93. name: 'Annotations & Alerts',
  94. type: 'dashboard',
  95. iconColor: DEFAULT_ANNOTATION_COLOR,
  96. enable: true,
  97. hide: true,
  98. builtIn: 1,
  99. });
  100. }
  101. private initMeta(meta) {
  102. meta = meta || {};
  103. meta.canShare = meta.canShare !== false;
  104. meta.canSave = meta.canSave !== false;
  105. meta.canStar = meta.canStar !== false;
  106. meta.canEdit = meta.canEdit !== false;
  107. if (!this.editable) {
  108. meta.canEdit = false;
  109. meta.canDelete = false;
  110. meta.canSave = false;
  111. }
  112. this.meta = meta;
  113. }
  114. // cleans meta data and other non peristent state
  115. getSaveModelClone() {
  116. // make clone
  117. var copy: any = {};
  118. for (var property in this) {
  119. if (DashboardModel.nonPersistedProperties[property] || !this.hasOwnProperty(property)) {
  120. continue;
  121. }
  122. copy[property] = _.cloneDeep(this[property]);
  123. }
  124. // get variable save models
  125. copy.templating = {
  126. list: _.map(this.templating.list, variable => (variable.getSaveModel ? variable.getSaveModel() : variable)),
  127. };
  128. // get panel save models
  129. copy.panels = _.map(this.panels, panel => panel.getSaveModel());
  130. // sort by keys
  131. copy = sortByKeys(copy);
  132. return copy;
  133. }
  134. setViewMode(panel: PanelModel, fullscreen: boolean, isEditing: boolean) {
  135. this.meta.fullscreen = fullscreen;
  136. this.meta.isEditing = isEditing && this.meta.canEdit;
  137. panel.setViewMode(fullscreen, this.meta.isEditing);
  138. this.events.emit('view-mode-changed', panel);
  139. }
  140. private ensureListExist(data) {
  141. if (!data) {
  142. data = {};
  143. }
  144. if (!data.list) {
  145. data.list = [];
  146. }
  147. return data;
  148. }
  149. getNextPanelId() {
  150. let max = 0;
  151. for (let panel of this.panels) {
  152. if (panel.id > max) {
  153. max = panel.id;
  154. }
  155. }
  156. return max + 1;
  157. }
  158. forEachPanel(callback) {
  159. for (let i = 0; i < this.panels.length; i++) {
  160. callback(this.panels[i], i);
  161. }
  162. }
  163. getPanelById(id) {
  164. for (let panel of this.panels) {
  165. if (panel.id === id) {
  166. return panel;
  167. }
  168. }
  169. return null;
  170. }
  171. addPanel(panelData) {
  172. panelData.id = this.getNextPanelId();
  173. let panel = new PanelModel(panelData);
  174. this.panels.unshift(panel);
  175. this.sortPanelsByGridPos();
  176. this.events.emit('panel-added', panel);
  177. }
  178. sortPanelsByGridPos() {
  179. this.panels.sort(function(panelA, panelB) {
  180. if (panelA.gridPos.y === panelB.gridPos.y) {
  181. return panelA.gridPos.x - panelB.gridPos.x;
  182. } else {
  183. return panelA.gridPos.y - panelB.gridPos.y;
  184. }
  185. });
  186. }
  187. cleanUpRepeats() {
  188. this.processRepeats(true);
  189. }
  190. processRepeats(cleanUpOnly?: boolean) {
  191. if (this.snapshot || this.templating.list.length === 0) {
  192. return;
  193. }
  194. this.iteration = (this.iteration || new Date().getTime()) + 1;
  195. let panelsToRemove = [];
  196. // cleanup scopedVars
  197. for (let panel of this.panels) {
  198. delete panel.scopedVars;
  199. }
  200. for (let i = 0; i < this.panels.length; i++) {
  201. let panel = this.panels[i];
  202. if (panel.repeat) {
  203. if (!cleanUpOnly) {
  204. this.repeatPanel(panel, i);
  205. }
  206. } else if (panel.repeatPanelId && panel.repeatIteration !== this.iteration) {
  207. panelsToRemove.push(panel);
  208. }
  209. }
  210. // for (let panel of this.panels) {
  211. // if (panel.repeat) {
  212. // if (!cleanUpOnly) {
  213. // this.repeatPanel(panel);
  214. // }
  215. // } else if (panel.repeatPanelId && panel.repeatIteration !== this.iteration) {
  216. // panelsToRemove.push(panel);
  217. // }
  218. // }
  219. // remove panels
  220. _.pull(this.panels, ...panelsToRemove);
  221. this.sortPanelsByGridPos();
  222. this.events.emit('repeats-processed');
  223. }
  224. getPanelRepeatClone(sourcePanel, valueIndex, sourcePanelIndex) {
  225. // if first clone return source
  226. if (valueIndex === 0) {
  227. return sourcePanel;
  228. }
  229. var clone = new PanelModel(sourcePanel.getSaveModel());
  230. clone.id = this.getNextPanelId();
  231. if (sourcePanel.type === 'row') {
  232. // for row clones we need to figure out panels under row to clone and where to insert clone
  233. let rowPanels = this.getRowPanels(sourcePanelIndex);
  234. clone.panels = _.map(rowPanels, panel => panel.getSaveModel());
  235. // insert after preceding row's panels
  236. let insertPos = sourcePanelIndex + ((rowPanels.length + 1)*valueIndex);
  237. this.panels.splice(insertPos, 0, clone);
  238. } else {
  239. // insert after source panel + value index
  240. this.panels.splice(sourcePanelIndex+valueIndex, 0, clone);
  241. }
  242. clone.repeatIteration = this.iteration;
  243. clone.repeatPanelId = sourcePanel.id;
  244. clone.repeat = null;
  245. return clone;
  246. }
  247. getBottomYForRow() {
  248. }
  249. repeatPanel(panel: PanelModel, panelIndex: number) {
  250. var variable = _.find(this.templating.list, {name: panel.repeat});
  251. if (!variable) {
  252. return;
  253. }
  254. var selected;
  255. if (variable.current.text === 'All') {
  256. selected = variable.options.slice(1, variable.options.length);
  257. } else {
  258. selected = _.filter(variable.options, {selected: true});
  259. }
  260. let minWidth = panel.minSpan || 6;
  261. let xPos = 0;
  262. let yPos = panel.gridPos.y;
  263. for (let index = 0; index < selected.length; index++) {
  264. var option = selected[index];
  265. var copy = this.getPanelRepeatClone(panel, index, panelIndex);
  266. copy.scopedVars = {};
  267. copy.scopedVars[variable.name] = option;
  268. if (copy.type === 'row') {
  269. // place row below row panels
  270. }
  271. if (panel.repeatDirection === REPEAT_DIR_VERTICAL) {
  272. copy.gridPos.y = yPos;
  273. yPos += copy.gridPos.h;
  274. } else {
  275. // set width based on how many are selected
  276. // assumed the repeated panels should take up full row width
  277. copy.gridPos.w = Math.max(GRID_COLUMN_COUNT / selected.length, minWidth);
  278. copy.gridPos.x = xPos;
  279. copy.gridPos.y = yPos;
  280. xPos += copy.gridPos.w;
  281. // handle overflow by pushing down one row
  282. if (xPos + copy.gridPos.w > GRID_COLUMN_COUNT) {
  283. xPos = 0;
  284. yPos += copy.gridPos.h;
  285. }
  286. }
  287. }
  288. }
  289. removePanel(panel: PanelModel) {
  290. var index = _.indexOf(this.panels, panel);
  291. this.panels.splice(index, 1);
  292. this.events.emit('panel-removed', panel);
  293. }
  294. setPanelFocus(id) {
  295. this.meta.focusPanelId = id;
  296. }
  297. updateSubmenuVisibility() {
  298. this.meta.submenuEnabled = (() => {
  299. if (this.links.length > 0) {
  300. return true;
  301. }
  302. var visibleVars = _.filter(this.templating.list, variable => variable.hide !== 2);
  303. if (visibleVars.length > 0) {
  304. return true;
  305. }
  306. var visibleAnnotations = _.filter(this.annotations.list, annotation => annotation.hide !== true);
  307. if (visibleAnnotations.length > 0) {
  308. return true;
  309. }
  310. return false;
  311. })();
  312. }
  313. getPanelInfoById(panelId) {
  314. for (let i = 0; i < this.panels.length; i++) {
  315. if (this.panels[i].id === panelId) {
  316. return {
  317. panel: this.panels[i],
  318. index: i,
  319. };
  320. }
  321. }
  322. return null;
  323. }
  324. duplicatePanel(panel) {
  325. const newPanel = panel.getSaveModel();
  326. newPanel.id = this.getNextPanelId();
  327. delete newPanel.repeat;
  328. delete newPanel.repeatIteration;
  329. delete newPanel.repeatPanelId;
  330. delete newPanel.scopedVars;
  331. if (newPanel.alert) {
  332. delete newPanel.thresholds;
  333. }
  334. delete newPanel.alert;
  335. // does it fit to the right?
  336. if (panel.gridPos.x + panel.gridPos.w * 2 <= GRID_COLUMN_COUNT) {
  337. newPanel.gridPos.x += panel.gridPos.w;
  338. } else {
  339. // add bellow
  340. newPanel.gridPos.y += panel.gridPos.h;
  341. }
  342. this.addPanel(newPanel);
  343. return newPanel;
  344. }
  345. formatDate(date, format?) {
  346. date = moment.isMoment(date) ? date : moment(date);
  347. format = format || 'YYYY-MM-DD HH:mm:ss';
  348. let timezone = this.getTimezone();
  349. return timezone === 'browser' ? moment(date).format(format) : moment.utc(date).format(format);
  350. }
  351. destroy() {
  352. this.events.removeAllListeners();
  353. for (let panel of this.panels) {
  354. panel.destroy();
  355. }
  356. }
  357. toggleRow(row: PanelModel) {
  358. let rowIndex = _.indexOf(this.panels, row);
  359. if (row.collapsed) {
  360. row.collapsed = false;
  361. if (row.panels.length > 0) {
  362. // Use first panel to figure out if it was moved or pushed
  363. let firstPanel = row.panels[0];
  364. let yDiff = firstPanel.gridPos.y - (row.gridPos.y + row.gridPos.h);
  365. // start inserting after row
  366. let insertPos = rowIndex+1;
  367. // y max will represent the bottom y pos after all panels have been added
  368. // needed to know home much panels below should be pushed down
  369. let yMax = row.gridPos.y;
  370. for (let panel of row.panels) {
  371. // make sure y is adjusted (in case row moved while collapsed)
  372. panel.gridPos.y -= yDiff;
  373. // insert after row
  374. this.panels.splice(insertPos, 0, new PanelModel(panel));
  375. // update insert post and y max
  376. insertPos += 1;
  377. yMax = Math.max(yMax, panel.gridPos.y + panel.gridPos.h);
  378. }
  379. const pushDownAmount = yMax - row.gridPos.y;
  380. // push panels below down
  381. for (let panelIndex = insertPos; panelIndex < this.panels.length; panelIndex++) {
  382. this.panels[panelIndex].gridPos.y += pushDownAmount;
  383. }
  384. row.panels = [];
  385. }
  386. // sort panels
  387. this.sortPanelsByGridPos();
  388. // emit change event
  389. this.events.emit('row-expanded');
  390. return;
  391. }
  392. let rowPanels = this.getRowPanels(rowIndex);
  393. // remove panels
  394. _.pull(this.panels, ...rowPanels);
  395. // save panel models inside row panel
  396. row.panels = _.map(rowPanels, panel => panel.getSaveModel());
  397. row.collapsed = true;
  398. // emit change event
  399. this.events.emit('row-collapsed');
  400. }
  401. /**
  402. * Will return all panels after rowIndex until it encounters another row
  403. */
  404. getRowPanels(rowIndex: number): PanelModel[] {
  405. let rowPanels = [];
  406. for (let index = rowIndex+1; index < this.panels.length; index++) {
  407. let panel = this.panels[index];
  408. // break when encountering another row
  409. if (panel.type === 'row') {
  410. break;
  411. }
  412. // this panel must belong to row
  413. rowPanels.push(panel);
  414. }
  415. return rowPanels;
  416. }
  417. on(eventName, callback) {
  418. this.events.on(eventName, callback);
  419. }
  420. off(eventName, callback?) {
  421. this.events.off(eventName, callback);
  422. }
  423. cycleGraphTooltip() {
  424. this.graphTooltip = (this.graphTooltip + 1) % 3;
  425. }
  426. sharedTooltipModeEnabled() {
  427. return this.graphTooltip > 0;
  428. }
  429. sharedCrosshairModeOnly() {
  430. return this.graphTooltip === 1;
  431. }
  432. getRelativeTime(date) {
  433. date = moment.isMoment(date) ? date : moment(date);
  434. return this.timezone === 'browser' ? moment(date).fromNow() : moment.utc(date).fromNow();
  435. }
  436. getNextQueryLetter(panel) {
  437. var letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  438. return _.find(letters, function(refId) {
  439. return _.every(panel.targets, function(other) {
  440. return other.refId !== refId;
  441. });
  442. });
  443. }
  444. isTimezoneUtc() {
  445. return this.getTimezone() === 'utc';
  446. }
  447. getTimezone() {
  448. return this.timezone ? this.timezone : contextSrv.user.timezone;
  449. }
  450. private updateSchema(old) {
  451. let migrator = new DashboardMigrator(this);
  452. migrator.updateSchema(old);
  453. }
  454. }