dashboard_model.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699
  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 = (!removePanels && row.collapsed) || (removePanels && !row.collapsed);
  401. if (needToogle) {
  402. this.toggleRow(row);
  403. }
  404. this.removePanel(row);
  405. }
  406. setPanelFocus(id) {
  407. this.meta.focusPanelId = id;
  408. }
  409. updateSubmenuVisibility() {
  410. this.meta.submenuEnabled = (() => {
  411. if (this.links.length > 0) {
  412. return true;
  413. }
  414. var visibleVars = _.filter(
  415. this.templating.list,
  416. variable => variable.hide !== 2
  417. );
  418. if (visibleVars.length > 0) {
  419. return true;
  420. }
  421. var visibleAnnotations = _.filter(
  422. this.annotations.list,
  423. annotation => annotation.hide !== true
  424. );
  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"
  468. ? moment(date).format(format)
  469. : moment.utc(date).format(format);
  470. }
  471. destroy() {
  472. this.events.removeAllListeners();
  473. for (let panel of this.panels) {
  474. panel.destroy();
  475. }
  476. }
  477. toggleRow(row: PanelModel) {
  478. let rowIndex = _.indexOf(this.panels, row);
  479. if (row.collapsed) {
  480. row.collapsed = false;
  481. if (row.panels.length > 0) {
  482. // Use first panel to figure out if it was moved or pushed
  483. let firstPanel = row.panels[0];
  484. let yDiff = firstPanel.gridPos.y - (row.gridPos.y + row.gridPos.h);
  485. // start inserting after row
  486. let insertPos = rowIndex + 1;
  487. // y max will represent the bottom y pos after all panels have been added
  488. // needed to know home much panels below should be pushed down
  489. let yMax = row.gridPos.y;
  490. for (let panel of row.panels) {
  491. // make sure y is adjusted (in case row moved while collapsed)
  492. panel.gridPos.y -= yDiff;
  493. // insert after row
  494. this.panels.splice(insertPos, 0, new PanelModel(panel));
  495. // update insert post and y max
  496. insertPos += 1;
  497. yMax = Math.max(yMax, panel.gridPos.y + panel.gridPos.h);
  498. }
  499. const pushDownAmount = yMax - row.gridPos.y;
  500. // push panels below down
  501. for (
  502. let panelIndex = insertPos;
  503. panelIndex < this.panels.length;
  504. panelIndex++
  505. ) {
  506. this.panels[panelIndex].gridPos.y += pushDownAmount;
  507. }
  508. row.panels = [];
  509. }
  510. // sort panels
  511. this.sortPanelsByGridPos();
  512. // emit change event
  513. this.events.emit("row-expanded");
  514. return;
  515. }
  516. let rowPanels = this.getRowPanels(rowIndex);
  517. // remove panels
  518. _.pull(this.panels, ...rowPanels);
  519. // save panel models inside row panel
  520. row.panels = _.map(rowPanels, panel => panel.getSaveModel());
  521. row.collapsed = true;
  522. // emit change event
  523. this.events.emit("row-collapsed");
  524. }
  525. /**
  526. * Will return all panels after rowIndex until it encounters another row
  527. */
  528. getRowPanels(rowIndex: number): PanelModel[] {
  529. let rowPanels = [];
  530. for (let index = rowIndex + 1; index < this.panels.length; index++) {
  531. let panel = this.panels[index];
  532. // break when encountering another row
  533. if (panel.type === "row") {
  534. break;
  535. }
  536. // this panel must belong to row
  537. rowPanels.push(panel);
  538. }
  539. return rowPanels;
  540. }
  541. on(eventName, callback) {
  542. this.events.on(eventName, callback);
  543. }
  544. off(eventName, callback?) {
  545. this.events.off(eventName, callback);
  546. }
  547. cycleGraphTooltip() {
  548. this.graphTooltip = (this.graphTooltip + 1) % 3;
  549. }
  550. sharedTooltipModeEnabled() {
  551. return this.graphTooltip > 0;
  552. }
  553. sharedCrosshairModeOnly() {
  554. return this.graphTooltip === 1;
  555. }
  556. getRelativeTime(date) {
  557. date = moment.isMoment(date) ? date : moment(date);
  558. return this.timezone === "browser"
  559. ? moment(date).fromNow()
  560. : moment.utc(date).fromNow();
  561. }
  562. getNextQueryLetter(panel) {
  563. var letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  564. return _.find(letters, function(refId) {
  565. return _.every(panel.targets, function(other) {
  566. return other.refId !== refId;
  567. });
  568. });
  569. }
  570. isTimezoneUtc() {
  571. return this.getTimezone() === "utc";
  572. }
  573. getTimezone() {
  574. return this.timezone ? this.timezone : contextSrv.user.timezone;
  575. }
  576. private updateSchema(old) {
  577. let migrator = new DashboardMigrator(this);
  578. migrator.updateSchema(old);
  579. }
  580. }