dashboard_model.ts 18 KB

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