DashboardMigrator.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718
  1. // Libraries
  2. import _ from 'lodash';
  3. // Utils
  4. import getFactors from 'app/core/utils/factors';
  5. import { appendQueryToUrl } from 'app/core/utils/url';
  6. import kbn from 'app/core/utils/kbn';
  7. // Types
  8. import { PanelModel } from './PanelModel';
  9. import { DashboardModel } from './DashboardModel';
  10. import { DataLink } from '@grafana/data';
  11. // Constants
  12. import {
  13. GRID_COLUMN_COUNT,
  14. GRID_CELL_HEIGHT,
  15. GRID_CELL_VMARGIN,
  16. DEFAULT_ROW_HEIGHT,
  17. MIN_PANEL_HEIGHT,
  18. DEFAULT_PANEL_SPAN,
  19. } from 'app/core/constants';
  20. import { DataLinkBuiltInVars } from '@grafana/ui';
  21. export class DashboardMigrator {
  22. dashboard: DashboardModel;
  23. constructor(dashboardModel: DashboardModel) {
  24. this.dashboard = dashboardModel;
  25. }
  26. updateSchema(old: any) {
  27. let i, j, k, n;
  28. const oldVersion = this.dashboard.schemaVersion;
  29. const panelUpgrades = [];
  30. this.dashboard.schemaVersion = 20;
  31. if (oldVersion === this.dashboard.schemaVersion) {
  32. return;
  33. }
  34. // version 2 schema changes
  35. if (oldVersion < 2) {
  36. if (old.services) {
  37. if (old.services.filter) {
  38. this.dashboard.time = old.services.filter.time;
  39. this.dashboard.templating.list = old.services.filter.list || [];
  40. }
  41. }
  42. panelUpgrades.push((panel: any) => {
  43. // rename panel type
  44. if (panel.type === 'graphite') {
  45. panel.type = 'graph';
  46. }
  47. if (panel.type !== 'graph') {
  48. return;
  49. }
  50. if (_.isBoolean(panel.legend)) {
  51. panel.legend = { show: panel.legend };
  52. }
  53. if (panel.grid) {
  54. if (panel.grid.min) {
  55. panel.grid.leftMin = panel.grid.min;
  56. delete panel.grid.min;
  57. }
  58. if (panel.grid.max) {
  59. panel.grid.leftMax = panel.grid.max;
  60. delete panel.grid.max;
  61. }
  62. }
  63. if (panel.y_format) {
  64. if (!panel.y_formats) {
  65. panel.y_formats = [];
  66. }
  67. panel.y_formats[0] = panel.y_format;
  68. delete panel.y_format;
  69. }
  70. if (panel.y2_format) {
  71. if (!panel.y_formats) {
  72. panel.y_formats = [];
  73. }
  74. panel.y_formats[1] = panel.y2_format;
  75. delete panel.y2_format;
  76. }
  77. });
  78. }
  79. // schema version 3 changes
  80. if (oldVersion < 3) {
  81. // ensure panel ids
  82. let maxId = this.dashboard.getNextPanelId();
  83. panelUpgrades.push((panel: any) => {
  84. if (!panel.id) {
  85. panel.id = maxId;
  86. maxId += 1;
  87. }
  88. });
  89. }
  90. // schema version 4 changes
  91. if (oldVersion < 4) {
  92. // move aliasYAxis changes
  93. panelUpgrades.push((panel: any) => {
  94. if (panel.type !== 'graph') {
  95. return;
  96. }
  97. _.each(panel.aliasYAxis, (value, key) => {
  98. panel.seriesOverrides = [{ alias: key, yaxis: value }];
  99. });
  100. delete panel.aliasYAxis;
  101. });
  102. }
  103. if (oldVersion < 6) {
  104. // move pulldowns to new schema
  105. const annotations: any = _.find(old.pulldowns, { type: 'annotations' });
  106. if (annotations) {
  107. this.dashboard.annotations = {
  108. list: annotations.annotations || [],
  109. };
  110. }
  111. // update template variables
  112. for (i = 0; i < this.dashboard.templating.list.length; i++) {
  113. const variable = this.dashboard.templating.list[i];
  114. if (variable.datasource === void 0) {
  115. variable.datasource = null;
  116. }
  117. if (variable.type === 'filter') {
  118. variable.type = 'query';
  119. }
  120. if (variable.type === void 0) {
  121. variable.type = 'query';
  122. }
  123. if (variable.allFormat === void 0) {
  124. variable.allFormat = 'glob';
  125. }
  126. }
  127. }
  128. if (oldVersion < 7) {
  129. if (old.nav && old.nav.length) {
  130. this.dashboard.timepicker = old.nav[0];
  131. }
  132. // ensure query refIds
  133. panelUpgrades.push((panel: any) => {
  134. _.each(panel.targets, target => {
  135. if (!target.refId) {
  136. target.refId = panel.getNextQueryLetter && panel.getNextQueryLetter();
  137. }
  138. });
  139. });
  140. }
  141. if (oldVersion < 8) {
  142. panelUpgrades.push((panel: any) => {
  143. _.each(panel.targets, target => {
  144. // update old influxdb query schema
  145. if (target.fields && target.tags && target.groupBy) {
  146. if (target.rawQuery) {
  147. delete target.fields;
  148. delete target.fill;
  149. } else {
  150. target.select = _.map(target.fields, field => {
  151. const parts = [];
  152. parts.push({ type: 'field', params: [field.name] });
  153. parts.push({ type: field.func, params: [] });
  154. if (field.mathExpr) {
  155. parts.push({ type: 'math', params: [field.mathExpr] });
  156. }
  157. if (field.asExpr) {
  158. parts.push({ type: 'alias', params: [field.asExpr] });
  159. }
  160. return parts;
  161. });
  162. delete target.fields;
  163. _.each(target.groupBy, part => {
  164. if (part.type === 'time' && part.interval) {
  165. part.params = [part.interval];
  166. delete part.interval;
  167. }
  168. if (part.type === 'tag' && part.key) {
  169. part.params = [part.key];
  170. delete part.key;
  171. }
  172. });
  173. if (target.fill) {
  174. target.groupBy.push({ type: 'fill', params: [target.fill] });
  175. delete target.fill;
  176. }
  177. }
  178. }
  179. });
  180. });
  181. }
  182. // schema version 9 changes
  183. if (oldVersion < 9) {
  184. // move aliasYAxis changes
  185. panelUpgrades.push((panel: any) => {
  186. if (panel.type !== 'singlestat' && panel.thresholds !== '') {
  187. return;
  188. }
  189. if (panel.thresholds) {
  190. const k = panel.thresholds.split(',');
  191. if (k.length >= 3) {
  192. k.shift();
  193. panel.thresholds = k.join(',');
  194. }
  195. }
  196. });
  197. }
  198. // schema version 10 changes
  199. if (oldVersion < 10) {
  200. // move aliasYAxis changes
  201. panelUpgrades.push((panel: any) => {
  202. if (panel.type !== 'table') {
  203. return;
  204. }
  205. _.each(panel.styles, style => {
  206. if (style.thresholds && style.thresholds.length >= 3) {
  207. const k = style.thresholds;
  208. k.shift();
  209. style.thresholds = k;
  210. }
  211. });
  212. });
  213. }
  214. if (oldVersion < 12) {
  215. // update template variables
  216. _.each(this.dashboard.templating.list, templateVariable => {
  217. if (templateVariable.refresh) {
  218. templateVariable.refresh = 1;
  219. }
  220. if (!templateVariable.refresh) {
  221. templateVariable.refresh = 0;
  222. }
  223. if (templateVariable.hideVariable) {
  224. templateVariable.hide = 2;
  225. } else if (templateVariable.hideLabel) {
  226. templateVariable.hide = 1;
  227. }
  228. });
  229. }
  230. if (oldVersion < 12) {
  231. // update graph yaxes changes
  232. panelUpgrades.push((panel: any) => {
  233. if (panel.type !== 'graph') {
  234. return;
  235. }
  236. if (!panel.grid) {
  237. return;
  238. }
  239. if (!panel.yaxes) {
  240. panel.yaxes = [
  241. {
  242. show: panel['y-axis'],
  243. min: panel.grid.leftMin,
  244. max: panel.grid.leftMax,
  245. logBase: panel.grid.leftLogBase,
  246. format: panel.y_formats[0],
  247. label: panel.leftYAxisLabel,
  248. },
  249. {
  250. show: panel['y-axis'],
  251. min: panel.grid.rightMin,
  252. max: panel.grid.rightMax,
  253. logBase: panel.grid.rightLogBase,
  254. format: panel.y_formats[1],
  255. label: panel.rightYAxisLabel,
  256. },
  257. ];
  258. panel.xaxis = {
  259. show: panel['x-axis'],
  260. };
  261. delete panel.grid.leftMin;
  262. delete panel.grid.leftMax;
  263. delete panel.grid.leftLogBase;
  264. delete panel.grid.rightMin;
  265. delete panel.grid.rightMax;
  266. delete panel.grid.rightLogBase;
  267. delete panel.y_formats;
  268. delete panel.leftYAxisLabel;
  269. delete panel.rightYAxisLabel;
  270. delete panel['y-axis'];
  271. delete panel['x-axis'];
  272. }
  273. });
  274. }
  275. if (oldVersion < 13) {
  276. // update graph yaxes changes
  277. panelUpgrades.push((panel: any) => {
  278. if (panel.type !== 'graph') {
  279. return;
  280. }
  281. if (!panel.grid) {
  282. return;
  283. }
  284. panel.thresholds = [];
  285. const t1: any = {},
  286. t2: any = {};
  287. if (panel.grid.threshold1 !== null) {
  288. t1.value = panel.grid.threshold1;
  289. if (panel.grid.thresholdLine) {
  290. t1.line = true;
  291. t1.lineColor = panel.grid.threshold1Color;
  292. t1.colorMode = 'custom';
  293. } else {
  294. t1.fill = true;
  295. t1.fillColor = panel.grid.threshold1Color;
  296. t1.colorMode = 'custom';
  297. }
  298. }
  299. if (panel.grid.threshold2 !== null) {
  300. t2.value = panel.grid.threshold2;
  301. if (panel.grid.thresholdLine) {
  302. t2.line = true;
  303. t2.lineColor = panel.grid.threshold2Color;
  304. t2.colorMode = 'custom';
  305. } else {
  306. t2.fill = true;
  307. t2.fillColor = panel.grid.threshold2Color;
  308. t2.colorMode = 'custom';
  309. }
  310. }
  311. if (_.isNumber(t1.value)) {
  312. if (_.isNumber(t2.value)) {
  313. if (t1.value > t2.value) {
  314. t1.op = t2.op = 'lt';
  315. panel.thresholds.push(t1);
  316. panel.thresholds.push(t2);
  317. } else {
  318. t1.op = t2.op = 'gt';
  319. panel.thresholds.push(t1);
  320. panel.thresholds.push(t2);
  321. }
  322. } else {
  323. t1.op = 'gt';
  324. panel.thresholds.push(t1);
  325. }
  326. }
  327. delete panel.grid.threshold1;
  328. delete panel.grid.threshold1Color;
  329. delete panel.grid.threshold2;
  330. delete panel.grid.threshold2Color;
  331. delete panel.grid.thresholdLine;
  332. });
  333. }
  334. if (oldVersion < 14) {
  335. this.dashboard.graphTooltip = old.sharedCrosshair ? 1 : 0;
  336. }
  337. if (oldVersion < 16) {
  338. this.upgradeToGridLayout(old);
  339. }
  340. if (oldVersion < 17) {
  341. panelUpgrades.push((panel: any) => {
  342. if (panel.minSpan) {
  343. const max = GRID_COLUMN_COUNT / panel.minSpan;
  344. const factors = getFactors(GRID_COLUMN_COUNT);
  345. // find the best match compared to factors
  346. // (ie. [1,2,3,4,6,12,24] for 24 columns)
  347. panel.maxPerRow =
  348. factors[
  349. _.findIndex(factors, o => {
  350. return o > max;
  351. }) - 1
  352. ];
  353. }
  354. delete panel.minSpan;
  355. });
  356. }
  357. if (oldVersion < 18) {
  358. // migrate change to gauge options
  359. panelUpgrades.push((panel: any) => {
  360. if (panel['options-gauge']) {
  361. panel.options = panel['options-gauge'];
  362. panel.options.valueOptions = {
  363. unit: panel.options.unit,
  364. stat: panel.options.stat,
  365. decimals: panel.options.decimals,
  366. prefix: panel.options.prefix,
  367. suffix: panel.options.suffix,
  368. };
  369. // correct order
  370. if (panel.options.thresholds) {
  371. panel.options.thresholds.reverse();
  372. }
  373. // this options prop was due to a bug
  374. delete panel.options.options;
  375. delete panel.options.unit;
  376. delete panel.options.stat;
  377. delete panel.options.decimals;
  378. delete panel.options.prefix;
  379. delete panel.options.suffix;
  380. delete panel['options-gauge'];
  381. }
  382. });
  383. }
  384. if (oldVersion < 19) {
  385. // migrate change to gauge options
  386. panelUpgrades.push((panel: any) => {
  387. if (panel.links && _.isArray(panel.links)) {
  388. panel.links = panel.links.map(upgradePanelLink);
  389. }
  390. });
  391. }
  392. if (oldVersion < 20) {
  393. const updateLinks = (link: DataLink) => {
  394. return {
  395. ...link,
  396. url: updateVariablesSyntax(link.url),
  397. };
  398. };
  399. panelUpgrades.push((panel: any) => {
  400. // For graph panel
  401. if (panel.options && panel.options.dataLinks && _.isArray(panel.options.dataLinks)) {
  402. panel.options.dataLinks = panel.options.dataLinks.map(updateLinks);
  403. }
  404. // For panel with fieldOptions
  405. if (panel.options && panel.options.fieldOptions && panel.options.fieldOptions.defaults) {
  406. if (panel.options.fieldOptions.defaults.links && _.isArray(panel.options.fieldOptions.defaults.links)) {
  407. panel.options.fieldOptions.defaults.links = panel.options.fieldOptions.defaults.links.map(updateLinks);
  408. }
  409. if (panel.options.fieldOptions.defaults.title) {
  410. panel.options.fieldOptions.defaults.title = updateVariablesSyntax(
  411. panel.options.fieldOptions.defaults.title
  412. );
  413. }
  414. }
  415. });
  416. }
  417. if (panelUpgrades.length === 0) {
  418. return;
  419. }
  420. for (j = 0; j < this.dashboard.panels.length; j++) {
  421. for (k = 0; k < panelUpgrades.length; k++) {
  422. panelUpgrades[k].call(this, this.dashboard.panels[j]);
  423. if (this.dashboard.panels[j].panels) {
  424. for (n = 0; n < this.dashboard.panels[j].panels.length; n++) {
  425. panelUpgrades[k].call(this, this.dashboard.panels[j].panels[n]);
  426. }
  427. }
  428. }
  429. }
  430. }
  431. upgradeToGridLayout(old: any) {
  432. let yPos = 0;
  433. const widthFactor = GRID_COLUMN_COUNT / 12;
  434. const maxPanelId = _.max(
  435. _.flattenDeep(
  436. _.map(old.rows, row => {
  437. return _.map(row.panels, 'id');
  438. })
  439. )
  440. );
  441. let nextRowId = maxPanelId + 1;
  442. if (!old.rows) {
  443. return;
  444. }
  445. // Add special "row" panels if even one row is collapsed, repeated or has visible title
  446. const showRows = _.some(old.rows, row => row.collapse || row.showTitle || row.repeat);
  447. for (const row of old.rows) {
  448. if (row.repeatIteration) {
  449. continue;
  450. }
  451. const height: any = row.height || DEFAULT_ROW_HEIGHT;
  452. const rowGridHeight = getGridHeight(height);
  453. const rowPanel: any = {};
  454. let rowPanelModel: PanelModel;
  455. if (showRows) {
  456. // add special row panel
  457. rowPanel.id = nextRowId;
  458. rowPanel.type = 'row';
  459. rowPanel.title = row.title;
  460. rowPanel.collapsed = row.collapse;
  461. rowPanel.repeat = row.repeat;
  462. rowPanel.panels = [];
  463. rowPanel.gridPos = {
  464. x: 0,
  465. y: yPos,
  466. w: GRID_COLUMN_COUNT,
  467. h: rowGridHeight,
  468. };
  469. rowPanelModel = new PanelModel(rowPanel);
  470. nextRowId++;
  471. yPos++;
  472. }
  473. const rowArea = new RowArea(rowGridHeight, GRID_COLUMN_COUNT, yPos);
  474. for (const panel of row.panels) {
  475. panel.span = panel.span || DEFAULT_PANEL_SPAN;
  476. if (panel.minSpan) {
  477. panel.minSpan = Math.min(GRID_COLUMN_COUNT, (GRID_COLUMN_COUNT / 12) * panel.minSpan);
  478. }
  479. const panelWidth = Math.floor(panel.span) * widthFactor;
  480. const panelHeight = panel.height ? getGridHeight(panel.height) : rowGridHeight;
  481. const panelPos = rowArea.getPanelPosition(panelHeight, panelWidth);
  482. yPos = rowArea.yPos;
  483. panel.gridPos = {
  484. x: panelPos.x,
  485. y: yPos + panelPos.y,
  486. w: panelWidth,
  487. h: panelHeight,
  488. };
  489. rowArea.addPanel(panel.gridPos);
  490. delete panel.span;
  491. if (rowPanelModel && rowPanel.collapsed) {
  492. rowPanelModel.panels.push(panel);
  493. } else {
  494. this.dashboard.panels.push(new PanelModel(panel));
  495. }
  496. }
  497. if (rowPanelModel) {
  498. this.dashboard.panels.push(rowPanelModel);
  499. }
  500. if (!(rowPanelModel && rowPanel.collapsed)) {
  501. yPos += rowGridHeight;
  502. }
  503. }
  504. }
  505. }
  506. function getGridHeight(height: number | string) {
  507. if (_.isString(height)) {
  508. height = parseInt(height.replace('px', ''), 10);
  509. }
  510. if (height < MIN_PANEL_HEIGHT) {
  511. height = MIN_PANEL_HEIGHT;
  512. }
  513. const gridHeight = Math.ceil(height / (GRID_CELL_HEIGHT + GRID_CELL_VMARGIN));
  514. return gridHeight;
  515. }
  516. /**
  517. * RowArea represents dashboard row filled by panels
  518. * area is an array of numbers represented filled column's cells like
  519. * -----------------------
  520. * |******** ****
  521. * |******** ****
  522. * |********
  523. * -----------------------
  524. * 33333333 2222 00000 ...
  525. */
  526. class RowArea {
  527. area: number[];
  528. yPos: number;
  529. height: number;
  530. constructor(height: number, width = GRID_COLUMN_COUNT, rowYPos = 0) {
  531. this.area = new Array(width).fill(0);
  532. this.yPos = rowYPos;
  533. this.height = height;
  534. }
  535. reset() {
  536. this.area.fill(0);
  537. }
  538. /**
  539. * Update area after adding the panel.
  540. */
  541. addPanel(gridPos: any) {
  542. for (let i = gridPos.x; i < gridPos.x + gridPos.w; i++) {
  543. if (!this.area[i] || gridPos.y + gridPos.h - this.yPos > this.area[i]) {
  544. this.area[i] = gridPos.y + gridPos.h - this.yPos;
  545. }
  546. }
  547. return this.area;
  548. }
  549. /**
  550. * Calculate position for the new panel in the row.
  551. */
  552. getPanelPosition(panelHeight: number, panelWidth: number, callOnce = false): any {
  553. let startPlace, endPlace;
  554. let place;
  555. for (let i = this.area.length - 1; i >= 0; i--) {
  556. if (this.height - this.area[i] > 0) {
  557. if (endPlace === undefined) {
  558. endPlace = i;
  559. } else {
  560. if (i < this.area.length - 1 && this.area[i] <= this.area[i + 1]) {
  561. startPlace = i;
  562. } else {
  563. break;
  564. }
  565. }
  566. } else {
  567. break;
  568. }
  569. }
  570. if (startPlace !== undefined && endPlace !== undefined && endPlace - startPlace >= panelWidth - 1) {
  571. const yPos = _.max(this.area.slice(startPlace));
  572. place = {
  573. x: startPlace,
  574. y: yPos,
  575. };
  576. } else if (!callOnce) {
  577. // wrap to next row
  578. this.yPos += this.height;
  579. this.reset();
  580. return this.getPanelPosition(panelHeight, panelWidth, true);
  581. } else {
  582. return null;
  583. }
  584. return place;
  585. }
  586. }
  587. function upgradePanelLink(link: any): DataLink {
  588. let url = link.url;
  589. if (!url && link.dashboard) {
  590. url = `/dashboard/db/${kbn.slugifyForUrl(link.dashboard)}`;
  591. }
  592. if (!url && link.dashUri) {
  593. url = `/dashboard/${link.dashUri}`;
  594. }
  595. // some models are incomplete and have no dashboard or dashUri
  596. if (!url) {
  597. url = '/';
  598. }
  599. if (link.keepTime) {
  600. url = appendQueryToUrl(url, `$${DataLinkBuiltInVars.keepTime}`);
  601. }
  602. if (link.includeVars) {
  603. url = appendQueryToUrl(url, `$${DataLinkBuiltInVars.includeVars}`);
  604. }
  605. if (link.params) {
  606. url = appendQueryToUrl(url, link.params);
  607. }
  608. return {
  609. url: url,
  610. title: link.title,
  611. targetBlank: link.targetBlank,
  612. };
  613. }
  614. function updateVariablesSyntax(text: string) {
  615. const legacyVariableNamesRegex = /(__series_name)|(\$__series_name)|(__value_time)|(__field_name)|(\$__field_name)/g;
  616. return text.replace(legacyVariableNamesRegex, (match, seriesName, seriesName1, valueTime, fieldName, fieldName1) => {
  617. if (seriesName) {
  618. return '__series.name';
  619. }
  620. if (seriesName1) {
  621. return '${__series.name}';
  622. }
  623. if (valueTime) {
  624. return '__value.time';
  625. }
  626. if (fieldName) {
  627. return '__field.name';
  628. }
  629. if (fieldName1) {
  630. return '${__field.name}';
  631. }
  632. return match;
  633. });
  634. }