DashboardMigrator.ts 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302
  1. import { each, find, findIndex, flattenDeep, isArray, isBoolean, isNumber, isString, map, max, some } from 'lodash';
  2. import {
  3. AnnotationQuery,
  4. DataLink,
  5. DataLinkBuiltInVars,
  6. DataQuery,
  7. DataSourceRef,
  8. DataTransformerConfig,
  9. FieldConfigSource,
  10. FieldMatcherID,
  11. FieldType,
  12. getActiveThreshold,
  13. getDataSourceRef,
  14. isDataSourceRef,
  15. MappingType,
  16. PanelPlugin,
  17. SpecialValueMatch,
  18. standardEditorsRegistry,
  19. standardFieldConfigEditorRegistry,
  20. ThresholdsConfig,
  21. urlUtil,
  22. ValueMap,
  23. ValueMapping,
  24. } from '@grafana/data';
  25. import { getDataSourceSrv, setDataSourceSrv } from '@grafana/runtime';
  26. import { AxisPlacement, GraphFieldConfig } from '@grafana/ui';
  27. import { getAllOptionEditors, getAllStandardFieldConfigs } from 'app/core/components/editors/registry';
  28. import { config } from 'app/core/config';
  29. import {
  30. DEFAULT_PANEL_SPAN,
  31. DEFAULT_ROW_HEIGHT,
  32. GRID_CELL_HEIGHT,
  33. GRID_CELL_VMARGIN,
  34. GRID_COLUMN_COUNT,
  35. MIN_PANEL_HEIGHT,
  36. } from 'app/core/constants';
  37. import getFactors from 'app/core/utils/factors';
  38. import kbn from 'app/core/utils/kbn';
  39. import { DatasourceSrv } from 'app/features/plugins/datasource_srv';
  40. import { isConstant, isMulti } from 'app/features/variables/guard';
  41. import { alignCurrentWithMulti } from 'app/features/variables/shared/multiOptions';
  42. import { CloudWatchMetricsQuery, LegacyAnnotationQuery } from 'app/plugins/datasource/cloudwatch/types';
  43. import { plugin as gaugePanelPlugin } from 'app/plugins/panel/gauge/module';
  44. import { plugin as statPanelPlugin } from 'app/plugins/panel/stat/module';
  45. import { labelsToFieldsTransformer } from '../../../../../packages/grafana-data/src/transformations/transformers/labelsToFields';
  46. import { mergeTransformer } from '../../../../../packages/grafana-data/src/transformations/transformers/merge';
  47. import {
  48. migrateCloudWatchQuery,
  49. migrateMultipleStatsAnnotationQuery,
  50. migrateMultipleStatsMetricsQuery,
  51. } from '../../../plugins/datasource/cloudwatch/migrations/dashboardMigrations';
  52. import { VariableHide } from '../../variables/types';
  53. import { DashboardModel } from './DashboardModel';
  54. import { PanelModel } from './PanelModel';
  55. standardEditorsRegistry.setInit(getAllOptionEditors);
  56. standardFieldConfigEditorRegistry.setInit(getAllStandardFieldConfigs);
  57. type PanelSchemeUpgradeHandler = (panel: PanelModel) => PanelModel;
  58. export class DashboardMigrator {
  59. dashboard: DashboardModel;
  60. constructor(dashboardModel: DashboardModel) {
  61. this.dashboard = dashboardModel;
  62. // for tests to pass
  63. if (!getDataSourceSrv()) {
  64. setDataSourceSrv(new DatasourceSrv());
  65. }
  66. }
  67. updateSchema(old: any) {
  68. let i, j, k, n;
  69. const oldVersion = this.dashboard.schemaVersion;
  70. const panelUpgrades: PanelSchemeUpgradeHandler[] = [];
  71. this.dashboard.schemaVersion = 36;
  72. if (oldVersion === this.dashboard.schemaVersion) {
  73. return;
  74. }
  75. // version 2 schema changes
  76. if (oldVersion < 2) {
  77. if (old.services) {
  78. if (old.services.filter) {
  79. this.dashboard.time = old.services.filter.time;
  80. this.dashboard.templating.list = old.services.filter.list || [];
  81. }
  82. }
  83. panelUpgrades.push((panel: any) => {
  84. // rename panel type
  85. if (panel.type === 'graphite') {
  86. panel.type = 'graph';
  87. }
  88. if (panel.type !== 'graph') {
  89. return panel;
  90. }
  91. if (isBoolean(panel.legend)) {
  92. panel.legend = { show: panel.legend };
  93. }
  94. if (panel.grid) {
  95. if (panel.grid.min) {
  96. panel.grid.leftMin = panel.grid.min;
  97. delete panel.grid.min;
  98. }
  99. if (panel.grid.max) {
  100. panel.grid.leftMax = panel.grid.max;
  101. delete panel.grid.max;
  102. }
  103. }
  104. if (panel.y_format) {
  105. if (!panel.y_formats) {
  106. panel.y_formats = [];
  107. }
  108. panel.y_formats[0] = panel.y_format;
  109. delete panel.y_format;
  110. }
  111. if (panel.y2_format) {
  112. if (!panel.y_formats) {
  113. panel.y_formats = [];
  114. }
  115. panel.y_formats[1] = panel.y2_format;
  116. delete panel.y2_format;
  117. }
  118. return panel;
  119. });
  120. }
  121. // schema version 3 changes
  122. if (oldVersion < 3) {
  123. // ensure panel IDs
  124. let maxId = this.dashboard.getNextPanelId();
  125. panelUpgrades.push((panel: any) => {
  126. if (!panel.id) {
  127. panel.id = maxId;
  128. maxId += 1;
  129. }
  130. return panel;
  131. });
  132. }
  133. // schema version 4 changes
  134. if (oldVersion < 4) {
  135. // move aliasYAxis changes
  136. panelUpgrades.push((panel: any) => {
  137. if (panel.type !== 'graph') {
  138. return panel;
  139. }
  140. each(panel.aliasYAxis, (value, key) => {
  141. panel.seriesOverrides = [{ alias: key, yaxis: value }];
  142. });
  143. delete panel.aliasYAxis;
  144. return panel;
  145. });
  146. }
  147. if (oldVersion < 6) {
  148. // move drop-downs to new schema
  149. const annotations: any = find(old.pulldowns, { type: 'annotations' });
  150. if (annotations) {
  151. this.dashboard.annotations = {
  152. list: annotations.annotations || [],
  153. };
  154. }
  155. // update template variables
  156. for (i = 0; i < this.dashboard.templating.list.length; i++) {
  157. const variable = this.dashboard.templating.list[i];
  158. if (variable.datasource === void 0) {
  159. variable.datasource = null;
  160. }
  161. if (variable.type === 'filter') {
  162. variable.type = 'query';
  163. }
  164. if (variable.type === void 0) {
  165. variable.type = 'query';
  166. }
  167. if (variable.allFormat === void 0) {
  168. variable.allFormat = 'glob';
  169. }
  170. }
  171. }
  172. if (oldVersion < 7) {
  173. if (old.nav && old.nav.length) {
  174. this.dashboard.timepicker = old.nav[0];
  175. }
  176. // ensure query refIds
  177. panelUpgrades.push((panel: any) => {
  178. each(panel.targets, (target) => {
  179. if (!target.refId) {
  180. target.refId = panel.getNextQueryLetter && panel.getNextQueryLetter();
  181. }
  182. });
  183. return panel;
  184. });
  185. }
  186. if (oldVersion < 8) {
  187. panelUpgrades.push((panel: any) => {
  188. each(panel.targets, (target) => {
  189. // update old influxdb query schema
  190. if (target.fields && target.tags && target.groupBy) {
  191. if (target.rawQuery) {
  192. delete target.fields;
  193. delete target.fill;
  194. } else {
  195. target.select = map(target.fields, (field) => {
  196. const parts = [];
  197. parts.push({ type: 'field', params: [field.name] });
  198. parts.push({ type: field.func, params: [] });
  199. if (field.mathExpr) {
  200. parts.push({ type: 'math', params: [field.mathExpr] });
  201. }
  202. if (field.asExpr) {
  203. parts.push({ type: 'alias', params: [field.asExpr] });
  204. }
  205. return parts;
  206. });
  207. delete target.fields;
  208. each(target.groupBy, (part) => {
  209. if (part.type === 'time' && part.interval) {
  210. part.params = [part.interval];
  211. delete part.interval;
  212. }
  213. if (part.type === 'tag' && part.key) {
  214. part.params = [part.key];
  215. delete part.key;
  216. }
  217. });
  218. if (target.fill) {
  219. target.groupBy.push({ type: 'fill', params: [target.fill] });
  220. delete target.fill;
  221. }
  222. }
  223. }
  224. });
  225. return panel;
  226. });
  227. }
  228. // schema version 9 changes
  229. if (oldVersion < 9) {
  230. // move aliasYAxis changes
  231. panelUpgrades.push((panel: any) => {
  232. if (panel.type !== 'singlestat' && panel.thresholds !== '') {
  233. return panel;
  234. }
  235. if (panel.thresholds) {
  236. const k = panel.thresholds.split(',');
  237. if (k.length >= 3) {
  238. k.shift();
  239. panel.thresholds = k.join(',');
  240. }
  241. }
  242. return panel;
  243. });
  244. }
  245. // schema version 10 changes
  246. if (oldVersion < 10) {
  247. // move aliasYAxis changes
  248. panelUpgrades.push((panel: any) => {
  249. if (panel.type !== 'table') {
  250. return panel;
  251. }
  252. each(panel.styles, (style) => {
  253. if (style.thresholds && style.thresholds.length >= 3) {
  254. const k = style.thresholds;
  255. k.shift();
  256. style.thresholds = k;
  257. }
  258. });
  259. return panel;
  260. });
  261. }
  262. if (oldVersion < 12) {
  263. // update template variables
  264. each(this.dashboard.getVariables(), (templateVariable: any) => {
  265. if (templateVariable.refresh) {
  266. templateVariable.refresh = 1;
  267. }
  268. if (!templateVariable.refresh) {
  269. templateVariable.refresh = 0;
  270. }
  271. if (templateVariable.hideVariable) {
  272. templateVariable.hide = 2;
  273. } else if (templateVariable.hideLabel) {
  274. templateVariable.hide = 1;
  275. }
  276. });
  277. }
  278. if (oldVersion < 12) {
  279. // update graph yaxes changes
  280. panelUpgrades.push((panel: any) => {
  281. if (panel.type !== 'graph') {
  282. return panel;
  283. }
  284. if (!panel.grid) {
  285. return panel;
  286. }
  287. if (!panel.yaxes) {
  288. panel.yaxes = [
  289. {
  290. show: panel['y-axis'],
  291. min: panel.grid.leftMin,
  292. max: panel.grid.leftMax,
  293. logBase: panel.grid.leftLogBase,
  294. format: panel.y_formats[0],
  295. label: panel.leftYAxisLabel,
  296. },
  297. {
  298. show: panel['y-axis'],
  299. min: panel.grid.rightMin,
  300. max: panel.grid.rightMax,
  301. logBase: panel.grid.rightLogBase,
  302. format: panel.y_formats[1],
  303. label: panel.rightYAxisLabel,
  304. },
  305. ];
  306. panel.xaxis = {
  307. show: panel['x-axis'],
  308. };
  309. delete panel.grid.leftMin;
  310. delete panel.grid.leftMax;
  311. delete panel.grid.leftLogBase;
  312. delete panel.grid.rightMin;
  313. delete panel.grid.rightMax;
  314. delete panel.grid.rightLogBase;
  315. delete panel.y_formats;
  316. delete panel.leftYAxisLabel;
  317. delete panel.rightYAxisLabel;
  318. delete panel['y-axis'];
  319. delete panel['x-axis'];
  320. }
  321. return panel;
  322. });
  323. }
  324. if (oldVersion < 13) {
  325. // update graph yaxes changes
  326. panelUpgrades.push((panel: any) => {
  327. if (panel.type !== 'graph') {
  328. return panel;
  329. }
  330. if (!panel.grid) {
  331. return panel;
  332. }
  333. if (!panel.thresholds) {
  334. panel.thresholds = [];
  335. }
  336. const t1: any = {},
  337. t2: any = {};
  338. if (panel.grid.threshold1 !== null) {
  339. t1.value = panel.grid.threshold1;
  340. if (panel.grid.thresholdLine) {
  341. t1.line = true;
  342. t1.lineColor = panel.grid.threshold1Color;
  343. t1.colorMode = 'custom';
  344. } else {
  345. t1.fill = true;
  346. t1.fillColor = panel.grid.threshold1Color;
  347. t1.colorMode = 'custom';
  348. }
  349. }
  350. if (panel.grid.threshold2 !== null) {
  351. t2.value = panel.grid.threshold2;
  352. if (panel.grid.thresholdLine) {
  353. t2.line = true;
  354. t2.lineColor = panel.grid.threshold2Color;
  355. t2.colorMode = 'custom';
  356. } else {
  357. t2.fill = true;
  358. t2.fillColor = panel.grid.threshold2Color;
  359. t2.colorMode = 'custom';
  360. }
  361. }
  362. if (isNumber(t1.value)) {
  363. if (isNumber(t2.value)) {
  364. if (t1.value > t2.value) {
  365. t1.op = t2.op = 'lt';
  366. panel.thresholds.push(t1);
  367. panel.thresholds.push(t2);
  368. } else {
  369. t1.op = t2.op = 'gt';
  370. panel.thresholds.push(t1);
  371. panel.thresholds.push(t2);
  372. }
  373. } else {
  374. t1.op = 'gt';
  375. panel.thresholds.push(t1);
  376. }
  377. }
  378. delete panel.grid.threshold1;
  379. delete panel.grid.threshold1Color;
  380. delete panel.grid.threshold2;
  381. delete panel.grid.threshold2Color;
  382. delete panel.grid.thresholdLine;
  383. return panel;
  384. });
  385. }
  386. if (oldVersion < 14) {
  387. this.dashboard.graphTooltip = old.sharedCrosshair ? 1 : 0;
  388. }
  389. if (oldVersion < 16) {
  390. this.upgradeToGridLayout(old);
  391. }
  392. if (oldVersion < 17) {
  393. panelUpgrades.push((panel: any) => {
  394. if (panel.minSpan) {
  395. const max = GRID_COLUMN_COUNT / panel.minSpan;
  396. const factors = getFactors(GRID_COLUMN_COUNT);
  397. // find the best match compared to factors
  398. // (ie. [1,2,3,4,6,12,24] for 24 columns)
  399. panel.maxPerRow =
  400. factors[
  401. findIndex(factors, (o) => {
  402. return o > max;
  403. }) - 1
  404. ];
  405. }
  406. delete panel.minSpan;
  407. return panel;
  408. });
  409. }
  410. if (oldVersion < 18) {
  411. // migrate change to gauge options
  412. panelUpgrades.push((panel: any) => {
  413. if (panel['options-gauge']) {
  414. panel.options = panel['options-gauge'];
  415. panel.options.valueOptions = {
  416. unit: panel.options.unit,
  417. stat: panel.options.stat,
  418. decimals: panel.options.decimals,
  419. prefix: panel.options.prefix,
  420. suffix: panel.options.suffix,
  421. };
  422. // correct order
  423. if (panel.options.thresholds) {
  424. panel.options.thresholds.reverse();
  425. }
  426. // this options prop was due to a bug
  427. delete panel.options.options;
  428. delete panel.options.unit;
  429. delete panel.options.stat;
  430. delete panel.options.decimals;
  431. delete panel.options.prefix;
  432. delete panel.options.suffix;
  433. delete panel['options-gauge'];
  434. }
  435. return panel;
  436. });
  437. }
  438. if (oldVersion < 19) {
  439. // migrate change to gauge options
  440. panelUpgrades.push((panel: any) => {
  441. if (panel.links && isArray(panel.links)) {
  442. panel.links = panel.links.map(upgradePanelLink);
  443. }
  444. return panel;
  445. });
  446. }
  447. if (oldVersion < 20) {
  448. const updateLinks = (link: DataLink) => {
  449. return {
  450. ...link,
  451. url: updateVariablesSyntax(link.url),
  452. };
  453. };
  454. panelUpgrades.push((panel: any) => {
  455. // For graph panel
  456. if (panel.options && panel.options.dataLinks && isArray(panel.options.dataLinks)) {
  457. panel.options.dataLinks = panel.options.dataLinks.map(updateLinks);
  458. }
  459. // For panel with fieldOptions
  460. if (panel.options && panel.options.fieldOptions && panel.options.fieldOptions.defaults) {
  461. if (panel.options.fieldOptions.defaults.links && isArray(panel.options.fieldOptions.defaults.links)) {
  462. panel.options.fieldOptions.defaults.links = panel.options.fieldOptions.defaults.links.map(updateLinks);
  463. }
  464. if (panel.options.fieldOptions.defaults.title) {
  465. panel.options.fieldOptions.defaults.title = updateVariablesSyntax(
  466. panel.options.fieldOptions.defaults.title
  467. );
  468. }
  469. }
  470. return panel;
  471. });
  472. }
  473. if (oldVersion < 21) {
  474. const updateLinks = (link: DataLink) => {
  475. return {
  476. ...link,
  477. url: link.url.replace(/__series.labels/g, '__field.labels'),
  478. };
  479. };
  480. panelUpgrades.push((panel: any) => {
  481. // For graph panel
  482. if (panel.options && panel.options.dataLinks && isArray(panel.options.dataLinks)) {
  483. panel.options.dataLinks = panel.options.dataLinks.map(updateLinks);
  484. }
  485. // For panel with fieldOptions
  486. if (panel.options && panel.options.fieldOptions && panel.options.fieldOptions.defaults) {
  487. if (panel.options.fieldOptions.defaults.links && isArray(panel.options.fieldOptions.defaults.links)) {
  488. panel.options.fieldOptions.defaults.links = panel.options.fieldOptions.defaults.links.map(updateLinks);
  489. }
  490. }
  491. return panel;
  492. });
  493. }
  494. if (oldVersion < 22) {
  495. panelUpgrades.push((panel: any) => {
  496. if (panel.type !== 'table') {
  497. return panel;
  498. }
  499. each(panel.styles, (style) => {
  500. style.align = 'auto';
  501. });
  502. return panel;
  503. });
  504. }
  505. if (oldVersion < 23) {
  506. for (const variable of this.dashboard.templating.list) {
  507. if (!isMulti(variable)) {
  508. continue;
  509. }
  510. const { multi, current } = variable;
  511. variable.current = alignCurrentWithMulti(current, multi);
  512. }
  513. }
  514. if (oldVersion < 24) {
  515. // 7.0
  516. // - migrate existing tables to 'table-old'
  517. panelUpgrades.push((panel: any) => {
  518. const wasAngularTable = panel.type === 'table';
  519. if (wasAngularTable && !panel.styles) {
  520. return panel; // styles are missing so assumes default settings
  521. }
  522. const wasReactTable = panel.table === 'table2';
  523. if (!wasAngularTable || wasReactTable) {
  524. return panel;
  525. }
  526. panel.type = wasAngularTable ? 'table-old' : 'table';
  527. return panel;
  528. });
  529. }
  530. if (oldVersion < 25) {
  531. // tags are removed in version 28
  532. }
  533. if (oldVersion < 26) {
  534. panelUpgrades.push((panel: any) => {
  535. const wasReactText = panel.type === 'text2';
  536. if (!wasReactText) {
  537. return panel;
  538. }
  539. panel.type = 'text';
  540. delete panel.options.angular;
  541. return panel;
  542. });
  543. }
  544. if (oldVersion < 27) {
  545. for (const variable of this.dashboard.templating.list) {
  546. if (!isConstant(variable)) {
  547. continue;
  548. }
  549. if (variable.hide === VariableHide.dontHide || variable.hide === VariableHide.hideLabel) {
  550. variable.type = 'textbox';
  551. }
  552. variable.current = { selected: true, text: variable.query ?? '', value: variable.query ?? '' };
  553. variable.options = [variable.current];
  554. }
  555. }
  556. if (oldVersion < 28) {
  557. panelUpgrades.push((panel: PanelModel) => {
  558. if (panel.type === 'singlestat') {
  559. return migrateSinglestat(panel);
  560. }
  561. return panel;
  562. });
  563. for (const variable of this.dashboard.templating.list) {
  564. if (variable.tags) {
  565. delete variable.tags;
  566. }
  567. if (variable.tagsQuery) {
  568. delete variable.tagsQuery;
  569. }
  570. if (variable.tagValuesQuery) {
  571. delete variable.tagValuesQuery;
  572. }
  573. if (variable.useTags) {
  574. delete variable.useTags;
  575. }
  576. }
  577. }
  578. if (oldVersion < 29) {
  579. for (const variable of this.dashboard.templating.list) {
  580. if (variable.type !== 'query') {
  581. continue;
  582. }
  583. if (variable.refresh !== 1 && variable.refresh !== 2) {
  584. variable.refresh = 1;
  585. }
  586. if (variable.options?.length) {
  587. variable.options = [];
  588. }
  589. }
  590. }
  591. if (oldVersion < 30) {
  592. panelUpgrades.push(upgradeValueMappingsForPanel);
  593. panelUpgrades.push(migrateTooltipOptions);
  594. }
  595. if (oldVersion < 31) {
  596. panelUpgrades.push((panel: PanelModel) => {
  597. if (panel.transformations) {
  598. for (const t of panel.transformations) {
  599. if (t.id === labelsToFieldsTransformer.id) {
  600. return appendTransformerAfter(panel, labelsToFieldsTransformer.id, {
  601. id: mergeTransformer.id,
  602. options: {},
  603. });
  604. }
  605. }
  606. }
  607. return panel;
  608. });
  609. }
  610. if (oldVersion < 32) {
  611. // CloudWatch migrations have been moved to version 34
  612. }
  613. // Replace datasource name with reference, uid and type
  614. if (oldVersion < 33) {
  615. panelUpgrades.push((panel) => {
  616. panel.datasource = migrateDatasourceNameToRef(panel.datasource, { returnDefaultAsNull: true });
  617. if (!panel.targets) {
  618. return panel;
  619. }
  620. for (const target of panel.targets) {
  621. const targetRef = migrateDatasourceNameToRef(target.datasource, { returnDefaultAsNull: true });
  622. if (targetRef != null) {
  623. target.datasource = targetRef;
  624. }
  625. }
  626. return panel;
  627. });
  628. }
  629. if (oldVersion < 34) {
  630. panelUpgrades.push((panel: PanelModel) => {
  631. this.migrateCloudWatchQueries(panel);
  632. return panel;
  633. });
  634. this.migrateCloudWatchAnnotationQuery();
  635. }
  636. if (oldVersion < 35) {
  637. panelUpgrades.push(ensureXAxisVisibility);
  638. }
  639. if (oldVersion < 36) {
  640. // Migrate datasource to refs in annotations
  641. for (const query of this.dashboard.annotations.list) {
  642. query.datasource = migrateDatasourceNameToRef(query.datasource, { returnDefaultAsNull: false });
  643. }
  644. // Migrate datasource: null to current default
  645. const defaultDs = getDataSourceSrv().getInstanceSettings(null);
  646. if (defaultDs) {
  647. for (const variable of this.dashboard.templating.list) {
  648. if (variable.type === 'query' && variable.datasource === null) {
  649. variable.datasource = getDataSourceRef(defaultDs);
  650. }
  651. }
  652. panelUpgrades.push((panel: PanelModel) => {
  653. if (panel.targets) {
  654. let panelDataSourceWasDefault = false;
  655. if (panel.datasource == null && panel.targets.length > 0) {
  656. panel.datasource = getDataSourceRef(defaultDs);
  657. panelDataSourceWasDefault = true;
  658. }
  659. for (const target of panel.targets) {
  660. if (target.datasource == null || target.datasource.uid == null) {
  661. target.datasource = { ...panel.datasource };
  662. }
  663. if (panelDataSourceWasDefault && target.datasource.uid !== '__expr__') {
  664. // We can have situations when default ds changed and the panel level data source is different from the queries
  665. // In this case we use the query level data source as source for truth
  666. panel.datasource = target.datasource as DataSourceRef;
  667. }
  668. }
  669. }
  670. return panel;
  671. });
  672. }
  673. }
  674. if (panelUpgrades.length === 0) {
  675. return;
  676. }
  677. for (j = 0; j < this.dashboard.panels.length; j++) {
  678. for (k = 0; k < panelUpgrades.length; k++) {
  679. this.dashboard.panels[j] = panelUpgrades[k].call(this, this.dashboard.panels[j]);
  680. const rowPanels = this.dashboard.panels[j].panels;
  681. if (rowPanels) {
  682. for (n = 0; n < rowPanels.length; n++) {
  683. rowPanels[n] = panelUpgrades[k].call(this, rowPanels[n]);
  684. }
  685. }
  686. }
  687. }
  688. }
  689. // Migrates metric queries and/or annotation queries that use more than one statistic.
  690. // E.g query.statistics = ['Max', 'Min'] will be migrated to two queries - query1.statistic = 'Max' and query2.statistic = 'Min'
  691. // New queries, that were created during migration, are put at the end of the array.
  692. migrateCloudWatchQueries(panel: PanelModel) {
  693. for (const target of panel.targets || []) {
  694. if (isCloudWatchQuery(target)) {
  695. migrateCloudWatchQuery(target);
  696. if (target.hasOwnProperty('statistics')) {
  697. // New queries, that were created during migration, are put at the end of the array.
  698. const newQueries = migrateMultipleStatsMetricsQuery(target, [...panel.targets]);
  699. for (const newQuery of newQueries) {
  700. panel.targets.push(newQuery);
  701. }
  702. }
  703. }
  704. }
  705. }
  706. migrateCloudWatchAnnotationQuery() {
  707. for (const annotation of this.dashboard.annotations.list) {
  708. if (isLegacyCloudWatchAnnotationQuery(annotation)) {
  709. const newAnnotationQueries = migrateMultipleStatsAnnotationQuery(annotation);
  710. for (const newAnnotationQuery of newAnnotationQueries) {
  711. this.dashboard.annotations.list.push(newAnnotationQuery);
  712. }
  713. }
  714. }
  715. }
  716. upgradeToGridLayout(old: any) {
  717. let yPos = 0;
  718. const widthFactor = GRID_COLUMN_COUNT / 12;
  719. const maxPanelId = max(
  720. flattenDeep(
  721. map(old.rows, (row) => {
  722. return map(row.panels, 'id');
  723. })
  724. )
  725. );
  726. let nextRowId = maxPanelId + 1;
  727. if (!old.rows) {
  728. return;
  729. }
  730. // Add special "row" panels if even one row is collapsed, repeated or has visible title
  731. const showRows = some(old.rows, (row) => row.collapse || row.showTitle || row.repeat);
  732. for (const row of old.rows) {
  733. if (row.repeatIteration) {
  734. continue;
  735. }
  736. const height: any = row.height || DEFAULT_ROW_HEIGHT;
  737. const rowGridHeight = getGridHeight(height);
  738. const rowPanel: any = {};
  739. let rowPanelModel: PanelModel | undefined;
  740. if (showRows) {
  741. // add special row panel
  742. rowPanel.id = nextRowId;
  743. rowPanel.type = 'row';
  744. rowPanel.title = row.title;
  745. rowPanel.collapsed = row.collapse;
  746. rowPanel.repeat = row.repeat;
  747. rowPanel.panels = [];
  748. rowPanel.gridPos = {
  749. x: 0,
  750. y: yPos,
  751. w: GRID_COLUMN_COUNT,
  752. h: rowGridHeight,
  753. };
  754. rowPanelModel = new PanelModel(rowPanel);
  755. nextRowId++;
  756. yPos++;
  757. }
  758. const rowArea = new RowArea(rowGridHeight, GRID_COLUMN_COUNT, yPos);
  759. for (const panel of row.panels) {
  760. panel.span = panel.span || DEFAULT_PANEL_SPAN;
  761. if (panel.minSpan) {
  762. panel.minSpan = Math.min(GRID_COLUMN_COUNT, (GRID_COLUMN_COUNT / 12) * panel.minSpan);
  763. }
  764. const panelWidth = Math.floor(panel.span) * widthFactor;
  765. const panelHeight = panel.height ? getGridHeight(panel.height) : rowGridHeight;
  766. const panelPos = rowArea.getPanelPosition(panelHeight, panelWidth);
  767. yPos = rowArea.yPos;
  768. panel.gridPos = {
  769. x: panelPos.x,
  770. y: yPos + panelPos.y,
  771. w: panelWidth,
  772. h: panelHeight,
  773. };
  774. rowArea.addPanel(panel.gridPos);
  775. delete panel.span;
  776. if (rowPanelModel && rowPanel.collapsed) {
  777. rowPanelModel.panels?.push(panel);
  778. } else {
  779. this.dashboard.panels.push(new PanelModel(panel));
  780. }
  781. }
  782. if (rowPanelModel) {
  783. this.dashboard.panels.push(rowPanelModel);
  784. }
  785. if (!(rowPanelModel && rowPanel.collapsed)) {
  786. yPos += rowGridHeight;
  787. }
  788. }
  789. }
  790. }
  791. function getGridHeight(height: number | string) {
  792. if (isString(height)) {
  793. height = parseInt(height.replace('px', ''), 10);
  794. }
  795. if (height < MIN_PANEL_HEIGHT) {
  796. height = MIN_PANEL_HEIGHT;
  797. }
  798. const gridHeight = Math.ceil(height / (GRID_CELL_HEIGHT + GRID_CELL_VMARGIN));
  799. return gridHeight;
  800. }
  801. /**
  802. * RowArea represents dashboard row filled by panels
  803. * area is an array of numbers represented filled column's cells like
  804. * -----------------------
  805. * |******** ****
  806. * |******** ****
  807. * |********
  808. * -----------------------
  809. * 33333333 2222 00000 ...
  810. */
  811. class RowArea {
  812. area: number[];
  813. yPos: number;
  814. height: number;
  815. constructor(height: number, width = GRID_COLUMN_COUNT, rowYPos = 0) {
  816. this.area = new Array(width).fill(0);
  817. this.yPos = rowYPos;
  818. this.height = height;
  819. }
  820. reset() {
  821. this.area.fill(0);
  822. }
  823. /**
  824. * Update area after adding the panel.
  825. */
  826. addPanel(gridPos: any) {
  827. for (let i = gridPos.x; i < gridPos.x + gridPos.w; i++) {
  828. if (!this.area[i] || gridPos.y + gridPos.h - this.yPos > this.area[i]) {
  829. this.area[i] = gridPos.y + gridPos.h - this.yPos;
  830. }
  831. }
  832. return this.area;
  833. }
  834. /**
  835. * Calculate position for the new panel in the row.
  836. */
  837. getPanelPosition(panelHeight: number, panelWidth: number, callOnce = false): any {
  838. let startPlace, endPlace;
  839. let place;
  840. for (let i = this.area.length - 1; i >= 0; i--) {
  841. if (this.height - this.area[i] > 0) {
  842. if (endPlace === undefined) {
  843. endPlace = i;
  844. } else {
  845. if (i < this.area.length - 1 && this.area[i] <= this.area[i + 1]) {
  846. startPlace = i;
  847. } else {
  848. break;
  849. }
  850. }
  851. } else {
  852. break;
  853. }
  854. }
  855. if (startPlace !== undefined && endPlace !== undefined && endPlace - startPlace >= panelWidth - 1) {
  856. const yPos = max(this.area.slice(startPlace));
  857. place = {
  858. x: startPlace,
  859. y: yPos,
  860. };
  861. } else if (!callOnce) {
  862. // wrap to next row
  863. this.yPos += this.height;
  864. this.reset();
  865. return this.getPanelPosition(panelHeight, panelWidth, true);
  866. } else {
  867. return null;
  868. }
  869. return place;
  870. }
  871. }
  872. function upgradePanelLink(link: any): DataLink {
  873. let url = link.url;
  874. if (!url && link.dashboard) {
  875. url = `dashboard/db/${kbn.slugifyForUrl(link.dashboard)}`;
  876. }
  877. if (!url && link.dashUri) {
  878. url = `dashboard/${link.dashUri}`;
  879. }
  880. // some models are incomplete and have no dashboard or dashUri
  881. if (!url) {
  882. url = '/';
  883. }
  884. if (link.keepTime) {
  885. url = urlUtil.appendQueryToUrl(url, `$${DataLinkBuiltInVars.keepTime}`);
  886. }
  887. if (link.includeVars) {
  888. url = urlUtil.appendQueryToUrl(url, `$${DataLinkBuiltInVars.includeVars}`);
  889. }
  890. if (link.params) {
  891. url = urlUtil.appendQueryToUrl(url, link.params);
  892. }
  893. return {
  894. url: url,
  895. title: link.title,
  896. targetBlank: link.targetBlank,
  897. };
  898. }
  899. function updateVariablesSyntax(text: string) {
  900. const legacyVariableNamesRegex = /(__series_name)|(\$__series_name)|(__value_time)|(__field_name)|(\$__field_name)/g;
  901. return text.replace(legacyVariableNamesRegex, (match, seriesName, seriesName1, valueTime, fieldName, fieldName1) => {
  902. if (seriesName) {
  903. return '__series.name';
  904. }
  905. if (seriesName1) {
  906. return '${__series.name}';
  907. }
  908. if (valueTime) {
  909. return '__value.time';
  910. }
  911. if (fieldName) {
  912. return '__field.name';
  913. }
  914. if (fieldName1) {
  915. return '${__field.name}';
  916. }
  917. return match;
  918. });
  919. }
  920. function migrateSinglestat(panel: PanelModel) {
  921. // If 'grafana-singlestat-panel' exists, move to that
  922. if (config.panels['grafana-singlestat-panel']) {
  923. panel.type = 'grafana-singlestat-panel';
  924. return panel;
  925. }
  926. let returnSaveModel = false;
  927. if (!panel.changePlugin) {
  928. returnSaveModel = true;
  929. panel = new PanelModel(panel);
  930. }
  931. // To make sure PanelModel.isAngularPlugin logic thinks the current panel is angular
  932. // And since this plugin no longer exist we just fake it here
  933. panel.plugin = { angularPanelCtrl: {} } as PanelPlugin;
  934. // Otheriwse use gauge or stat panel
  935. if ((panel as any).gauge?.show) {
  936. gaugePanelPlugin.meta = config.panels['gauge'];
  937. panel.changePlugin(gaugePanelPlugin);
  938. } else {
  939. statPanelPlugin.meta = config.panels['stat'];
  940. panel.changePlugin(statPanelPlugin);
  941. }
  942. if (returnSaveModel) {
  943. return panel.getSaveModel();
  944. }
  945. return panel;
  946. }
  947. interface MigrateDatasourceNameOptions {
  948. returnDefaultAsNull: boolean;
  949. }
  950. export function migrateDatasourceNameToRef(
  951. nameOrRef: string | DataSourceRef | null | undefined,
  952. options: MigrateDatasourceNameOptions
  953. ): DataSourceRef | null {
  954. if (options.returnDefaultAsNull && (nameOrRef == null || nameOrRef === 'default')) {
  955. return null;
  956. }
  957. if (isDataSourceRef(nameOrRef)) {
  958. return nameOrRef;
  959. }
  960. const ds = getDataSourceSrv().getInstanceSettings(nameOrRef);
  961. if (!ds) {
  962. return { uid: nameOrRef as string }; // not found
  963. }
  964. return getDataSourceRef(ds);
  965. }
  966. // mutates transformations appending a new transformer after the existing one
  967. function appendTransformerAfter(panel: PanelModel, id: string, cfg: DataTransformerConfig) {
  968. if (panel.transformations) {
  969. const transformations: DataTransformerConfig[] = [];
  970. for (const t of panel.transformations) {
  971. transformations.push(t);
  972. if (t.id === id) {
  973. transformations.push({ ...cfg });
  974. }
  975. }
  976. panel.transformations = transformations;
  977. }
  978. return panel;
  979. }
  980. function upgradeValueMappingsForPanel(panel: PanelModel) {
  981. const fieldConfig = panel.fieldConfig;
  982. if (!fieldConfig) {
  983. return panel;
  984. }
  985. if (fieldConfig.defaults && fieldConfig.defaults.mappings) {
  986. fieldConfig.defaults.mappings = upgradeValueMappings(
  987. fieldConfig.defaults.mappings,
  988. fieldConfig.defaults.thresholds
  989. );
  990. }
  991. // Protect against no overrides
  992. if (Array.isArray(fieldConfig.overrides)) {
  993. for (const override of fieldConfig.overrides) {
  994. for (const prop of override.properties) {
  995. if (prop.id === 'mappings') {
  996. prop.value = upgradeValueMappings(prop.value);
  997. }
  998. }
  999. }
  1000. }
  1001. return panel;
  1002. }
  1003. function isCloudWatchQuery(target: DataQuery): target is CloudWatchMetricsQuery {
  1004. return (
  1005. target.hasOwnProperty('dimensions') &&
  1006. target.hasOwnProperty('namespace') &&
  1007. target.hasOwnProperty('region') &&
  1008. target.hasOwnProperty('metricName')
  1009. );
  1010. }
  1011. function isLegacyCloudWatchAnnotationQuery(
  1012. target: AnnotationQuery<DataQuery>
  1013. ): target is AnnotationQuery<LegacyAnnotationQuery> {
  1014. return (
  1015. target.hasOwnProperty('dimensions') &&
  1016. target.hasOwnProperty('namespace') &&
  1017. target.hasOwnProperty('region') &&
  1018. target.hasOwnProperty('prefixMatching') &&
  1019. target.hasOwnProperty('statistics')
  1020. );
  1021. }
  1022. function upgradeValueMappings(oldMappings: any, thresholds?: ThresholdsConfig): ValueMapping[] | undefined {
  1023. if (!oldMappings) {
  1024. return undefined;
  1025. }
  1026. const valueMaps: ValueMap = { type: MappingType.ValueToText, options: {} };
  1027. const newMappings: ValueMapping[] = [];
  1028. for (const old of oldMappings) {
  1029. // when migrating singlestat to stat/gauge, mappings are handled by panel type change handler used in that migration
  1030. if (old.type && old.options) {
  1031. // collect al value->text mappings in a single value map object. These are migrated by panel change handler as a separate value maps
  1032. if (old.type === MappingType.ValueToText) {
  1033. valueMaps.options = {
  1034. ...valueMaps.options,
  1035. ...old.options,
  1036. };
  1037. } else {
  1038. newMappings.push(old);
  1039. }
  1040. continue;
  1041. }
  1042. // Use the color we would have picked from thesholds
  1043. let color: string | undefined = undefined;
  1044. const numeric = parseFloat(old.text);
  1045. if (thresholds && !isNaN(numeric)) {
  1046. const level = getActiveThreshold(numeric, thresholds.steps);
  1047. if (level && level.color) {
  1048. color = level.color;
  1049. }
  1050. }
  1051. switch (old.type) {
  1052. case 1: // MappingType.ValueToText:
  1053. if (old.value != null) {
  1054. if (old.value === 'null') {
  1055. newMappings.push({
  1056. type: MappingType.SpecialValue,
  1057. options: {
  1058. match: SpecialValueMatch.Null,
  1059. result: { text: old.text, color },
  1060. },
  1061. });
  1062. } else {
  1063. valueMaps.options[String(old.value)] = {
  1064. text: old.text,
  1065. color,
  1066. };
  1067. }
  1068. }
  1069. break;
  1070. case 2: // MappingType.RangeToText:
  1071. newMappings.push({
  1072. type: MappingType.RangeToText,
  1073. options: {
  1074. from: +old.from,
  1075. to: +old.to,
  1076. result: { text: old.text, color },
  1077. },
  1078. });
  1079. break;
  1080. }
  1081. }
  1082. if (Object.keys(valueMaps.options).length > 0) {
  1083. newMappings.unshift(valueMaps);
  1084. }
  1085. return newMappings;
  1086. }
  1087. function migrateTooltipOptions(panel: PanelModel) {
  1088. if (panel.type === 'timeseries' || panel.type === 'xychart') {
  1089. if (panel.options.tooltipOptions) {
  1090. panel.options = {
  1091. ...panel.options,
  1092. tooltip: panel.options.tooltipOptions,
  1093. };
  1094. delete panel.options.tooltipOptions;
  1095. }
  1096. }
  1097. return panel;
  1098. }
  1099. // This migration is performed when there is a time series panel with all axes configured to be hidden
  1100. // To avoid breaking dashboards we add override that persists x-axis visibility
  1101. function ensureXAxisVisibility(panel: PanelModel) {
  1102. if (panel.type === 'timeseries') {
  1103. if (
  1104. (panel.fieldConfig as FieldConfigSource<GraphFieldConfig>)?.defaults.custom?.axisPlacement ===
  1105. AxisPlacement.Hidden
  1106. ) {
  1107. panel.fieldConfig = {
  1108. ...panel.fieldConfig,
  1109. overrides: [
  1110. ...panel.fieldConfig.overrides,
  1111. {
  1112. matcher: {
  1113. id: FieldMatcherID.byType,
  1114. options: FieldType.time,
  1115. },
  1116. properties: [
  1117. {
  1118. id: 'custom.axisPlacement',
  1119. value: AxisPlacement.Auto,
  1120. },
  1121. ],
  1122. },
  1123. ],
  1124. };
  1125. }
  1126. }
  1127. return panel;
  1128. }