-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathgrafana_pdf.js
More file actions
executable file
·973 lines (824 loc) · 41.8 KB
/
grafana_pdf.js
File metadata and controls
executable file
·973 lines (824 loc) · 41.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
'use strict';
const puppeteer = require('puppeteer');
const fs = require('fs');
console.log("Script grafana_pdf.js started...");
const args = process.argv.slice(2);
const url = args[0];
const auth_string = args[1];
const widthArg = args.find(arg => arg.startsWith('--pdfWidthPx='));
const heightArg = args.find(arg => arg.startsWith('--pdfHeightPx='));
const useServiceAccount = process.env.GRAFANA_SERVICE_ACCOUNT === 'true';
let outfile = null;
const width_px = widthArg ? parseInt(widthArg.split('=')[1], 10) : parseInt(process.env.PDF_WIDTH_PX, 10) || 1920;
const envHeight = process.env.PDF_HEIGHT_PX;
const overrideHeight = heightArg
? parseInt(heightArg.split('=')[1], 10)
: (envHeight && envHeight !== 'auto') ? parseInt(envHeight, 10) : null;
console.log("PDF width set to:", width_px);
console.log("PDF height set to:", overrideHeight !== null ? overrideHeight : "auto (auto-detected)");
const auth_header = useServiceAccount ? 'Bearer ' + auth_string : 'Basic ' + Buffer.from(auth_string).toString('base64');
console.log("Using authentication:", useServiceAccount ? "Service Account" : "Basic Auth");
(async () => {
try {
console.log("URL provided:", url);
console.log("Checking URL accessibility...");
const response = await fetch(url, {
method: 'GET',
headers: {'Authorization': auth_header}
});
if (!response.ok) {
throw new Error(`Unable to access URL. HTTP status: ${response.status}`);
}
const contentType = response.headers.get('content-type');
if (!contentType || !contentType.includes('text/html')) {
throw new Error("The URL provided is not a valid Grafana instance.");
}
let finalUrl = url;
if(process.env.FORCE_KIOSK_MODE === 'true') {
console.log("Checking if kiosk mode is enabled.");
const urlObj = new URL(finalUrl);
if (!urlObj.searchParams.has('kiosk')) {
console.log("Kiosk mode not enabled. Enabling it.");
urlObj.searchParams.set('kiosk', '1');
finalUrl = urlObj.toString();
}
console.log("Final URL with kiosk mode:", finalUrl);
}
console.log("Starting browser...");
const browser = await puppeteer.launch({
executablePath: process.env.PUPPETEER_EXECUTABLE_PATH,
headless: true,
args: [
'--no-sandbox',
'--disable-setuid-sandbox',
'--disable-gpu',
'--disable-dev-shm-usage'
]
});
const page = await browser.newPage();
console.log("Browser started...");
await page.setExtraHTTPHeaders({'Authorization': auth_header});
await page.setDefaultNavigationTimeout(process.env.PUPPETEER_NAVIGATION_TIMEOUT || 120000);
await page.setViewport({
width: width_px,
height: 800,
deviceScaleFactor: 2,
isMobile: false
});
console.log("Navigating to URL...");
await page.goto(finalUrl, {
waitUntil: ['networkidle0', 'domcontentloaded'],
timeout: process.env.PUPPETEER_NAVIGATION_TIMEOUT || 120000
});
console.log("Page loaded...");
if(process.env.DEBUG_MODE === 'true') {
page.on('console', msg => {
for (let i = 0; i < msg.args().length; ++i)
msg.args()[i].jsonValue().then(val => console.log(`[Browser console] ${msg.type()}:`, val));
});
}
let dashboardName = 'output_grafana';
let date = new Date().toISOString().split('T')[0];
const addRandomStr = process.env.ADD_RANDOM_STRING_TO_FILE_NAME === 'true';
if (process.env.EXTRACT_DATE_AND_DASHBOARD_NAME_FROM_HTML_PANEL_ELEMENTS === 'true') {
console.log("Extracting dashboard name and date from the HTML page...");
let scrapedDashboardName = await page.evaluate(() => {
const dashboardElement = document.getElementById('gfexp_display_actual_dashboard_title');
return dashboardElement ? dashboardElement.innerText.trim() : null;
});
let scrapedDate = await page.evaluate(() => {
const dateElement = document.getElementById('gfexp_display_actual_date');
return dateElement ? dateElement.innerText.trim() : null;
});
let scrapedPanelName = await page.evaluate(() => {
const scrapedPanelName = document.querySelectorAll('h6');
if (scrapedPanelName.length > 1) { // Multiple panels detected
console.log("Multiple panels detected. Unable to fetch a unique panel name. Using default value.")
return null;
}
if (scrapedPanelName[0] && scrapedPanelName[0].innerText.trim() === '') {
console.log("Empty panel name detected. Using default value.")
return null;
}
return scrapedPanelName[0] ? scrapedPanelName[0].innerText.trim() : null;
});
if (scrapedPanelName && !scrapedDashboardName) {
console.log("Panel name fetched:", scrapedPanelName);
dashboardName = scrapedPanelName;
} else if (!scrapedDashboardName) {
console.log("Dashboard name not found. Using default value.");
} else {
console.log("Dashboard name fetched:", scrapedDashboardName);
dashboardName = scrapedDashboardName;
}
if (scrapedPanelName && !scrapedDate) {
const urlParts = new URL(url);
const from = urlParts.searchParams.get('from');
const to = urlParts.searchParams.get('to');
if (from && to) {
const fromDate = isNaN(from) ? from.replace(/[^\w\s-]/g, '_') : new Date(parseInt(from)).toISOString().split('T')[0];
const toDate = isNaN(to) ? to.replace(/[^\w\s-]/g, '_') : new Date(parseInt(to)).toISOString().split('T')[0];
date = `${fromDate}_to_${toDate}`;
} else {
// using date in URL
date = new Date().toISOString().split('T')[0];
}
} else if (!scrapedDate) {
console.log("Date not found. Using default value.");
} else {
console.log("Date fetched:", date);
date = scrapedDate;
}
} else {
console.log("Extracting dashboard name and date from the URL...");
const urlParts = new URL(url);
const pathSegments = urlParts.pathname.split('/');
dashboardName = pathSegments[pathSegments.length - 1] || dashboardName;
const from = urlParts.searchParams.get('from');
const to = urlParts.searchParams.get('to');
if (from && to) {
const fromDate = isNaN(from) ? from.replace(/[^\w\s-]/g, '_') : new Date(parseInt(from)).toISOString().split('T')[0];
const toDate = isNaN(to) ? to.replace(/[^\w\s-]/g, '_') : new Date(parseInt(to)).toISOString().split('T')[0];
date = `${fromDate}_to_${toDate}`;
} else {
date = new Date().toISOString().split('T')[0];
}
console.log("Dashboard name fetched from URL:", dashboardName);
console.log("Trying to fetch the panel name from the page...")
let scrapedPanelName = await page.evaluate(() => {
const scrapedPanelName = document.querySelectorAll('h6');
console.log(scrapedPanelName)
if (scrapedPanelName.length > 1) { // Multiple panels detected
console.log("Multiple panels detected. Unable to fetch a unique panel name. Using default value.")
return null;
}
if (scrapedPanelName[0] && scrapedPanelName[0].innerText.trim() === '') {
console.log("Empty panel name detected. Using default value.")
return null;
}
return scrapedPanelName[0] ? scrapedPanelName[0].innerText.trim() : null;
});
if (scrapedPanelName) {
console.log("Panel name fetched:", scrapedPanelName);
dashboardName = scrapedPanelName;
}
console.log("Date fetched from URL:", date);
}
console.log("addRandomStr", addRandomStr);
outfile = `./output/${dashboardName.replace(/\s+/g, '_')}_${date.replace(/\s+/g, '_')}${addRandomStr ? '_' + Math.random().toString(36).substring(7) : ''}.pdf`;
const loginPageDetected = await page.evaluate(() => {
const resetPasswordButton = document.querySelector('a[href*="reset-email"]');
return !!resetPasswordButton;
})
if (loginPageDetected) {
throw new Error("Login page detected. Check your credentials.");
}
// Debug panel count and status - improved for Grafana 12
const panelCount = await page.evaluate(() => {
const panelSelectors = [
'[data-testid="panel"]',
'.panel-container',
'.react-grid-item',
'.dashboard-panel'
];
let counts = {};
for (const selector of panelSelectors) {
const elements = document.querySelectorAll(selector);
counts[selector] = elements.length;
}
return counts;
});
console.log("Panel detection counts:", panelCount);
if(process.env.DEBUG_MODE === 'true') {
const documentHTML = await page.evaluate(() => {
return document.querySelector("*").outerHTML;
});
if (!fs.existsSync('./debug')) {
fs.mkdirSync('./debug');
}
const filename = `./debug/debug_${dashboardName.replace(/\s+/g, '_')}_${date.replace(/\s+/g, '_')}${'_' + Math.random().toString(36).substring(7)}.html`;
fs.writeFileSync(filename, documentHTML);
console.log("Debug HTML file saved at:", filename);
// Enhanced debug information for panel visibility
const panelInfo = await page.evaluate(() => {
const allSelectors = [
'[data-testid="panel"]',
'.panel-container',
'.react-grid-item',
'.dashboard-panel'
];
// Find which selector works for this Grafana version
let panels = [];
let usedSelector = '';
for (const selector of allSelectors) {
const elements = document.querySelectorAll(selector);
if (elements && elements.length > 0) {
panels = Array.from(elements);
usedSelector = selector;
break;
}
}
return {
usedSelector,
panelCount: panels.length,
panels: panels.map((panel, index) => {
const rect = panel.getBoundingClientRect();
const style = window.getComputedStyle(panel);
return {
index,
visible: rect.width > 0 && rect.height > 0,
displayed: style.display !== 'none',
position: {
top: rect.top,
left: rect.left,
width: rect.width,
height: rect.height
},
computedStyle: {
display: style.display,
visibility: style.visibility,
opacity: style.opacity
}
};
})
};
});
console.log("Panel detection details:", JSON.stringify(panelInfo, null, 2));
}
// IMPROVED: Enhanced panel detection and rendering for Grafana 12 compatibility
console.log("Ensuring panels are properly rendered...");
await page.evaluate(async () => {
// Force all known panel types to be visible
const panelSelectors = [
'[data-testid="panel"]',
'.panel-container',
'.react-grid-item',
'.dashboard-panel',
'.grafana-dashboard-panel'
];
for (const selector of panelSelectors) {
const panels = document.querySelectorAll(selector);
if (panels.length > 0) {
console.log(`Found ${panels.length} panels with selector ${selector}`);
// Make sure all panels are visible
Array.from(panels).forEach((panel, i) => {
panel.style.display = 'block';
panel.style.visibility = 'visible';
panel.style.opacity = '1';
console.log(`Ensured visibility of panel ${i+1}`);
});
}
}
});
async function expandCollapsedPanels(page) {
const debugMode = process.env.DEBUG_MODE === 'true';
if (debugMode) console.log('[DEBUG] Searching for collapsed panels/rows...');
// Panel and row selectors for different Grafana versions
const selectors = [
'[data-testid="panel"][aria-expanded="false"]',
'.panel-collapsed',
'.row-collapsed',
'.dashboard-row--collapsed',
'.dashboard-row[aria-expanded="false"]',
'.panel-title-container .fa-chevron-right',
'.panel-title-container .fa-angle-right',
'.panel-title-container .fa-caret-right',
'.dashboard-row__title .fa-chevron-right',
'.dashboard-row__title .fa-angle-right',
'.dashboard-row__title .fa-caret-right',
'.row-title-container .fa-chevron-right',
'.row-title-container .fa-angle-right',
'.row-title-container .fa-caret-right',
'button[aria-label="Expand row"]'
];
const expanded = await page.evaluate(async (selectors, debugMode) => {
let expandedCount = 0;
for (const selector of selectors) {
const elements = document.querySelectorAll(selector);
if (elements.length > 0 && debugMode) {
console.log(`[DEBUG] Found expandable elements for ${selector}: ${elements.length}`);
}
for (const el of elements) {
try {
// Try clicking on the expand icon
if (typeof el.click === 'function') {
el.click();
expandedCount++;
if (debugMode) console.log(`[DEBUG] Clicked on element: ${selector}`);
} else {
// Fallback: Try clicking on parent element
if (el.parentElement && typeof el.parentElement.click === 'function') {
el.parentElement.click();
expandedCount++;
if (debugMode) console.log(`[DEBUG] Clicked on parent element: ${selector}`);
}
}
} catch (error) {
if (debugMode) console.log(`[DEBUG] Error clicking on ${selector}: ${error.message}`);
}
}
}
// Wait after clicks so content can load
if (expandedCount > 0) {
await new Promise(resolve => setTimeout(resolve, 2000 + expandedCount * 500));
}
return expandedCount;
}, selectors, debugMode);
if (debugMode) console.log(`[DEBUG] Number of expanded panels/rows: ${expanded}`);
return expanded;
}
const expandPanels = process.env.EXPAND_COLLAPSED_PANELS !== 'false';
if (expandPanels) {
console.log("Searching and expanding collapsed panels/rows...");
const expanded = await expandCollapsedPanels(page);
if (expanded > 0) {
console.log(`Expanded ${expanded} panels/rows. Waiting for content to load...`);
await page.evaluate(timeout => new Promise(resolve => setTimeout(resolve, timeout)), 2000 + expanded * 500);
} else {
console.log("No collapsed panels/rows found.");
}
} else {
console.log("Automatic expansion of collapsed panels is disabled.");
}
const expandTables = process.env.EXPAND_TABLES !== 'false';
if (expandTables) {
console.log("Looking for tables to expand...");
const expandedTables = await page.evaluate(async () => {
const panelSelectors = [
'div.react-grid-item',
'div[data-griditem-key]',
'div[class*="react-grid-item"]'
];
const tableSelectors = [
'div[role="table"]',
'[data-testid*="panel content"] div[role="table"]',
'[data-panel-id] div[role="table"]'
];
const strategies = [
{
name: 'Grafana ≥ v11.5 – nested scrollable view',
selector: '.scrollbar-view > div div[data-testid*="table body"] .scrollbar-view > div > div',
},
{
name: 'Grafana ≤ v11 – fallback inner wrapper',
selector: '.scrollbar-view > div > div',
},
{
name: 'Fallback: direct inner content with height',
selector: '.scrollbar-view div[style*="height"]',
}
];
const expandedPanels = new Set();
for (const panelSel of panelSelectors) {
const panels = Array.from(document.querySelectorAll(panelSel));
for (const panel of panels) {
if (expandedPanels.has(panel)) continue;
let table = null;
for (const tSel of tableSelectors) {
table = panel.querySelector(tSel);
if (table) break;
}
if (!table) continue;
for (const strat of strategies) {
const target = table.querySelector(strat.selector);
if (!target) continue;
const originalHeight = target.offsetHeight;
const panelHeight = panel.offsetHeight;
if (originalHeight > panelHeight) {
const newHeight = originalHeight + 100;
panel.style.height = `${newHeight}px`;
panel.style.minHeight = `${newHeight}px`;
await new Promise(resolve => setTimeout(resolve, 100));
const updatedHeight = target.offsetHeight;
console.log(`Height after layout update: ${updatedHeight}px (was: ${originalHeight})`);
if (updatedHeight !== newHeight) {
const finalHeight = updatedHeight + 100;
panel.style.height = `${finalHeight}px`;
panel.style.minHeight = `${finalHeight}px`;
console.log(`Re-adjusted panel to match updated child height: ${finalHeight}px`);
}
console.log(`Table panel expanded using strategy: ${strat.name}`);
expandedPanels.add(panel);
break;
}
}
}
}
return expandedPanels.size;
});
console.log(`Expanded ${expandedTables} scrollable table(s).`);
}
await page.evaluate((hideDashboardControls) => {
const selectorsToHide = [
'.panel-info-corner',
'.react-resizable-handle',
'div[data-testid*="Alert error"]',
'div[data-testid*="title-items-container"]',
'div[class*="toolbar-button-panel-menu"]'
];
if (hideDashboardControls) {
selectorsToHide.push(
'.dashboard-controls',
'.dashboard-toolbar',
'div[data-testid*="dashboard controls"]',
);
}
selectorsToHide.forEach(selector => {
document.querySelectorAll(selector).forEach(el => {
el.hidden = true;
});
});
}, process.env.HIDE_DASHBOARD_CONTROLS === 'true');
// IMPROVED: Enhanced height detection with Grafana 12 specific selectors
let scrollableSection = null;
console.log("Forcing DOM reflow and layout recalculation...");
await page.evaluate(() => {
// try to resize the window to force layout recalculation
window.dispatchEvent(new Event('resize'));
// try to force a reflow
document.body.style.display = 'none';
document.body.offsetHeight;
document.body.style.display = 'block';
return new Promise(resolve => setTimeout(resolve, 500));
});
console.log("Layout reflow completed. Re-calculating content height.");
const totalHeight = await page.evaluate(() => {
console.log("Attempting to detect page height with multiple selectors...");
// Priority list of selectors for different Grafana versions
const selectors = [
'#pageContent div[class*="canvas-wrapper-old"]', // Grafana 12.0.2+
'[data-testid="dashboard-grid"]', // Grafana 12 dashboard grid (highest priority)
'[data-testid="scrollbar-view"]', // Grafana 11.5+
'.scrollbar-view', // Grafana <= 11.4
'.main-view', // Alternative main view
'.dashboard-container', // Dashboard container
'.react-grid-layout', // Dashboard panels grid
'.dashboard-scroll', // Scrollable dashboard area
'main', // Main HTML element
'.panel-container', // Panel container fallback
'body' // Ultimate fallback
];
let selectorUsed = '';
// Try each selector until we find one
for (const selector of selectors) {
console.log(`Trying selector: ${selector}`);
scrollableSection = document.querySelector(selector);
if (scrollableSection) {
selectorUsed = selector;
console.log(`Successfully found element with selector: ${selector}`);
break;
}
}
if (!scrollableSection) {
console.log("No suitable element found, using document.body as fallback");
scrollableSection = document.body;
selectorUsed = 'body (fallback)';
}
// Different height calculation strategies
let height = null;
// NEW: Grafana 12 specific panel height calculation
const allPanelSelectors = [
'#pageContent div[class*="canvas-wrapper-old"]',
'[data-testid="panel"]',
'.panel-container',
'.react-grid-item',
'.dashboard-panel'
];
let panels = [];
for (const selector of allPanelSelectors) {
const elements = document.querySelectorAll(selector);
if (elements && elements.length > 0) {
panels = Array.from(elements);
console.log(`Using ${selector} for panel height calculation, found ${panels.length} panels`);
break;
}
}
if (panels.length > 0) {
let maxBottom = 0;
panels.forEach((panel, idx) => {
const rect = panel.getBoundingClientRect();
console.log(`Panel ${idx+1} position: top=${rect.top}, bottom=${rect.bottom}`);
maxBottom = Math.max(maxBottom, rect.bottom);
});
if (maxBottom > 100) {
height = Math.ceil(maxBottom + 100); // Add padding
console.log(`Height calculated from ${panels.length} panels: ${height}`);
return height;
}
}
// Original height calculation strategies as fallback
if (!height && scrollableSection.firstElementChild && scrollableSection.firstElementChild.scrollHeight > 100) {
height = scrollableSection.firstElementChild.scrollHeight;
console.log(`Height from firstElementChild.scrollHeight: ${height} (selector: ${selectorUsed})`);
}
if (!height && scrollableSection.scrollHeight > 100) {
height = scrollableSection.scrollHeight;
console.log(`Height from element.scrollHeight: ${height} (selector: ${selectorUsed})`);
}
if (!height) {
const rect = scrollableSection.getBoundingClientRect();
if (rect.height > 100) {
height = Math.ceil(rect.height);
console.log(`Height from getBoundingClientRect: ${height} (selector: ${selectorUsed})`);
}
}
// Fallback height
if (!height) {
height = Math.max(window.innerHeight * 2, 1600);
console.log(`Using fallback height: ${height}`);
}
console.log(`Final height determined: ${height} using selector: ${selectorUsed}`);
return height;
});
if (!totalHeight || totalHeight < 100) {
console.log("Warning: Could not determine reliable page height, using fallback of 1600px");
const fallbackHeight = 1600;
// Advanced scrolling technique for Grafana 12
await page.evaluate(async () => {
console.log("Performing comprehensive scrolling to ensure all content is loaded...");
// Progressive scrolling with pauses
const viewportHeight = window.innerHeight;
const maxScrolls = 25; // Increased for Grafana 12
const scrollDelay = 750;
for (let i = 0; i < maxScrolls; i++) {
window.scrollTo(0, i * viewportHeight / 2);
await new Promise(resolve => setTimeout(resolve, scrollDelay));
}
// Scroll back to top
window.scrollTo(0, 0);
await new Promise(resolve => setTimeout(resolve, scrollDelay));
});
console.log("Page height set to fallback:", fallbackHeight);
} else {
console.log("Page height successfully determined:", totalHeight);
// Enhanced scrolling for Grafana 12
await page.evaluate(async () => {
console.log("Performing enhanced scrolling to load all content...");
// Progressive scroll approach
const viewportHeight = window.innerHeight;
const totalScrolls = Math.ceil(document.body.scrollHeight / (viewportHeight / 3));
const scrollDelay = 750;
console.log(`Planning ${totalScrolls} scroll steps`);
// First scroll down gradually
for (let i = 0; i < totalScrolls; i++) {
window.scrollTo(0, i * viewportHeight / 3);
await new Promise(resolve => setTimeout(resolve, scrollDelay));
}
// Then scroll back up gradually
for (let i = totalScrolls; i >= 0; i--) {
window.scrollTo(0, i * viewportHeight / 3);
await new Promise(resolve => setTimeout(resolve, scrollDelay));
}
console.log("Progressive scrolling completed");
});
}
if (process.env.CHECK_QUERIES_TO_COMPLETE === 'true' && !finalUrl.includes('viewPanel=')) {
console.log("Waiting for all queries to complete...");
await page.evaluate(async () => {
if (scrollableSection) {
console.log("Scrolling to the bottom of the page to trigger all queries...");
const totalHeight = scrollableSection.scrollHeight;
const viewportHeight = window.innerHeight;
let scrolled = 0;
while (scrolled < totalHeight) {
scrollableSection.scrollBy(0, viewportHeight);
scrolled += viewportHeight;
await new Promise(res => setTimeout(res, 500));
}
}
});
const dashboardQueryInfo = await page.evaluate(async (excludedTypes) => {
const entry = performance.getEntriesByType("resource").find(r => {
if (!['fetch','xmlhttprequest'].includes(r.initiatorType)) return false;
const u = r.name;
return /\/api\/dashboards\/uid\/[^/?#]+/.test(u) ||
/\/apis\/dashboard\.grafana\.app\/v1beta1\/namespaces\/[^/]+\/dashboards\/[^/]+\/dto(?:\?|$)/.test(u);
});
if (!entry) throw new Error("Dashboard request not found.");
const res = await fetch(entry.name, { credentials: 'include' });
if (!res.ok) throw new Error(`Fetch failed: ${res.status}`);
const json = await res.json();
const root =
json?.spec ??
json?.model ??
json?.dashboard ??
json;
const panels = Array.isArray(root?.panels) ? root.panels : [];
const templating = root?.templating?.list ?? [];
function countPanels(list) {
let n = 0;
for (const p of list) {
if (!p || excludedTypes.includes(p.type)) continue;
if (p.type === 'row' && Array.isArray(p.panels)) { n += countPanels(p.panels); continue; }
const hasDs = !!p.datasource || (Array.isArray(p.targets) && p.targets.some(t => t?.datasource));
if (hasDs) n++;
}
return n;
}
const valid = countPanels(panels);
const templatingQueries = templating.filter(v => v?.type === 'query').length;
console.log(`✔ Expected queries: ${valid + templatingQueries}`);
return { valid, templating: templatingQueries };
}, ['text']);
const panelErrorSelectors = [
'.panel-content .alert-error',
'.panel-content .panel-error',
'.panel-content .panel-alert-error',
'.react-panel-error',
'[data-testid="panel-error-container"]',
'.panel-content .render-error',
'.react-grid-item div[data-testid*="header-container"] button[data-testid*="status error"]'
];
const panelErrorCount = await page.evaluate((selectors) => {
const matchedErrors = selectors.flatMap(selector =>
Array.from(document.querySelectorAll(selector))
);
const uniquePanels = new Set();
matchedErrors.forEach(errEl => {
const panel =
errEl.closest('.panel-container') ||
errEl.closest('.panel') ||
errEl.closest('[data-testid*="panel"]') ||
errEl.closest('.react-grid-item');
if (panel) {
uniquePanels.add(panel);
const titleSelectors = [
'div[class*="panel-title"] h2',
'[data-testid="panel-title"]',
'.panel-header span',
'h2', 'h3', 'h4',
];
let title = '[Untitled Panel]';
for (const selector of titleSelectors) {
const el = panel.querySelector(selector);
if (el?.textContent?.trim()) {
title = el.textContent.trim();
break;
}
}
console.log(`🛑 Panel with error detected: "${title}"`);
}
});
console.log(`🛑 Total panels with errors: ${uniquePanels.size}`);
return uniquePanels.size;
}, panelErrorSelectors);
const variableErrorSelectors = [
'div[data-testid*="template variable"] label svg',
];
const variableQueryErrorCount = await page.evaluate((selectors) => {
const matched = selectors.flatMap(sel => Array.from(document.querySelectorAll(sel)));
const variableWrappers = new Set();
matched.forEach(el => {
const variableWrapper = el.closest('.variable-wrapper') ||
el.closest('.template-variable-wrapper') ||
el.closest('div[data-testid*="template variable"]');
if (variableWrapper) {
variableWrappers.add(variableWrapper);
const titleSelectors = [
'span.variable-label',
'label[data-testid*="template variable"]',
'.variable-name',
'.variable-title'
];
let title = '[Untitled Variable]';
for (const selector of titleSelectors) {
const el = variableWrapper.querySelector(selector);
if (el?.textContent?.trim()) {
title = el.textContent.trim();
break;
}
}
console.log(`🛑 Variable with query error detected: "${title}"`);
}
});
console.log(`🛑 Variables with query errors detected: ${variableWrappers.size}`);
return variableWrappers.size;
}, variableErrorSelectors);
const panelCountFromJson = dashboardQueryInfo.valid;
const variableQueryCount = dashboardQueryInfo.templating;
const effectiveVariableQueryCount = Math.max(0, variableQueryCount - variableQueryErrorCount);
const effectivePanelQueryCount = Math.max(0, (panelCountFromJson - panelErrorCount)) + effectiveVariableQueryCount;
const maxWaitTime = parseInt(process.env.CHECK_QUERIES_TO_COMPLETE_QUERIES_COMPLETION_TIMEOUT, 10) || 60000;
const maxStableWait = parseInt(process.env.CHECK_QUERIES_TO_COMPLETE_MAX_QUERY_COMPLETION_TIME, 10) || 30000;
const interval = parseInt(process.env.CHECK_QUERIES_TO_COMPLETE_QUERIES_INTERVAL, 10) || 4000;
let elapsedTime = 0;
let lastCompletedCount = 0;
let stableCountTime = 0;
console.log(`Waiting for queries to complete... Expected: ${effectivePanelQueryCount}, Timeout: ${maxWaitTime}ms, Interval: ${interval}ms`);
while (elapsedTime < maxWaitTime) {
const completedQueryCount = await page.evaluate(() =>
performance.getEntriesByType("resource")
.filter(r => r.initiatorType === 'fetch' && r.name.includes('query')).length
);
console.log(`Completed Queries: ${completedQueryCount} / ${effectivePanelQueryCount}`);
if (completedQueryCount >= effectivePanelQueryCount) {
console.log("All expected queries have completed.");
break;
}
if (completedQueryCount === lastCompletedCount) {
stableCountTime += interval;
if (stableCountTime >= maxStableWait) {
throw new Error(`❌ Query completion seems stuck — no progress after ${maxStableWait}ms.`);
}
} else {
stableCountTime = 0;
}
lastCompletedCount = completedQueryCount;
await new Promise(res => setTimeout(res, interval));
elapsedTime += interval;
console.log(`Waiting... Elapsed: ${elapsedTime}ms`);
}
if (elapsedTime >= maxWaitTime) {
throw new Error("Timeout: Not all queries completed in time.");
}
}
// Add a final check for all panels and ensure they're visible
await page.evaluate(async () => {
console.log("Final check for panel visibility...");
// Find all panels with any known selector
const panelSelectors = [
'#pageContent div[class*="canvas-wrapper-old"]',
'[data-testid="panel"]',
'.panel-container',
'.react-grid-item',
'.dashboard-panel',
'.grafana-panel'
];
let allPanels = [];
for (const selector of panelSelectors) {
const panels = document.querySelectorAll(selector);
if (panels && panels.length > 0) {
allPanels = Array.from(panels);
console.log(`Found ${panels.length} panels with selector ${selector}`);
break;
}
}
if (allPanels.length > 0) {
// Make sure all panels are visible
allPanels.forEach((panel, i) => {
panel.style.display = 'block';
panel.style.visibility = 'visible';
panel.style.opacity = '1';
// Ensure any lazy-loaded content inside panels is visible
const charts = panel.querySelectorAll('.graph-canvas, .graph-panel, canvas, svg');
charts.forEach(chart => {
chart.style.visibility = 'visible';
chart.style.opacity = '1';
});
});
console.log(`Ensured visibility of ${allPanels.length} panels`);
}
// Extra wait to ensure charts render
await new Promise(resolve => setTimeout(resolve, 2000));
});
// Final wait for all panels to be fully rendered
console.log("Final wait for all panels to render completely...");
await page.evaluate(timeout => {
return new Promise(resolve => setTimeout(resolve, timeout));
}, 5000);
const finalHeight = totalHeight && totalHeight >= 100 ? totalHeight : 1600;
await page.setViewport({
width: width_px,
height: finalHeight,
deviceScaleFactor: 2,
isMobile: false
});
console.log("Generating PDF...");
let pdfHeight = finalHeight;
if (overrideHeight && !isNaN(overrideHeight)) {
pdfHeight = overrideHeight;
console.log(`Forcing PDF page height to override: ${pdfHeight}px`);
} else {
console.log(`PDF page height will follow auto-detected content height: ${pdfHeight}px`);
}
await page.emulateMediaType('screen');
await page.addStyleTag({
content: `
html, body {
height: auto !important;
overflow: visible !important;
-webkit-print-color-adjust: exact !important;
print-color-adjust: exact !important;
}
@page { size: ${width_px}px ${pdfHeight}px; margin: 0; }
`
});
await page.pdf({
path: outfile,
width: width_px + 'px',
height: pdfHeight + 'px',
printBackground: true,
scale: 1,
displayHeaderFooter: false,
margin: {top: 0, right: 0, bottom: 0, left: 0}
});
console.log(`PDF generated: ${outfile}`);
await browser.close();
console.log("Browser closed.");
process.send({ success: true, path: outfile });
} catch (error) {
console.error("Error during PDF generation:", error.message);
process.send({ success: false, error: error.message });
process.exit(1);
}
})();