forked from green-coding-solutions/green-metrics-tool
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
498 lines (434 loc) · 18.5 KB
/
Copy pathmain.js
File metadata and controls
498 lines (434 loc) · 18.5 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
const GMT_MACHINES = JSON.parse(localStorage.getItem('gmt_machines')) || {}; // global variable. dynamically resolved via resolveMachinesToGlobalVariable
const escapeString = (string) =>{
let my_string = String(string)
const map = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
const reg = /[&<>"']/ig;
return my_string.replace(reg, (match) => map[match]);
}
const toHttpsUri = (uri) => {
if (uri.startsWith('git@')) {
return uri.replace(/^git@([^:]+):/, 'https://$1/').replace(/\.git$/, '');
}
if (uri.startsWith('ssh://')) {
return uri.replace(/^ssh:\/\/(?:[^@]+@)?/, 'https://').replace(/\.git$/, '');
}
return uri;
};
// Platform path conventions:
// type='commit': /commit/ (GitHub), /-/commit/ (GitLab), /commits/ (Bitbucket)
// type='tree': /tree/ (GitHub), /-/tree/ (GitLab), /src/ (Bitbucket)
// Returns null for non-HTTP URIs (e.g. local paths).
const getRepoRefUrl = (uri, type) => {
const cleanUri = toHttpsUri(uri);
if (!cleanUri.startsWith('http')) return null;
if (type !== 'commit' && type !== 'tree') {
throw new Error(`getRepoRefUrl: unknown type '${type}', expected 'commit' or 'tree'`);
}
const base = cleanUri.endsWith('.git') ? cleanUri.slice(0, -4) : cleanUri;
if (base.includes('bitbucket')) {
return base + (type === 'commit' ? '/commits/' : '/src/');
}
const pathSep = base.includes('gitlab') ? '/-/' : '/';
return base + (type === 'commit' ? pathSep + 'commit/' : pathSep + 'tree/');
};
class APIHTTPError extends Error {
constructor(status, message) {
super(message);
this.status = status;
}
}
const date_options = {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
hour12: false
};
/*
WebComponent function without ShadowDOM
to expand the menu in the HTML pages
*/
class GMTMenu extends HTMLElement {
connectedCallback() {
const validActiveMenuKeys = new Set([
'home',
'scenario-runner',
'runs-repos',
'watchlist',
'submit-software',
'cluster-status',
'eco-ci',
'power-hog',
'carbondb',
'data-analysis',
'authentication',
'settings',
]);
const configuredActiveMenuKey = this.getAttribute('data-active-item');
const activeMenuKey = validActiveMenuKeys.has(configuredActiveMenuKey) ? configuredActiveMenuKey : 'home';
const menuItemClass = (menuKey) => activeMenuKey === menuKey ? 'item active' : 'item';
let html_content = `
<div id="menu" class="ui inverted secondary pointing vertical menu">
<div class="item-container">
<a class="${menuItemClass('home')}" href="/index.html" aria-label="Home">
<b><i class="home icon"></i> Home</b>
</a>`
if (ACTIVATE_SCENARIO_RUNNER == true) {
html_content += `
<a class="${menuItemClass('scenario-runner')}" href="/runs.html" aria-label="ScenarioRunner"><b><i class="tachometer alternate left icon"></i> ScenarioRunner</b></a>
<a class="${menuItemClass('runs-repos')}" href="/runs.html" aria-label="Runs / Repos">
⮑ <b><i class="code branch icon"></i> Runs / Repos</b>
</a>
<a class="${menuItemClass('watchlist')}" href="/watchlist.html" aria-label="Watchlist">
⮑ <b><i class="list icon"></i> Watchlist</b>
</a>
<a class="${menuItemClass('submit-software')}" href="/request.html" aria-label="Submit Software">
⮑ <b><i class="bullseye icon"></i> Submit Software</b>
</a>
<a class="${menuItemClass('cluster-status')}" href="/cluster-status.html" aria-label="Cluster Status">
⮑ <b><i class="database icon"></i> Cluster Status</b>
</a>`;
};
if (ACTIVATE_ECO_CI == true) {
html_content += `
<a class="${menuItemClass('eco-ci')}" href="/ci-index.html" aria-label="Eco CI">
<b><i class="seedling icon"></i> Eco CI</b>
</a>`;
};
if (ACTIVATE_POWER_HOG == true) {
html_content += `
<a class="${menuItemClass('power-hog')}" href="/hog.html" aria-label="Power HOG">
<b><i class="piggy bank icon"></i> Power HOG</b>
</a>`;
};
if (ACTIVATE_CARBON_DB == true) {
html_content += `
<a class="${menuItemClass('carbondb')}" href="/carbondb.html" aria-label="CarbonDB">
<b><i class="balance scale icon"></i> CarbonDB</b>
</a>`;
};
html_content += `
<a class="${menuItemClass('data-analysis')}" href="/data-analysis.html" aria-label="Data Analysis">
<b><i class="chartline icon"></i> Data Analysis</b>
</a>
<a class="${menuItemClass('authentication')}" href="/authentication.html" aria-label="Authentication">
<b><i class="users icon"></i>Authentication</b>
</a>
<a class="${menuItemClass('settings')}" href="/settings.html" aria-label="Settings">
<b><i class="cogs icon"></i> Settings</b>
</a>
</div>`;
const user_name = localStorage.getItem('user_name');
if (user_name != null) {
html_content += `
<div class="sticky-container" style="width: 90%; margin: 20px auto;">
<span class="ui label"><i class="users icon"></i> User: ${escapeString(user_name)}</span>
</div>`;
}
html_content += `
<div class="sticky-container">
<a href="https://www.green-coding.io">
<img class="ui fluid image menu-logo" src="/images/green-coding-menu-logo-2x.webp"
srcset="/images/green-coding-menu-logo.webp 1x,
/images/green-coding-menu-logo-2x.webp 2x"
alt="Green Coduing Solutions Logo">
</a>
</div>
</div> <!-- end menu -->`;
this.innerHTML = html_content;
}
}
customElements.define('gmt-menu', GMTMenu);
// tricky to make this async as some other functions will depend on the value of the variable
// but if it is not set yet it will populate in a later call
const resolveMachinesToGlobalVariable = async () => {
if (Object.keys(GMT_MACHINES).length === 0) {
const api_data = await makeAPICall('/v1/machines')
api_data.data.forEach(el => {
GMT_MACHINES[el[0]] = el[1];
})
}
localStorage.setItem('gmt_machines', JSON.stringify(GMT_MACHINES));
}
const getClusterStatus = async (status_ok_selector, status_warning_selector) => {
try {
cluster_status_data = await makeAPICall('/v1/cluster/status')
const container = document.querySelector('.cluster-health-message.yellow #cluster-health-warnings');
cluster_status_data.data.forEach(message => {
container.insertAdjacentHTML('beforeend', `<p id="message-${message[0]}"><b>${new Date(message[3]).toLocaleDateString('sv-SE', date_options)}</b>: ${message[1]}</p>`);
})
document.querySelector('.cluster-health-message.yellow').style.display = 'flex'; // show
} catch (err) {
if (err instanceof APIHTTPError && err.status === 204) {
document.querySelector('.cluster-health-message.success').style.display = 'flex'; // show
} else {
showNotification('Could not get cluster health status data from API', err); // no return as we want other calls to happen
}
}
}
const dateTimePicker = (days_before=30, url_params=null) => {
$('#rangestart').calendar({
type: 'date',
endCalendar: $('#rangeend'),
initialDate: (url_params['start_date'] != null) ? url_params['start_date'] : new Date((new Date()).setDate((new Date).getDate() - days_before)),
});
$('#rangeend').calendar({
type: 'date',
startCalendar: $('#rangestart'),
initialDate: (url_params['end_date'] != null) ? url_params['end_date'] : new Date(),
});
}
const getURLParams = () => {
const url_params = new URLSearchParams(window.location.search);
if (!url_params.size) return {};
return Object.fromEntries(url_params.entries())
}
const getPretty = (metric_name, key) => {
if(metric_name.startsWith('custom_')) {
if (key == 'source') return 'User supplied';
if (key == 'clean_name') return metric_name.replace(/^custom_/, '').replace(/_sci_global$/, ' (SCI)').split('_').map(e => e.charAt(0).toUpperCase() + e.slice(1)).join(' ');
if (key == 'explanation') return metric_name.endsWith('sci_global') ? 'SCI (Software Carbon Intensity) derived from user supplied custom metric' : 'User supplied custom metric';
} else if (METRIC_MAPPINGS[metric_name] == null || METRIC_MAPPINGS[metric_name][key] == null) {
console.log(metric_name, ' is undefined in METRIC_MAPPINGS or has no key');
return `${metric_name}_${key}`;
}
return METRIC_MAPPINGS[metric_name][key];
}
// We are using now the STDDEV of the sample for two reasons:
// It is required by the Blue Angel for Software
// We got many debates that in cases where the average is only estimated through measurements and is not absolute
// one MUST use the sample STDDEV.
// Still one could argue that one does not want to characterize the measured software but rather the measurement setup
// it is safer to use the sample STDDEV as it is always higher
const calculateStatistics = (data) => {
const getNumericValue = (entry) => {
if (Array.isArray(entry?.value)) return entry.value[1];
if (entry?.value != null) return entry.value;
return entry;
}
let sum = null;
let stddev = null;
let mean = null;
sum = data.reduce((sum, value) => sum + getNumericValue(value), 0)
mean = sum / data.length;
if (data.length < 2) {
stddev = 0
} else {
stddev = Math.sqrt(data.reduce((sum, value) => sum + Math.pow(getNumericValue(value) - mean, 2), 0) / (data.length - 1) );
}
const stddev_rel = (stddev / mean) * 100;
return [ mean, stddev, sum, stddev_rel ];
}
const replaceRepoIcon = (uri) => {
uri = toHttpsUri(String(uri))
if(!uri.startsWith('http')) return escapeString(uri); // ignore filesystem paths, but escape them for HTML
let url;
try {
url = new URL(uri);
} catch (error) {
// If URL parsing fails (malicious or malformed URI), safely escape and return
return escapeString(uri);
}
let iconClass = "";
switch (url.host) {
case "github.com":
case "www.github.com":
iconClass = "github";
break;
case "bitbucket.com":
case "www.bitbucket.com":
iconClass = "bitbucket";
break;
case "gitlab.com":
case "www.gitlab.com":
iconClass = "gitlab";
break;
default:
return escapeString(uri);
}
return `<i class="icon ${iconClass}"></i>` + escapeString(url.pathname + url.search + url.hash);
};
const createExternalIconLink = (url) => {
// Build a safe external icon link. toHttpsUri only normalises SSH/git@ prefixes; it does NOT strip
// HTML-attribute-breaking chars like ", so the href value still requires escapeString.
// The startsWith('http') check restricts the protocol but does not on its own prevent attribute breakout.
const httpsUrl = url ? toHttpsUri(url) : url;
if (httpsUrl && httpsUrl.startsWith('http')) {
return `<a href="${escapeString(httpsUrl)}" target="_blank"><i class="icon external alternate"></i></a>`;
}
return '';
}
const showNotification = (message_title, message_text, type='error') => {
if (typeof message_text === 'object') console.log(message_text); // this is most likey an error. We need it in the console
const message = typeof message_text === 'string' ? message_text : (message_text instanceof Error ? message_text.message : JSON.stringify(message_text));
$('body')
.toast({
class: type,
showProgress: 'top',
position: 'top right',
displayTime: 5000,
title: message_title,
message: message,
});
return;
}
const copyToClipboard = async (e) => {
e.preventDefault();
if (!navigator?.clipboard?.writeText) {
alert('Clipboard API not supported');
return;
}
try {
const htmlContent = e.currentTarget.previousElementSibling.innerHTML;
await navigator.clipboard.writeText(htmlContent);
} catch (err) {
alert('Failed to copy HTML content to clipboard!');
}
};
const dateToYMD = (date, short=false, no_break=false) => {
let day = date.getDate().toString().padStart(2, '0');
let month = (date.getMonth() + 1).toString().padStart(2, '0'); //Month from 0 to 11
let hours = date.getHours().toString().padStart(2, '0');
let minutes = date.getMinutes().toString().padStart(2, '0');
let offset = date.getTimezoneOffset();
offset = offset < 0 ? `+${-offset/60}` : -offset/60;
if(short) return `${date.getFullYear().toString()}-${month}-${day}`;
const breaker = (no_break === true) ? '' : '<br>';
return ` ${date.getFullYear()}-${month}-${day} ${breaker} ${hours}:${minutes} UTC${offset}`;
}
async function makeAPICall(path, values=null, force_authentication_token=null, force_put=false) {
if(values != null ) {
var options = {
method: "POST",
body: JSON.stringify(values),
headers: {
'Content-Type': 'application/json'
}
}
if (force_put == true) {
options.method = 'PUT';
}
} else {
var options = { method: 'GET', headers: {} }
}
if (force_authentication_token != null && force_authentication_token != '') {
options.headers['X-Authentication'] = force_authentication_token;
} else {
const authentication_token = localStorage.getItem('authentication_token');
if (authentication_token != null && authentication_token != '') {
options.headers['X-Authentication'] = authentication_token;
}
}
let json_response = null;
let _http_status = null;
if(localStorage.getItem('remove_idle') === 'true') path += (path.includes('?') ? '&' : '?') + 'remove_idle=true'
await fetch(API_URL + path, options)
.then(response => {
_http_status = response.status;
if (response.status == 204) {
// 204 responses use no body, so json() call would fail
throw new APIHTTPError(204, 'No data to display. API returned empty response (HTTP 204)')
}
if (response.status == 202) {
return
}
return response.json()
})
.then(my_json => {
if (my_json != null && my_json.success != true) {
if (Array.isArray(my_json.err) && my_json.err.length !== 0)
throw new APIHTTPError(_http_status, my_json.err[0]?.msg)
else
throw new APIHTTPError(_http_status, my_json.err)
}
json_response = my_json
})
return json_response;
};
/* Menu toggling */
let openMenu = function(){
$(this).removeClass('closed').addClass('opened');
$('#menu').removeClass('closed').addClass('opened');
$('#main').removeClass('closed').addClass('opened');
setTimeout(function(){window.dispatchEvent(new Event('resize'))}, 500) // needed for the graphs to resize
localStorage.setItem('menu_closed', false)
}
let closeMenu = function(){
$(this).removeClass('opened').addClass('closed');
$('#menu').removeClass('opened').addClass('closed');
$('#main').removeClass('opened').addClass('closed');
setTimeout(function(){window.dispatchEvent(new Event('resize'))}, 500) // needed for the graphs to resize
localStorage.setItem('menu_closed', true)
}
async function sortDate() {
const button = document.querySelector('#sort-button')
button.removeEventListener('click', sortDate);
button.addEventListener('click', sortName);
button.innerHTML = '<i class="font icon"></i>Sort name';
await getRepositories('date');
}
async function sortName() {
const button = document.querySelector('#sort-button')
button.removeEventListener('click', sortName);
button.addEventListener('click', sortDate);
button.innerHTML = '<i class="clock icon"></i>Sort date';
await getRepositories('name');
}
const numberFormatter = new Intl.NumberFormat('en-US', {
style: 'decimal', // You can also use 'currency', 'percent', or 'unit'
minimumFractionDigits: 2,
maximumFractionDigits: 2,
});
const numberFormatterLong = new Intl.NumberFormat('en-US', {
style: 'decimal',
minimumFractionDigits: 2,
maximumFractionDigits: 4,
});
const showHiddenPhaseTab = (el) => {
if (el.currentTarget.classList.contains('hidden-phase-tab')) {
el.currentTarget.querySelector('.hidden-phase-name').classList.remove('hidden');
} else {
document.querySelectorAll('.hidden-phase-name').forEach(matched_el => {
matched_el.classList.add('hidden');
})
}
}
const fetchTimelineNotes = async (run_id) => {
let notes = null;
try {
notes = await makeAPICall('/v1/notes/' + run_id)
} catch (err) {
showNotification('Could not get notes data from API', err);
}
return notes?.data;
}
if (localStorage.getItem('closed_descriptions') == null) {
localStorage.setItem('closed_descriptions', '');
}
$(document).ready(() => {
$(document).on('click','#menu-toggle.closed', openMenu);
$(document).on('click','#menu-toggle.opened', closeMenu);
if ($(window).width() < 960 || localStorage.getItem('menu_closed') === 'true') {
$('#menu-toggle').removeClass('opened').addClass('closed');
$('#menu').removeClass('opened').addClass('closed');
$('#main').removeClass('opened').addClass('closed');
}
$("body").removeClass("preload"); // activate tranisition CSS properties again
const closed_descriptions = localStorage.getItem('closed_descriptions');
$('.close').on('click', function() {
$(this).closest('.ui').transition('fade');
localStorage.setItem('closed_descriptions', `${closed_descriptions},${window.location.pathname}`)
});
if (closed_descriptions.indexOf(window.location.pathname) !== -1) {
document.querySelectorAll('i.close.icon').forEach(el => { el.closest('.ui').remove()}
)
}
resolveMachinesToGlobalVariable();
});