dashboard_model.ts 17 KB

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