dashboard_model.ts 17 KB

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