dashboard_model.ts 18 KB

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