dashboard_model.ts 18 KB

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