dashboard_model.ts 18 KB

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