forked from green-coding-solutions/green-metrics-tool
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstats.js
More file actions
1300 lines (1109 loc) · 55.4 KB
/
Copy pathstats.js
File metadata and controls
1300 lines (1109 loc) · 55.4 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
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
class CO2Tangible extends HTMLElement {
connectedCallback() {
this.innerHTML = `
<div class="ui blue icon message">
<i class="question circle icon"></i>
<div class="content">
<div class="header">
How much is this value of CO2 to something tangible?
</div>
<p>CO2 of software per run is relatively small. The values get big though cause software is repeatedly run.<br>Therefore the following numbers reflect the CO2 value of the software as if it was run for 1,000 times a day over the course of a year (365 days).</p>
<p>Source of CO2 to Tree etc. conversion: <a href="https://www.epa.gov/energy/greenhouse-gas-equivalencies-calculator">EPA</a></p>
</div>
</div>
<div class="ui five cards stackable">
<div class="card">
<div class="content">
<div class="ui header">Trees</div>
<div class="ui small statistic">
<div class="value">
<i class="tree icon"></i> <span class="co2-trees">-</span>
</div>
</div>
</div>
</div>
<div class="card">
<div class="content">
<div class="ui header">Distance driven</div>
<div class="ui small statistic">
<div class="value">
<i class="truck pickup icon"></i> <span class="co2-distance-driven">-</span>
</div>
</div>
<div class="ui bottom right attached label distance-units">in miles by car</div>
</div>
</div>
<div class="card">
<div class="content">
<div class="ui header">Gasoline</div>
<div class="ui small statistic">
<div class="value">
<i class="gas pump icon"></i> <span class="co2-gasoline">-</span>
</div>
</div>
<div class="ui bottom right attached label gasoline-units">in gallons</div>
</div>
</div>
<div class="card">
<div class="content">
<div class="ui header">Flights</div>
<div class="ui small statistic">
<div class="value">
<i class="plane departure icon"></i> <span class="co2-flights">-</span>
</div>
</div>
<div class="ui bottom right attached label">Berlin » NYC</div>
</div>
</div>
<div class="ui card">
<div class="ui content">
<div class="ui header">co2 budget / day</div>
<div class="ui small statistic">
<div class="value">
<i class="user icon"></i> <span class="co2-budget-utilization"> - %</span>
</div>
</div>
<div class="ui bottom right attached label">for CPU + Memory + Network</div>
</div>
</div>
</div><!-- end ui five cards stackable -->`;
}
}
customElements.define('co2-tangible', CO2Tangible);
const getElephantServiceUrl = () => {
return typeof ELEPHANT_URL === 'string' ? ELEPHANT_URL.trim() : ''
};
const setAndShowAnalyticsLinks = (run_id, run_data) => {
if (getElephantServiceUrl() !== '') {
const simulationLink = document.querySelector('#analytics-simulation-link');
if (simulationLink) {
simulationLink.href = `simulation.html?id=${encodeURIComponent(run_id)}`;
}
const simulationYearlyLink = document.querySelector('#analytics-simulation-yearly-link');
if (simulationYearlyLink) {
simulationYearlyLink.href = `simulation-yearly.html?id=${encodeURIComponent(run_id)}`;
}
} else {
document.querySelector('a[data-tab="analytics-simulation"]').classList.add('hidden');
}
const timelineLink = document.querySelector('#analytics-timeline-link');
if (!timelineLink) return;
const timelineParams = new URLSearchParams();
if (run_data?.uri) timelineParams.set('uri', run_data.uri);
if (run_data?.branch) timelineParams.set('branch', run_data.branch);
if (run_data?.filename) timelineParams.set('filename', run_data.filename);
if (run_data?.machine_id != null) timelineParams.set('machine_id', String(run_data.machine_id));
if (run_data?.usage_scenario_variables && Object.keys(run_data.usage_scenario_variables).length > 0) {
timelineParams.set('usage_scenario_variables', JSON.stringify(run_data.usage_scenario_variables));
}
if (timelineParams.get('uri')) {
timelineLink.href = `timeline.html?${timelineParams.toString()}`;
timelineLink.classList.remove('disabled');
return;
}
timelineLink.removeAttribute('href');
timelineLink.classList.add('disabled');
};
const fetchAndFillRunData = async (run_id) => {
let run = null;
try {
run = await makeAPICall('/v2/run/' + run_id)
} catch (err) {
showNotification('Could not get run data from API', err);
return
}
const run_data = run.data
const run_data_accordion_node = document.querySelector('#run-data-accordion');
setAndShowAnalyticsLinks(run_id, run_data);
for (const item in run_data) {
if (item == 'machine_id') {
run_data_accordion_node.insertAdjacentHTML('beforeend', `<tr><td><strong>${escapeString(item)}</strong></td><td>${escapeString(run_data[item])} (${escapeString(GMT_MACHINES[run_data[item]] || run_data[item])})</td></tr>`);
} else if (item == 'runner_arguments') {
fillRunTab('#runner-arguments', run_data[item]); // recurse
} else if (item == 'machine_specs') {
fillRunTab('#machine-specs', run_data[item]); // recurse
} else if(item == 'usage_scenario') {
// we would really like to highlight here what was replaced, but since the replace mechanism is so powerful that even the !include command could be modified we can only replace after the file was merged. Thus it is not possible to know after what the replacements are
document.querySelector("#usage-scenario").textContent = json2yaml(run_data[item]);
} else if(item == 'usage_scenario_variables') {
if (Object.keys(run_data[item]).length > 0) {
const container = document.querySelector("#usage-scenario-variables ul");
for (const key in run_data[item]) {
container.insertAdjacentHTML('beforeend', `<li><span class="ui label">${escapeString(key)}=${escapeString(run_data[item][key])}</span></li>`)
}
} else {
document.querySelector("#usage-scenario-variables").insertAdjacentHTML('beforeend', `N/A`)
}
} else if(item == 'container_dependencies') {
// skip. Is used in 'containers'
} else if(item == 'containers') {
if (run_data[item] == null) continue; // can be null
const containers_node = document.querySelector('#containers');
for (const ctr_name in run_data[item]) {
containers_node.insertAdjacentHTML('beforeend', `
<div id="container-${escapeString(ctr_name)}" class="ui segment">
<h3>${escapeString(ctr_name)}</h3>
<p>CPUS: ${escapeString(run_data[item][ctr_name].cpus)}</p>
<p>CPUSet: ${escapeString(run_data[item][ctr_name].cpuset)}</p>
<p>Memory Limit: ${escapeString(run_data[item][ctr_name].mem_limit)} (${Math.round(run_data[item][ctr_name].mem_limit/1024**2)} MB)</p>
<p>Memory Swap: ${escapeString(run_data[item][ctr_name].memory_swap)} (${Math.round(run_data[item][ctr_name].memory_swap/1024**2)} MB)</p>
<p>Memory Swappiness: ${escapeString(run_data[item][ctr_name].memory_swappiness)}</p>
<p>OOM Score Adj.: ${escapeString(run_data[item][ctr_name].oom_score_adj)}</p>
<p>Image: ${escapeString(run_data?.container_dependencies?.[ctr_name]?.['source']?.['image'])}</p>
<p>Hash: ${escapeString(run_data?.container_dependencies?.[ctr_name]?.['source']?.['hash'])}</p>
<p>OS: ${escapeString(run_data?.container_dependencies?.[ctr_name]?.['source']?.['os'])}</p>
<p data-tooltip="Kernel Version will be same as host for Linux docker containers. On macOS it will be the kernel of the VM" data-position="top center">Kernel Version <i class="question circle icon"></i>: ${escapeString(run_data?.container_dependencies?.[ctr_name]?.['source']?.['kernel_version'])}</p>
<h4>Dependencies</h4>
${renderUsageScenarioDependencies(ctr_name, run_data?.container_dependencies)}
</div>`);
}
document.querySelectorAll('.ui.accordion.container-dependencies').forEach(accordion => {
$(accordion).accordion();
});
} else if(item == 'logs') {
const logsData = run_data[item];
if (logsData === null) {
// Display simple message indicating no output was produced
document.querySelector("#logs").innerHTML = '<pre>Run did not produce any logs to be captured</pre>';
} else if (typeof logsData === 'object' && logsData !== null) {
// Handle JSON structure logs
// Check first if any logs have type 'legacy' - if so, render as simple text instead of structured interface
const hasLegacyLogs = Object.values(logsData).some(containerLogs =>
Array.isArray(containerLogs) && containerLogs.some(log => log.type === 'legacy')
);
if (!hasLegacyLogs) {
renderLogsInterface(logsData);
} else {
renderLegacyLogsFromJson(logsData);
}
} else {
// Handle legacy plain text logs (pre-JSON structure)
displayLegacyLogs(run_data[item]);
}
} else if(item == 'measurement_config') {
fillRunTab('#measurement-config', run_data[item]); // recurse
} else if(item == 'id' || item == 'phases') {
// skip
} else if(item == 'relations') {
if (run_data[item] == null) continue; // can be empty
for (relation in run_data[item]) {
const url = run_data[item][relation]['url'];
const httpsUrl = toHttpsUri(url);
const display = httpsUrl.startsWith('http')
? `<a href="${escapeString(httpsUrl)}" target="_blank">${escapeString(url)} (${run_data[item][relation]['commit_hash']})</a>`
: `${escapeString(url)} (${run_data[item][relation]['commit_hash']})`;
document.querySelector('#run-data-top').insertAdjacentHTML('beforeend', `<tr><td><strong>relation: ${escapeString(relation)}</strong></td><td>${display}</td></tr>`)
}
} else if(item == 'commit_hash') {
if (run_data[item] == null) continue; // some old runs did not save it
const commit_link = getRepoRefUrl(run_data['uri'], 'tree');
const display = commit_link
? `<a href="${escapeString(commit_link + run_data['commit_hash'])}" target="_blank">${run_data[item]}</a>`
: run_data[item];
document.querySelector('#run-data-top').insertAdjacentHTML('beforeend', `<tr><td><strong>${escapeString(item)}</strong></td><td>${display}</td></tr>`)
} else if(item == 'name' || item == 'filename' || item == 'branch') {
document.querySelector('#run-data-top').insertAdjacentHTML('beforeend', `<tr><td><strong>${escapeString(item)}</strong></td><td>${escapeString(run_data[item])}</td></tr>`)
} else if(item == 'failed' && run_data[item] == true) {
const failedContainer = document.querySelector('#run-failed');
failedContainer.classList.remove('hidden');
} else if(item == 'start_measurement' || item == 'end_measurement') {
run_data_accordion_node.insertAdjacentHTML('beforeend', `<tr><td><strong>${escapeString(item)}</strong></td><td title="${escapeString(run_data[item])}">${new Date(run_data[item] / 1e3)}</td></tr>`)
} else if(item == 'created_at' ) {
run_data_accordion_node.insertAdjacentHTML('beforeend', `<tr><td><strong>${escapeString(item)}</strong></td><td title="${escapeString(run_data[item])}">${new Date(run_data[item])}</td></tr>`)
} else if(item == 'gmt_hash') {
run_data_accordion_node.insertAdjacentHTML('beforeend', `<tr><td><strong>${escapeString(item)}</strong></td><td><a href="https://github.com/green-coding-solutions/green-metrics-tool/commit/${run_data[item]}">${escapeString(run_data[item])}</a></td></tr>`);
} else if(item == 'uri') {
const uri = run_data[item];
const httpsUri = toHttpsUri(uri);
// toHttpsUri only rewrites SSH/git@ prefixes; it does not strip HTML-attribute-breaking chars,
// so the href value still needs escapeString. Absolute paths stay as plain text.
const uriDisplay = httpsUri.startsWith('http')
? `<a href="${escapeString(httpsUri)}">${escapeString(uri)}</a>`
: escapeString(uri);
document.querySelector('#run-data-top').insertAdjacentHTML('beforeend', `<tr><td><strong>${escapeString(item)}</strong></td><td>${uriDisplay}</td></tr>`);
} else if(item == 'note') {
const note = run_data[item].trim();
if (note !== '') {
// no need to escape here as .value and .innerText will not execute HTML / JS
document.querySelector('textarea[name=note]').value = note;
document.querySelector('#run-note-text').innerText = note;
document.querySelector('#run-note').classList.remove('hidden')
}
} else if(item == 'user_id') {
continue
} else if (item == 'user_name') {
run_data_accordion_node.insertAdjacentHTML('beforeend', `<tr><td><strong>user</strong></td><td>${escapeString(run_data[item])} (${escapeString(run_data['user_id'])})</td></tr>`)
} else if(item == 'archived') {
const archive_run_button = document.querySelector('#archive-run');
const unarchive_run_button = document.querySelector('#unarchive-run');
if (run_data[item] === true) {
archive_run_button.classList.add('hidden');
unarchive_run_button.classList.remove('hidden');
}
archive_run_button.addEventListener('click', async () => {
try {
await makeAPICall(`/v1/run/${run_id}`, {archived: true}, false, true);
} catch (err) {
showNotification('Error while trying to archive run!', err);
return;
}
archive_run_button.classList.add('hidden');
unarchive_run_button.classList.remove('hidden');
showNotification('Run Archived!', '', 'success')
})
unarchive_run_button.addEventListener('click', async () => {
try {
await makeAPICall(`/v1/run/${run_id}`, {archived: false}, false, true);
} catch (err) {
showNotification('Error while trying to un-archive run!', err);
return;
}
archive_run_button.classList.remove('hidden');
unarchive_run_button.classList.add('hidden');
showNotification('Run Unarchived!', '', 'success')
})
} else if(item == 'public') {
const public_button = document.querySelector('#make-run-public');
const non_public_button = document.querySelector('#make-run-non-public');
if (run_data[item] === true) {
public_button.classList.add('hidden');
non_public_button.classList.remove('hidden');
}
public_button.addEventListener('click', async () => {
try {
await makeAPICall(`/v1/run/${run_id}`, {public: true}, false, true);
} catch (err) {
showNotification('Error while trying to make run public!', err);
return;
}
public_button.classList.add('hidden');
non_public_button.classList.remove('hidden');
showNotification('Run Made Public!', '', 'success')
})
non_public_button.addEventListener('click', async () => {
try {
await makeAPICall(`/v1/run/${run_id}`, {public: false}, false, true);
} catch (err) {
showNotification('Error while trying to make run non-public!', err);
return;
}
public_button.classList.remove('hidden');
non_public_button.classList.add('hidden');
showNotification('Run Made Non-Public!', '', 'success')
})
} else {
run_data_accordion_node.insertAdjacentHTML('beforeend', `<tr><td><strong>${escapeString(item)}</strong></td><td>${escapeString(run_data[item])}</td></tr>`)
}
}
document.querySelector('#save-note').addEventListener('click', async () => {
const note_text = document.querySelector('textarea[name=note]').value;
try {
await makeAPICall(`/v1/run/${run_id}`, {note: note_text}, false, true);
} catch (err) {
showNotification('Error while trying to save note!', err);
return;
}
showNotification('Note saved!', '', 'success')
});
document.querySelectorAll('.re-submit-run').forEach(el => {
el.addEventListener('click', () => {
const params = new URLSearchParams();
if (run_data.name) params.set('name', run_data.name);
if (run_data.uri) params.set('repo_url', run_data.uri);
if (run_data.filename) params.set('filename', run_data.filename);
if (run_data.branch) params.set('branch', run_data.branch);
if (run_data.machine_id) params.set('machine_id', run_data.machine_id);
if (run_data.schedule_mode) params.set('schedule_mode', run_data.schedule_mode);
if (run_data.usage_scenario_variables && Object.keys(run_data.usage_scenario_variables).length > 0) {
Object.entries(run_data.usage_scenario_variables).forEach(([key, value]) => {
params.append(`usage_scenario_variables[${key}]`, String(value));
});
} else {
params.set('usage_scenario_variables', 'false');
}
window.open(`request.html?${params.toString()}`, '_blank');
});
})
// create new custom field
// timestamp is in microseconds, therefore divide by 10**6
const measurement_duration_in_s = (run_data.end_measurement - run_data.start_measurement) / 1e6
const measurement_duration_display = (measurement_duration_in_s > 60) ? `${numberFormatter.format(measurement_duration_in_s / 60)} min` : `${numberFormatter.format(measurement_duration_in_s)} s`
run_data_accordion_node.insertAdjacentHTML('beforeend', `<tr><td><strong>duration</strong></td><td title="${measurement_duration_in_s} seconds">${measurement_duration_display}</td></tr>`)
// warnings will be fetched separately
}
const fillRunTab = async (selector, data, parent = '') => {
const node = document.querySelector(selector);
for (const item in data) {
if(data[item] != null && typeof data[item] == 'object') {
if (parent == '') {
node.insertAdjacentHTML('beforeend', `<tr><td><strong><h2>${escapeString(item)}</h2></strong></td><td></td></tr>`)
}
fillRunTab(selector, data[item], `${item}.`)
} else {
node.insertAdjacentHTML('beforeend', `<tr><td><strong>${escapeString(parent)}${escapeString(item)}</strong></td><td>${escapeString(data[item])}</td></tr>`)
}
}
}
const displayLegacyLogs = (logData) => {
const logsElement = document.querySelector("#logs");
logsElement.innerHTML = `<pre>${escapeString(logData)}</pre>`;
};
const renderLegacyLogsFromJson = (logsData) => {
const legacyLogTemplate = `
<div class="ui segment">
<h4 class="ui header">{{containerName}}</h4>
<pre>{{stdout}}</pre>
</div>
`;
const logsElement = document.querySelector("#logs");
let contentHTML = '';
// actually, in the legacy case there is only one 'container' called "unified (legacy)"
// but to be on the safe side, still use loops for all lists in the JSON structure
Object.keys(logsData).forEach(containerName => {
const containerLogs = logsData[containerName];
containerLogs.forEach(logEntry => {
if (logEntry.stdout) {
contentHTML += legacyLogTemplate
.replace('{{containerName}}', escapeString(containerName))
.replace('{{stdout}}', escapeString(logEntry.stdout));
}
});
});
logsElement.innerHTML = contentHTML;
};
const renderLogsInterface = (logsData) => {
const containerTemplate = `
<div class="title">
<i class="dropdown icon"></i><i class="server icon"></i> {{containerName}}
<div class="ui mini label">{{logCount}} log{{logPlural}}</div>
</div>
<div class="content">{{content}}</div>
`;
const logCardTemplate = `
<div class="ui card fluid">
{{metadataContent}}
{{commandContent}}
{{stdoutContent}}
{{stderrContent}}
</div>
`;
const metadataTemplate = `
<div class="content">
<div class="header">
<div class="ui small labels">
{{typeLabel}}
{{flowLabel}}
{{classLabel}}
{{operationLabel}}
{{phaseLabel}}
{{idLabel}}
</div>
</div>
</div>
`;
const commandTemplate = `
<div class="content">
<h5 class="ui header"><i class="terminal icon"></i> Command</h5>
<div class="ui segment">
<code>{{command}}</code>
</div>
</div>
`;
const stdoutTemplate = `
<div class="content">
<h5 class="ui header"><i class="file text outline icon"></i> Standard Output</h5>
<div class="ui segment stdout">
<div>{{stdout}}</div>
</div>
</div>
`;
const stderrTemplate = `
<div class="content">
<h5 class="ui header"><i class="exclamation triangle icon"></i> Standard Error</h5>
<div class="ui segment stderr">
<div>{{stderr}}</div>
</div>
</div>
`;
const logsElement = document.querySelector("#logs");
let accordionHTML = '<div class="ui styled accordion">';
const containerNames = Object.keys(logsData);
// Display [SYSTEM] logs first
const systemIndex = containerNames.indexOf('[SYSTEM]');
if (systemIndex > -1) {
containerNames.splice(systemIndex, 1);
containerNames.unshift('[SYSTEM]');
}
containerNames.forEach(containerName => {
const containerLogs = logsData[containerName];
let contentHTML = '';
containerLogs.forEach(logEntry => {
let typeIcon, typeTooltip;
switch (logEntry.type) {
case 'container_execution':
typeIcon = 'cog';
typeTooltip = 'Logs from the entire container execution process';
break;
case 'setup_commands':
typeIcon = 'wrench';
typeTooltip = 'Logs from setup commands before flow execution';
break;
case 'flow_command':
typeIcon = 'play';
typeTooltip = 'Logs from a specific flow execution';
break;
case 'network_stats':
typeIcon = 'wifi';
typeTooltip = 'Network connection statistics from tcpdump';
break;
case 'exception':
typeIcon = 'exclamation triangle';
typeTooltip = 'An error occurred during execution';
break;
default:
typeIcon = 'question';
typeTooltip = 'Logs from an unknown or custom execution type';
break;
}
// Make the type name more visually appealing by replacing underscores with spaces and capitalising the first letter of each word
const typeTitle = escapeString(logEntry.type.replace('_', ' ').replace(/\b\w/g, l => l.toUpperCase()));
const typeLabel = `<div class="ui purple label" data-tooltip="${typeTooltip}" data-position="top center"><i class="${typeIcon} icon"></i> ${typeTitle}</div>`;
const phaseLabel = logEntry.phase ?
`<div class="ui blue label" data-tooltip="Execution phase when this command was run" data-position="top center"><i class="clock icon"></i> ${escapeString(logEntry.phase)}</div>` : '';
const flowLabel = logEntry.flow ?
`<div class="ui green label" data-tooltip="Flow this command belongs to" data-position="top center"><i class="sitemap icon"></i> ${escapeString(logEntry.flow)}</div>` : '';
const idLabel = `<div class="ui label" data-tooltip="Unique identifier for this log entry" data-position="top center"><i class="hashtag icon"></i> ID: ${escapeString(logEntry.id)}</div>`;
const stdoutContent = logEntry.stdout ?
stdoutTemplate.replace('{{stdout}}', escapeString(logEntry.stdout)) : '';
const stderrContent = logEntry.stderr ?
stderrTemplate.replace('{{stderr}}', escapeString(logEntry.stderr)) : '';
// Show different information if the type is exception
let operationLabel = '';
let classLabel = '';
if (logEntry.type === 'exception') {
let operationTooltip;
switch (logEntry.cmd) {
case 'run_scenario':
operationTooltip = 'Exception occurred during main scenario execution runtime';
break;
case 'post_process':
operationTooltip = 'Exception occurred during cleanup and post-processing phase';
break;
default:
operationTooltip = `Exception occurred during '${logEntry.cmd}' operation`;
}
// Make the operation name more visually appealing by replacing underscores with spaces and capitalising the first letter of each word
const operationTitle = escapeString(logEntry.cmd.replace('_', ' ').replace(/\b\w/g, l => l.toUpperCase()));
operationLabel = `<div class="ui orange label" data-tooltip="${operationTooltip}" data-position="top center"><i class="cogs icon"></i> ${operationTitle}</div>`;
if (logEntry.exception_class) {
classLabel = `<div class="ui red label" data-tooltip="Exception class type" data-position="top center"><i class="exclamation triangle icon"></i> ${escapeString(logEntry.exception_class)}</div>`;
}
}
const metadataContent = metadataTemplate
.replace('{{flowLabel}}', flowLabel)
.replace('{{typeLabel}}', typeLabel)
.replace('{{operationLabel}}', operationLabel)
.replace('{{classLabel}}', classLabel)
.replace('{{phaseLabel}}', phaseLabel)
.replace('{{idLabel}}', idLabel);
// For exceptions or empty/null commands, don't show the command section
const commandContent = (logEntry.type === 'exception' || !logEntry.cmd) ? '' :
commandTemplate.replace('{{command}}', escapeString(logEntry.cmd));
contentHTML += logCardTemplate
.replace('{{metadataContent}}', metadataContent)
.replace('{{commandContent}}', commandContent)
.replace('{{stdoutContent}}', stdoutContent)
.replace('{{stderrContent}}', stderrContent);
});
accordionHTML += containerTemplate
.replace('{{containerName}}', escapeString(containerName))
.replace('{{logCount}}', containerLogs.length)
.replace('{{logPlural}}', containerLogs.length === 1 ? '' : 's')
.replace('{{content}}', contentHTML);
});
accordionHTML += '</div>';
logsElement.innerHTML = accordionHTML;
$('.ui.accordion').accordion();
}
const buildTimelineChartData = async (measurements_data) => {
const metrics = {}
const t0 = performance.now();
const transform_timelines_energy_to_power = localStorage.getItem('transform_timelines_energy_to_power') === 'true' ? true : false;
try {
// define here as var (not let!), so we can alert it later in error case.
// this was done, because we apparently often forget to add new metrics here and this helps debugging quickly with the alert later :)
var metric_name = null
// this can be let
let time_before = 0;
let detail_name = null;
measurements_data.forEach(el => {
const time_after = el[1] / 1000000;
const time_in_ms = el[1] / 1000; // divide microseconds timestamp to ms to be handled by charting lib
let value = el[3];
let metric_changed = false;
let unit = el[4];
if(metric_name !== el[2] || detail_name !== el[0]) {
// metric changed -> reset time counter and update variables
metric_name = el[2];
detail_name = el[0];
time_before = time_after;
metric_changed = true;
}
[value, unit] = convertValue(value, unit);
if (metrics[metric_name] == undefined) {
metrics[metric_name] = {
series: {},
unit: unit,
converted_unit: unit
}
}
if(transform_timelines_energy_to_power && metrics[metric_name].unit == 'J') {
value = value/(time_after-time_before); // convert Joules to Watts by dividing through the time difference of two measurements
metrics[metric_name].converted_unit = 'W';
} else if(!transform_timelines_energy_to_power && metrics[metric_name].unit == 'W') {
value = value*(time_after-time_before); // convert Watts to Joules by multiplying with the time difference of two measurements
metrics[metric_name].converted_unit = 'J';
}
time_before = time_after;
if(metric_changed && transform_timelines_energy_to_power) return; // if watts display then the first graph value will be zero. We skip that.
// Depending on the charting library the object has to be reformatted
// First we check if structure is initialized
if (metrics[metric_name].series[detail_name] == undefined) {
metrics[metric_name].series[detail_name] = { name: detail_name, data: [] }
}
metrics[metric_name].series[detail_name]['data'].push([time_in_ms, value]);
})
} catch (err) {
alert(err)
alert(metric_name)
}
const t1 = performance.now();
console.log(`buildTimelineMetrics Took ${t1 - t0} milliseconds.`);
return metrics;
}
const wrapNoteText = (text, maxLength = 80) => {
if (text.length <= maxLength) return text;
const lines = [];
let currentLine = '';
const breakChars = [' ', '/', ':', '-', '_'];
for (const char of text) {
currentLine += char;
if (currentLine.length >= maxLength) {
const breakIndex = currentLine.split('').findLastIndex(c => breakChars.includes(c));
if (breakIndex > maxLength * 0.5) {
const breakChar = currentLine[breakIndex];
const endIndex = breakChar === ' ' ? breakIndex : breakIndex + 1;
lines.push(currentLine.substring(0, endIndex));
currentLine = currentLine.substring(breakIndex + 1);
} else {
lines.push(currentLine.substring(0, maxLength));
currentLine = currentLine.substring(maxLength);
}
}
}
if (currentLine) lines.push(currentLine);
return lines.join('\n');
};
const displayTimelineCharts = async (metrics, notes) => {
const note_positions = [
'insideStartTop',
'insideEndBottom'
];
const chart_instances = [];
const t0 = performance.now();
let markline = {};
if(localStorage.getItem('time_series_avg') === 'true') {
markline = {
precision: 4, // generally annoying that precision is by default 2. Wrong AVG if values are smaller than 0.001 and no autoscaling!
data: [ {type: "average",label: {formatter: "AVG\n(selection):\n{c}"}}]
}
}
for (const metric_name in metrics) {
const element = createChartContainer("#chart-container", `${getPretty(metric_name, 'clean_name')} via ${getPretty(metric_name, 'source')} <i data-tooltip="${getPretty(metric_name, 'explanation')}" data-position="bottom center" data-inverted><i class="question circle icon link"></i></i>`);
let legend = [];
let series = [];
for (const detail_name in metrics[metric_name].series) {
legend.push(detail_name)
series.push({
name: detail_name,
type: 'line',
smooth: true,
symbol: 'none',
areaStyle: {},
data: metrics[metric_name].series[detail_name].data,
markLine: markline,
});
}
// now we add all notes to every chart
legend.push('Notes')
let notes_labels = [];
let inner_counter = 0;
if (notes != null) {
notes.forEach(note => {
notes_labels.push({xAxis: note[3]/1000, label: {formatter: wrapNoteText(note[2]), position: note_positions[inner_counter%2]}})
inner_counter++;
});
}
series.push({
name: "Notes",
type: 'line',
smooth: true,
symbol: 'none',
areaStyle: {},
data: [],
markLine: { data: notes_labels}
});
const chart_instance = echarts.init(element);
let options = getLineBarChartOptions(null, legend, series, 'Time', metrics[metric_name].converted_unit);
chart_instance.setOption(options);
chart_instances.push(chart_instance);
}
const t1 = performance.now();
console.log(`buildTimelineCharts took ${t1 - t0} milliseconds.`);
window.onresize = function() { // set callback when ever the user changes the viewport
chart_instances.forEach(chart_instance => {
chart_instance.resize();
})
}
document.querySelector('#api-loader').remove();
// after all charts instances have been placed
// the flexboxes might have rearranged. We need to trigger resize
setTimeout(function(){console.log("Resize"); window.dispatchEvent(new Event('resize'))}, 500);
}
const renderBadges = async (run_id, phase_stats) => {
if (phase_stats == null) return;
const phase_stats_keys = Object.keys(phase_stats);
const badge_container = document.querySelector('#run-badges')
phase_stats_keys.forEach(metric_name => {
if (phase_stats[metric_name].type != 'TOTAL') return; // skip averaged metrics
badge_container.innerHTML += `
<div class="inline field">
<a href="${METRICS_URL}/stats.html?id=${run_id}">
<img src="${API_URL}/v1/badge/single/${run_id}?metric=${encodeURIComponent(metric_name)}" loading="lazy" onerror="this.parentNode.parentNode.remove(); console.log('Could not render ${metric_name} badge - Likely due to non public visibility of the run.')">
</a>
<a class="copy-badge"><i class="copy icon"></i></a>
<div class="ui left pointing blue basic label">
${escapeString(METRIC_MAPPINGS[metric_name]?.['explanation'])}
</div>
<hr class="ui divider"></hr>
</div>`;
})
document.querySelectorAll(".copy-badge").forEach(el => {
el.addEventListener('click', copyToClipboard)
})
}
const fetchAndFillPhaseStatsData = async (run_id) => {
let phase_stats = null;
try {
phase_stats = await makeAPICall('/v1/phase_stats/single/' + run_id)
} catch (err) {
showNotification('Could not get phase_stats data from API', err);
return
}
buildPhaseTabs(phase_stats.data)
document.querySelectorAll('.ui.steps.phases .step, .runtime-step').forEach(node => node.addEventListener('click', el => {
const phase = el.currentTarget.getAttribute('data-tab');
renderCompareChartsForPhase(phase_stats.data, phase);
})
);
document.querySelectorAll('.ui.steps.phases .step, #runtime-sub-phases .item').forEach(node => { node.addEventListener('click', event => {
const activeTab = localStorage.getItem('activeMetricTab');
const tabName = node.getAttribute('data-tab');
const segment = document.querySelector('.ui.attached.tab.segment[data-tab="' + tabName + '"]');
if (!segment) return;
const tabs = $(segment).find('.ui.pointing.menu .item');
if (activeTab) {
tabs.tab('change tab', activeTab);
}
});
});
renderCompareChartsForPhase(phase_stats.data, getAndShowPhase());
displayTotalChart(...buildTotalChartData(phase_stats.data));
return phase_stats;
}
const fetchAndFillNetworkIntercepts = async (run_id) => {
let network = null;
try {
network = await makeAPICall('/v1/network/' + run_id)
} catch (err) {
if (err instanceof APIHTTPError && err.status === 204) {
console.log('No network intercepts present in API response. Skipping error as this is allowed case.')
} else {
showNotification('Could not get network intercepts data from API', err);
}
return
}
if (network.data.length === 0) {
document.querySelector("#network-divider").insertAdjacentHTML('afterEnd', '<p>No external network connections were detected.</p>')
} else {
const node = document.querySelector("#network-intercepts");
for (const item of network.data) {
const date = dateToYMD(new Date(Number(item[2])), false, true);
node.insertAdjacentHTML('beforeend', `<tr><td><strong>${escapeString(date)}</strong></td><td>${escapeString(item[3])}</td><td>${escapeString(item[4])}</td></tr>`)
}
}
}
const fetchAndFillOptimizationsData = async (run_id) => {
let optimizations = null;
try {
optimizations = await makeAPICall('/v1/optimizations/' + run_id)
} catch (err) {
showNotification('Could not get optimizations data from API', err);
return
}
const optimizationTemplate = `
<div class="content">
<div class="header">{{header}}
<span class="right floated time">
<div class="ui label"><i class="{{subsystem_icon}} icon"></i>{{subsystem}}</div>
<div class="ui {{label_colour}} label">{{label}}</div>
</span>
</div>
<div class="description">
<p>{{description}}</p>
</div>
<div class="extra content">
<span class="right floated time">
{{link}}
</span>
</div>
</div>
`;
const container = document.getElementById("optimizationsContainer");
optimizations.data.forEach(optimization => {
let optimizationHTML = optimizationTemplate
.replace("{{header}}", escapeString(optimization[0]))
.replace("{{label}}", escapeString(optimization[1]))
.replace("{{label_colour}}", escapeString(optimization[2]))
.replace("{{description}}", escapeString(optimization[5]))
.replace("{{subsystem}}", escapeString(optimization[3]))
.replace("{{subsystem_icon}}", escapeString(optimization[4]))
if (optimization[6]){
optimizationHTML = optimizationHTML.replace("{{link}}", `
<a class="ui mini icon primary basic button" href="${escapeString(optimization[6])}">
<i class="angle right icon"></i>
</a>`);
}else{
optimizationHTML = optimizationHTML.replace("{{link}}", "");
}
const optimizationElement = document.createElement("div");
optimizationElement.classList.add("ui", "horizontal", "fluid", "card");
optimizationElement.innerHTML = optimizationHTML;
container.appendChild(optimizationElement);
});
$('#optimization_count').html(optimizations.data.length)
}
const fetchAndFillAIData = async (run_id) => {
if (ACTIVATE_AI_OPTIMISATIONS !== true) return;
let ai_data = null;
try {
ai_data = await makeAPICall('/v1/ai/' + run_id)
} catch (err) {
// Do nothing as ai data will be empty most of the time
return
}
ai_data.sort((a, b) => a.rating - b.rating);
const stats = {
'green':0,
'yellow':0,
'red':0
};
ai_data.forEach(d => {
if (d.rating > 75) {
d.color = "green";
} else if (d.rating > 35) {
d.color = "yellow";
} else if (d.rating > 0) {
d.color = "red";
} else {
console.log('Massive error. We need to report this');
return;
}
stats[d.color] += 1;
});
const progressBar = `
<div id="ai_progress" class="ui multiple progress" data-value="${stats['red']},${stats['yellow']},${stats['green']}" data-total=${ai_data.length}>
<div class="red bar"></div>
<div class="yellow bar"></div>
<div class="green bar"></div>
</div>
`
const aiTemplate = `
<div class="title">
<div class="ui {{color}} label">{{rating}}</div> {{filename}}:{{function_name}} <i class="dropdown icon"></i>
</div>
<div class="content">
<h4 class="ui horizontal divider header">
<i class="barcode icon"></i>
Your code
</h4>
<pre>{{code}}</pre>
<h4 class="ui horizontal divider header">
<i class="brain icon"></i>
{{model}}
</h4>
<p>{{ret_val}}</p>
<button class="ui primary basic button copy-button">Improve this with AI</button>
</div>
`;
const ai_container = document.getElementById("ai-container");
ai_container.innerHTML = progressBar;
ai_data.forEach(d => {
let optimizationHTML = aiTemplate
.replace("{{function_name}}", escapeString(d.name))
.replace("{{rating}}", escapeString(d.rating))
.replace("{{filename}}", escapeString(d.filename))
.replace("{{code}}", escapeString(d.code))
.replace("{{model}}", escapeString(d.model))
.replace("{{color}}", escapeString(d.color))
.replace("{{ret_val}}", (d.ret_val || '').replace(/\n/g, '<br>'))
const optimizationElement = document.createElement("div");
optimizationElement.classList.add("ui", "styled","fluid", "accordion");
optimizationElement.innerHTML = optimizationHTML;
ai_container.appendChild(optimizationElement);
});