]> git.proxmox.com Git - proxmox-widget-toolkit.git/blob - src/Utils.js
abbad36f67e276e15274ddd305fd47355481882d
[proxmox-widget-toolkit.git] / src / Utils.js
1 Ext.ns('Proxmox');
2 Ext.ns('Proxmox.Setup');
3
4 if (!Ext.isDefined(Proxmox.Setup.auth_cookie_name)) {
5 throw "Proxmox library not initialized";
6 }
7
8 // avoid errors related to Accessible Rich Internet Applications
9 // (access for people with disabilities)
10 // TODO reenable after all components are upgraded
11 Ext.enableAria = false;
12 Ext.enableAriaButtons = false;
13 Ext.enableAriaPanels = false;
14
15 // avoid errors when running without development tools
16 if (!Ext.isDefined(Ext.global.console)) {
17 let console = {
18 dir: function() {
19 // do nothing
20 },
21 log: function() {
22 // do nothing
23 },
24 warn: function() {
25 // do nothing
26 },
27 };
28 Ext.global.console = console;
29 }
30
31 Ext.Ajax.defaultHeaders = {
32 'Accept': 'application/json',
33 };
34
35 Ext.Ajax.on('beforerequest', function(conn, options) {
36 if (Proxmox.CSRFPreventionToken) {
37 if (!options.headers) {
38 options.headers = {};
39 }
40 options.headers.CSRFPreventionToken = Proxmox.CSRFPreventionToken;
41 }
42 let storedAuth = Proxmox.Utils.getStoredAuth();
43 if (storedAuth.token) {
44 options.headers.Authorization = storedAuth.token;
45 }
46 });
47
48 Ext.define('Proxmox.Utils', { // a singleton
49 utilities: {
50
51 yesText: gettext('Yes'),
52 noText: gettext('No'),
53 enabledText: gettext('Enabled'),
54 disabledText: gettext('Disabled'),
55 noneText: gettext('none'),
56 NoneText: gettext('None'),
57 errorText: gettext('Error'),
58 unknownText: gettext('Unknown'),
59 defaultText: gettext('Default'),
60 daysText: gettext('days'),
61 dayText: gettext('day'),
62 runningText: gettext('running'),
63 stoppedText: gettext('stopped'),
64 neverText: gettext('never'),
65 totalText: gettext('Total'),
66 usedText: gettext('Used'),
67 directoryText: gettext('Directory'),
68 stateText: gettext('State'),
69 groupText: gettext('Group'),
70
71 language_map: {
72 ar: 'Arabic',
73 ca: 'Catalan',
74 zh_CN: 'Chinese (Simplified)',
75 zh_TW: 'Chinese (Traditional)',
76 da: 'Danish',
77 nl: 'Dutch',
78 en: 'English',
79 eu: 'Euskera (Basque)',
80 fr: 'French',
81 de: 'German',
82 he: 'Hebrew',
83 it: 'Italian',
84 ja: 'Japanese',
85 kr: 'Korean',
86 nb: 'Norwegian (Bokmal)',
87 nn: 'Norwegian (Nynorsk)',
88 fa: 'Persian (Farsi)',
89 pl: 'Polish',
90 pt_BR: 'Portuguese (Brazil)',
91 ru: 'Russian',
92 sl: 'Slovenian',
93 es: 'Spanish',
94 sv: 'Swedish',
95 tr: 'Turkish',
96 },
97
98 render_language: function(value) {
99 if (!value) {
100 return Proxmox.Utils.defaultText + ' (English)';
101 }
102 let text = Proxmox.Utils.language_map[value];
103 if (text) {
104 return text + ' (' + value + ')';
105 }
106 return value;
107 },
108
109 language_array: function() {
110 let data = [['__default__', Proxmox.Utils.render_language('')]];
111 Ext.Object.each(Proxmox.Utils.language_map, function(key, value) {
112 data.push([key, Proxmox.Utils.render_language(value)]);
113 });
114
115 return data;
116 },
117
118 bond_mode_gettext_map: {
119 '802.3ad': 'LACP (802.3ad)',
120 'lacp-balance-slb': 'LACP (balance-slb)',
121 'lacp-balance-tcp': 'LACP (balance-tcp)',
122 },
123
124 render_bond_mode: value => Proxmox.Utils.bond_mode_gettext_map[value] || value || '',
125
126 bond_mode_array: function(modes) {
127 return modes.map(mode => [mode, Proxmox.Utils.render_bond_mode(mode)]);
128 },
129
130 getNoSubKeyHtml: function(url) {
131 // url http://www.proxmox.com/products/proxmox-ve/subscription-service-plans
132 return Ext.String.format('You do not have a valid subscription for this server. Please visit <a target="_blank" href="{0}">www.proxmox.com</a> to get a list of available options.', url || 'https://www.proxmox.com');
133 },
134
135 format_boolean_with_default: function(value) {
136 if (Ext.isDefined(value) && value !== '__default__') {
137 return value ? Proxmox.Utils.yesText : Proxmox.Utils.noText;
138 }
139 return Proxmox.Utils.defaultText;
140 },
141
142 format_boolean: function(value) {
143 return value ? Proxmox.Utils.yesText : Proxmox.Utils.noText;
144 },
145
146 format_neg_boolean: function(value) {
147 return !value ? Proxmox.Utils.yesText : Proxmox.Utils.noText;
148 },
149
150 format_enabled_toggle: function(value) {
151 return value ? Proxmox.Utils.enabledText : Proxmox.Utils.disabledText;
152 },
153
154 format_expire: function(date) {
155 if (!date) {
156 return Proxmox.Utils.neverText;
157 }
158 return Ext.Date.format(date, "Y-m-d");
159 },
160
161 // somewhat like a human would tell durations, omit zero values and do not
162 // give seconds precision if we talk days already
163 format_duration_human: function(ut) {
164 let seconds = 0, minutes = 0, hours = 0, days = 0;
165
166 if (ut <= 0.1) {
167 return '<0.1s';
168 }
169
170 let remaining = ut;
171 seconds = Number((remaining % 60).toFixed(1));
172 remaining = Math.trunc(remaining / 60);
173 if (remaining > 0) {
174 minutes = remaining % 60;
175 remaining = Math.trunc(remaining / 60);
176 if (remaining > 0) {
177 hours = remaining % 24;
178 remaining = Math.trunc(remaining / 24);
179 if (remaining > 0) {
180 days = remaining;
181 }
182 }
183 }
184
185 let res = [];
186 let add = (t, unit) => {
187 if (t > 0) res.push(t + unit);
188 return t > 0;
189 };
190
191 let addSeconds = !add(days, 'd');
192 add(hours, 'h');
193 add(minutes, 'm');
194 if (addSeconds) {
195 add(seconds, 's');
196 }
197 return res.join(' ');
198 },
199
200 format_duration_long: function(ut) {
201 let days = Math.floor(ut / 86400);
202 ut -= days*86400;
203 let hours = Math.floor(ut / 3600);
204 ut -= hours*3600;
205 let mins = Math.floor(ut / 60);
206 ut -= mins*60;
207
208 let hours_str = '00' + hours.toString();
209 hours_str = hours_str.substr(hours_str.length - 2);
210 let mins_str = "00" + mins.toString();
211 mins_str = mins_str.substr(mins_str.length - 2);
212 let ut_str = "00" + ut.toString();
213 ut_str = ut_str.substr(ut_str.length - 2);
214
215 if (days) {
216 let ds = days > 1 ? Proxmox.Utils.daysText : Proxmox.Utils.dayText;
217 return days.toString() + ' ' + ds + ' ' +
218 hours_str + ':' + mins_str + ':' + ut_str;
219 } else {
220 return hours_str + ':' + mins_str + ':' + ut_str;
221 }
222 },
223
224 format_subscription_level: function(level) {
225 if (level === 'c') {
226 return 'Community';
227 } else if (level === 'b') {
228 return 'Basic';
229 } else if (level === 's') {
230 return 'Standard';
231 } else if (level === 'p') {
232 return 'Premium';
233 } else {
234 return Proxmox.Utils.noneText;
235 }
236 },
237
238 compute_min_label_width: function(text, width) {
239 if (width === undefined) { width = 100; }
240
241 let tm = new Ext.util.TextMetrics();
242 let min = tm.getWidth(text + ':');
243
244 return min < width ? width : min;
245 },
246
247 getStoredAuth: function() {
248 let storedAuth = JSON.parse(window.localStorage.getItem('ProxmoxUser'));
249 return storedAuth || {};
250 },
251
252 setAuthData: function(data) {
253 Proxmox.UserName = data.username;
254 Proxmox.LoggedOut = data.LoggedOut;
255 // creates a session cookie (expire = null)
256 // that way the cookie gets deleted after the browser window is closed
257 if (data.ticket) {
258 Proxmox.CSRFPreventionToken = data.CSRFPreventionToken;
259 Ext.util.Cookies.set(Proxmox.Setup.auth_cookie_name, data.ticket, null, '/', null, true);
260 }
261
262 if (data.token) {
263 window.localStorage.setItem('ProxmoxUser', JSON.stringify(data));
264 }
265 },
266
267 authOK: function() {
268 if (Proxmox.LoggedOut) {
269 return undefined;
270 }
271 let storedAuth = Proxmox.Utils.getStoredAuth();
272 let cookie = Ext.util.Cookies.get(Proxmox.Setup.auth_cookie_name);
273 if ((Proxmox.UserName !== '' && cookie && !cookie.startsWith("PVE:tfa!")) || storedAuth.token) {
274 return cookie || storedAuth.token;
275 } else {
276 return false;
277 }
278 },
279
280 authClear: function() {
281 if (Proxmox.LoggedOut) {
282 return;
283 }
284 Ext.util.Cookies.clear(Proxmox.Setup.auth_cookie_name);
285 window.localStorage.removeItem("ProxmoxUser");
286 },
287
288 // comp.setLoading() is buggy in ExtJS 4.0.7, so we
289 // use el.mask() instead
290 setErrorMask: function(comp, msg) {
291 let el = comp.el;
292 if (!el) {
293 return;
294 }
295 if (!msg) {
296 el.unmask();
297 } else if (msg === true) {
298 el.mask(gettext("Loading..."));
299 } else {
300 el.mask(msg);
301 }
302 },
303
304 getResponseErrorMessage: (err) => {
305 if (!err.statusText) {
306 return gettext('Connection error');
307 }
308 let msg = [`${err.statusText} (${err.status})`];
309 if (err.response && err.response.responseText) {
310 let txt = err.response.responseText;
311 try {
312 let res = JSON.parse(txt);
313 if (res.errors && typeof res.errors === 'object') {
314 for (let [key, value] of Object.entries(res.errors)) {
315 msg.push(Ext.String.htmlEncode(`${key}: ${value}`));
316 }
317 }
318 } catch (e) {
319 // fallback to string
320 msg.push(Ext.String.htmlEncode(txt));
321 }
322 }
323 return msg.join('<br>');
324 },
325
326 monStoreErrors: function(component, store, clearMaskBeforeLoad) {
327 if (clearMaskBeforeLoad) {
328 component.mon(store, 'beforeload', function(s, operation, eOpts) {
329 Proxmox.Utils.setErrorMask(component, false);
330 });
331 } else {
332 component.mon(store, 'beforeload', function(s, operation, eOpts) {
333 if (!component.loadCount) {
334 component.loadCount = 0; // make sure it is nucomponent.ic
335 Proxmox.Utils.setErrorMask(component, true);
336 }
337 });
338 }
339
340 // only works with 'proxmox' proxy
341 component.mon(store.proxy, 'afterload', function(proxy, request, success) {
342 component.loadCount++;
343
344 if (success) {
345 Proxmox.Utils.setErrorMask(component, false);
346 return;
347 }
348
349 let error = request._operation.getError();
350 let msg = Proxmox.Utils.getResponseErrorMessage(error);
351 Proxmox.Utils.setErrorMask(component, msg);
352 });
353 },
354
355 extractRequestError: function(result, verbose) {
356 let msg = gettext('Successful');
357
358 if (!result.success) {
359 msg = gettext("Unknown error");
360 if (result.message) {
361 msg = result.message;
362 if (result.status) {
363 msg += ' (' + result.status + ')';
364 }
365 }
366 if (verbose && Ext.isObject(result.errors)) {
367 msg += "<br>";
368 Ext.Object.each(result.errors, function(prop, desc) {
369 msg += "<br><b>" + Ext.htmlEncode(prop) + "</b>: " +
370 Ext.htmlEncode(desc);
371 });
372 }
373 }
374
375 return msg;
376 },
377
378 // Ext.Ajax.request
379 API2Request: function(reqOpts) {
380 let newopts = Ext.apply({
381 waitMsg: gettext('Please wait...'),
382 }, reqOpts);
383
384 if (!newopts.url.match(/^\/api2/)) {
385 newopts.url = '/api2/extjs' + newopts.url;
386 }
387 delete newopts.callback;
388
389 let createWrapper = function(successFn, callbackFn, failureFn) {
390 Ext.apply(newopts, {
391 success: function(response, options) {
392 if (options.waitMsgTarget) {
393 if (Proxmox.Utils.toolkit === 'touch') {
394 options.waitMsgTarget.setMasked(false);
395 } else {
396 options.waitMsgTarget.setLoading(false);
397 }
398 }
399 let result = Ext.decode(response.responseText);
400 response.result = result;
401 if (!result.success) {
402 response.htmlStatus = Proxmox.Utils.extractRequestError(result, true);
403 Ext.callback(callbackFn, options.scope, [options, false, response]);
404 Ext.callback(failureFn, options.scope, [response, options]);
405 return;
406 }
407 Ext.callback(callbackFn, options.scope, [options, true, response]);
408 Ext.callback(successFn, options.scope, [response, options]);
409 },
410 failure: function(response, options) {
411 if (options.waitMsgTarget) {
412 if (Proxmox.Utils.toolkit === 'touch') {
413 options.waitMsgTarget.setMasked(false);
414 } else {
415 options.waitMsgTarget.setLoading(false);
416 }
417 }
418 response.result = {};
419 try {
420 response.result = Ext.decode(response.responseText);
421 } catch (e) {
422 // ignore
423 }
424 let msg = gettext('Connection error') + ' - server offline?';
425 if (response.aborted) {
426 msg = gettext('Connection error') + ' - aborted.';
427 } else if (response.timedout) {
428 msg = gettext('Connection error') + ' - Timeout.';
429 } else if (response.status && response.statusText) {
430 msg = gettext('Connection error') + ' ' + response.status + ': ' + response.statusText;
431 }
432 response.htmlStatus = msg;
433 Ext.callback(callbackFn, options.scope, [options, false, response]);
434 Ext.callback(failureFn, options.scope, [response, options]);
435 },
436 });
437 };
438
439 createWrapper(reqOpts.success, reqOpts.callback, reqOpts.failure);
440
441 let target = newopts.waitMsgTarget;
442 if (target) {
443 if (Proxmox.Utils.toolkit === 'touch') {
444 target.setMasked({ xtype: 'loadmask', message: newopts.waitMsg });
445 } else {
446 // Note: ExtJS bug - this does not work when component is not rendered
447 target.setLoading(newopts.waitMsg);
448 }
449 }
450 Ext.Ajax.request(newopts);
451 },
452
453 checked_command: function(orig_cmd) {
454 Proxmox.Utils.API2Request(
455 {
456 url: '/nodes/localhost/subscription',
457 method: 'GET',
458 failure: function(response, opts) {
459 Ext.Msg.alert(gettext('Error'), response.htmlStatus);
460 },
461 success: function(response, opts) {
462 let res = response.result;
463 if (res === null || res === undefined || !res || res
464 .data.status.toLowerCase() !== 'active') {
465 Ext.Msg.show({
466 title: gettext('No valid subscription'),
467 icon: Ext.Msg.WARNING,
468 message: Proxmox.Utils.getNoSubKeyHtml(res.data.url),
469 buttons: Ext.Msg.OK,
470 callback: function(btn) {
471 if (btn !== 'ok') {
472 return;
473 }
474 orig_cmd();
475 },
476 });
477 } else {
478 orig_cmd();
479 }
480 },
481 },
482 );
483 },
484
485 assemble_field_data: function(values, data) {
486 if (!Ext.isObject(data)) {
487 return;
488 }
489 Ext.Object.each(data, function(name, val) {
490 if (Object.prototype.hasOwnProperty.call(values, name)) {
491 let bucket = values[name];
492 if (!Ext.isArray(bucket)) {
493 bucket = values[name] = [bucket];
494 }
495 if (Ext.isArray(val)) {
496 values[name] = bucket.concat(val);
497 } else {
498 bucket.push(val);
499 }
500 } else {
501 values[name] = val;
502 }
503 });
504 },
505
506 updateColumnWidth: function(container) {
507 let mode = Ext.state.Manager.get('summarycolumns') || 'auto';
508 let factor;
509 if (mode !== 'auto') {
510 factor = parseInt(mode, 10);
511 if (Number.isNaN(factor)) {
512 factor = 1;
513 }
514 } else {
515 factor = container.getSize().width < 1600 ? 1 : 2;
516 }
517
518 if (container.oldFactor === factor) {
519 return;
520 }
521
522 let items = container.query('>'); // direct childs
523 factor = Math.min(factor, items.length);
524 container.oldFactor = factor;
525
526 items.forEach((item) => {
527 item.columnWidth = 1 / factor;
528 });
529
530 // we have to update the layout twice, since the first layout change
531 // can trigger the scrollbar which reduces the amount of space left
532 container.updateLayout();
533 container.updateLayout();
534 },
535
536 dialog_title: function(subject, create, isAdd) {
537 if (create) {
538 if (isAdd) {
539 return gettext('Add') + ': ' + subject;
540 } else {
541 return gettext('Create') + ': ' + subject;
542 }
543 } else {
544 return gettext('Edit') + ': ' + subject;
545 }
546 },
547
548 network_iface_types: {
549 eth: gettext("Network Device"),
550 bridge: 'Linux Bridge',
551 bond: 'Linux Bond',
552 vlan: 'Linux VLAN',
553 OVSBridge: 'OVS Bridge',
554 OVSBond: 'OVS Bond',
555 OVSPort: 'OVS Port',
556 OVSIntPort: 'OVS IntPort',
557 },
558
559 render_network_iface_type: function(value) {
560 return Proxmox.Utils.network_iface_types[value] ||
561 Proxmox.Utils.unknownText;
562 },
563
564 task_desc_table: {
565 acmenewcert: ['SRV', gettext('Order Certificate')],
566 acmeregister: ['ACME Account', gettext('Register')],
567 acmedeactivate: ['ACME Account', gettext('Deactivate')],
568 acmeupdate: ['ACME Account', gettext('Update')],
569 acmerefresh: ['ACME Account', gettext('Refresh')],
570 acmerenew: ['SRV', gettext('Renew Certificate')],
571 acmerevoke: ['SRV', gettext('Revoke Certificate')],
572 'auth-realm-sync': [gettext('Realm'), gettext('Sync')],
573 'auth-realm-sync-test': [gettext('Realm'), gettext('Sync Preview')],
574 'move_volume': ['CT', gettext('Move Volume')],
575 clustercreate: ['', gettext('Create Cluster')],
576 clusterjoin: ['', gettext('Join Cluster')],
577 diskinit: ['Disk', gettext('Initialize Disk with GPT')],
578 vncproxy: ['VM/CT', gettext('Console')],
579 spiceproxy: ['VM/CT', gettext('Console') + ' (Spice)'],
580 vncshell: ['', gettext('Shell')],
581 spiceshell: ['', gettext('Shell') + ' (Spice)'],
582 qmsnapshot: ['VM', gettext('Snapshot')],
583 qmrollback: ['VM', gettext('Rollback')],
584 qmdelsnapshot: ['VM', gettext('Delete Snapshot')],
585 qmcreate: ['VM', gettext('Create')],
586 qmrestore: ['VM', gettext('Restore')],
587 qmdestroy: ['VM', gettext('Destroy')],
588 qmigrate: ['VM', gettext('Migrate')],
589 qmclone: ['VM', gettext('Clone')],
590 qmmove: ['VM', gettext('Move disk')],
591 qmtemplate: ['VM', gettext('Convert to template')],
592 qmstart: ['VM', gettext('Start')],
593 qmstop: ['VM', gettext('Stop')],
594 qmreset: ['VM', gettext('Reset')],
595 qmshutdown: ['VM', gettext('Shutdown')],
596 qmreboot: ['VM', gettext('Reboot')],
597 qmsuspend: ['VM', gettext('Hibernate')],
598 qmpause: ['VM', gettext('Pause')],
599 qmresume: ['VM', gettext('Resume')],
600 qmconfig: ['VM', gettext('Configure')],
601 vzsnapshot: ['CT', gettext('Snapshot')],
602 vzrollback: ['CT', gettext('Rollback')],
603 vzdelsnapshot: ['CT', gettext('Delete Snapshot')],
604 vzcreate: ['CT', gettext('Create')],
605 vzrestore: ['CT', gettext('Restore')],
606 vzdestroy: ['CT', gettext('Destroy')],
607 vzmigrate: ['CT', gettext('Migrate')],
608 vzclone: ['CT', gettext('Clone')],
609 vztemplate: ['CT', gettext('Convert to template')],
610 vzstart: ['CT', gettext('Start')],
611 vzstop: ['CT', gettext('Stop')],
612 vzmount: ['CT', gettext('Mount')],
613 vzumount: ['CT', gettext('Unmount')],
614 vzshutdown: ['CT', gettext('Shutdown')],
615 vzreboot: ['CT', gettext('Reboot')],
616 vzsuspend: ['CT', gettext('Suspend')],
617 vzresume: ['CT', gettext('Resume')],
618 push_file: ['CT', gettext('Push file')],
619 pull_file: ['CT', gettext('Pull file')],
620 hamigrate: ['HA', gettext('Migrate')],
621 hastart: ['HA', gettext('Start')],
622 hastop: ['HA', gettext('Stop')],
623 hashutdown: ['HA', gettext('Shutdown')],
624 srvstart: ['SRV', gettext('Start')],
625 srvstop: ['SRV', gettext('Stop')],
626 srvrestart: ['SRV', gettext('Restart')],
627 srvreload: ['SRV', gettext('Reload')],
628 cephcreatemgr: ['Ceph Manager', gettext('Create')],
629 cephdestroymgr: ['Ceph Manager', gettext('Destroy')],
630 cephcreatemon: ['Ceph Monitor', gettext('Create')],
631 cephdestroymon: ['Ceph Monitor', gettext('Destroy')],
632 cephcreateosd: ['Ceph OSD', gettext('Create')],
633 cephdestroyosd: ['Ceph OSD', gettext('Destroy')],
634 cephcreatepool: ['Ceph Pool', gettext('Create')],
635 cephdestroypool: ['Ceph Pool', gettext('Destroy')],
636 cephfscreate: ['CephFS', gettext('Create')],
637 cephcreatemds: ['Ceph Metadata Server', gettext('Create')],
638 cephdestroymds: ['Ceph Metadata Server', gettext('Destroy')],
639 imgcopy: ['', gettext('Copy data')],
640 imgdel: ['', gettext('Erase data')],
641 unknownimgdel: ['', gettext('Destroy image from unknown guest')],
642 download: ['', gettext('Download')],
643 vzdump: (type, id) => id ? `VM/CT ${id} - ${gettext('Backup')}` : gettext('Backup Job'),
644 aptupdate: ['', gettext('Update package database')],
645 startall: ['', gettext('Start all VMs and Containers')],
646 stopall: ['', gettext('Stop all VMs and Containers')],
647 migrateall: ['', gettext('Migrate all VMs and Containers')],
648 dircreate: [gettext('Directory Storage'), gettext('Create')],
649 dirremove: [gettext('Directory'), gettext('Remove')],
650 lvmcreate: [gettext('LVM Storage'), gettext('Create')],
651 lvmthincreate: [gettext('LVM-Thin Storage'), gettext('Create')],
652 zfscreate: [gettext('ZFS Storage'), gettext('Create')],
653 },
654
655 // to add or change existing for product specific ones
656 override_task_descriptions: function(extra) {
657 for (const [key, value] of Object.entries(extra)) {
658 Proxmox.Utils.task_desc_table[key] = value;
659 }
660 },
661
662 format_task_description: function(type, id) {
663 let farray = Proxmox.Utils.task_desc_table[type];
664 let text;
665 if (!farray) {
666 text = type;
667 if (id) {
668 type += ' ' + id;
669 }
670 return text;
671 } else if (Ext.isFunction(farray)) {
672 return farray(type, id);
673 }
674 let prefix = farray[0];
675 text = farray[1];
676 if (prefix && id !== undefined) {
677 return prefix + ' ' + id + ' - ' + text;
678 }
679 return text;
680 },
681
682 format_size: function(size) {
683 let units = ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi', 'Yi'];
684 let num = 0;
685 while (size >= 1024 && num++ <= units.length) {
686 size = size / 1024;
687 }
688
689 return size.toFixed(num > 0?2:0) + " " + units[num] + "B";
690 },
691
692 render_upid: function(value, metaData, record) {
693 let task = record.data;
694 let type = task.type || task.worker_type;
695 let id = task.id || task.worker_id;
696
697 return Proxmox.Utils.format_task_description(type, id);
698 },
699
700 render_uptime: function(value) {
701 let uptime = value;
702
703 if (uptime === undefined) {
704 return '';
705 }
706
707 if (uptime <= 0) {
708 return '-';
709 }
710
711 return Proxmox.Utils.format_duration_long(uptime);
712 },
713
714 systemd_unescape: function(string_value) {
715 const charcode_0 = '0'.charCodeAt(0);
716 const charcode_9 = '9'.charCodeAt(0);
717 const charcode_A = 'A'.charCodeAt(0);
718 const charcode_F = 'F'.charCodeAt(0);
719 const charcode_a = 'a'.charCodeAt(0);
720 const charcode_f = 'f'.charCodeAt(0);
721 const charcode_x = 'x'.charCodeAt(0);
722 const charcode_minus = '-'.charCodeAt(0);
723 const charcode_slash = '/'.charCodeAt(0);
724 const charcode_backslash = '\\'.charCodeAt(0);
725
726 let parse_hex_digit = function(d) {
727 if (d >= charcode_0 && d <= charcode_9) {
728 return d - charcode_0;
729 }
730 if (d >= charcode_A && d <= charcode_F) {
731 return d - charcode_A + 10;
732 }
733 if (d >= charcode_a && d <= charcode_f) {
734 return d - charcode_a + 10;
735 }
736 throw "got invalid hex digit";
737 };
738
739 let value = new TextEncoder().encode(string_value);
740 let result = new Uint8Array(value.length);
741
742 let i = 0;
743 let result_len = 0;
744
745 while (i < value.length) {
746 let c0 = value[i];
747 if (c0 === charcode_minus) {
748 result.set([charcode_slash], result_len);
749 result_len += 1;
750 i += 1;
751 continue;
752 }
753 if ((i + 4) < value.length) {
754 let c1 = value[i+1];
755 if (c0 === charcode_backslash && c1 === charcode_x) {
756 let h1 = parse_hex_digit(value[i+2]);
757 let h0 = parse_hex_digit(value[i+3]);
758 let ord = h1*16+h0;
759 result.set([ord], result_len);
760 result_len += 1;
761 i += 4;
762 continue;
763 }
764 }
765 result.set([c0], result_len);
766 result_len += 1;
767 i += 1;
768 }
769
770 return new TextDecoder().decode(result.slice(0, result.len));
771 },
772
773 parse_task_upid: function(upid) {
774 let task = {};
775
776 let res = upid.match(/^UPID:([^\s:]+):([0-9A-Fa-f]{8}):([0-9A-Fa-f]{8,9}):(([0-9A-Fa-f]{8,16}):)?([0-9A-Fa-f]{8}):([^:\s]+):([^:\s]*):([^:\s]+):$/);
777 if (!res) {
778 throw "unable to parse upid '" + upid + "'";
779 }
780 task.node = res[1];
781 task.pid = parseInt(res[2], 16);
782 task.pstart = parseInt(res[3], 16);
783 if (res[5] !== undefined) {
784 task.task_id = parseInt(res[5], 16);
785 }
786 task.starttime = parseInt(res[6], 16);
787 task.type = res[7];
788 task.id = Proxmox.Utils.systemd_unescape(res[8]);
789 task.user = res[9];
790
791 task.desc = Proxmox.Utils.format_task_description(task.type, task.id);
792
793 return task;
794 },
795
796 parse_task_status: function(status) {
797 if (status === 'OK') {
798 return 'ok';
799 }
800
801 if (status === 'unknown') {
802 return 'unknown';
803 }
804
805 let match = status.match(/^WARNINGS: (.*)$/);
806 if (match) {
807 return 'warning';
808 }
809
810 return 'error';
811 },
812
813 render_duration: function(value) {
814 if (value === undefined) {
815 return '-';
816 }
817 return Proxmox.Utils.format_duration_human(value);
818 },
819
820 render_timestamp: function(value, metaData, record, rowIndex, colIndex, store) {
821 let servertime = new Date(value * 1000);
822 return Ext.Date.format(servertime, 'Y-m-d H:i:s');
823 },
824
825 render_zfs_health: function(value) {
826 if (typeof value === 'undefined') {
827 return "";
828 }
829 var iconCls = 'question-circle';
830 switch (value) {
831 case 'AVAIL':
832 case 'ONLINE':
833 iconCls = 'check-circle good';
834 break;
835 case 'REMOVED':
836 case 'DEGRADED':
837 iconCls = 'exclamation-circle warning';
838 break;
839 case 'UNAVAIL':
840 case 'FAULTED':
841 case 'OFFLINE':
842 iconCls = 'times-circle critical';
843 break;
844 default: //unknown
845 }
846
847 return '<i class="fa fa-' + iconCls + '"></i> ' + value;
848 },
849
850 get_help_info: function(section) {
851 let helpMap;
852 if (typeof proxmoxOnlineHelpInfo !== 'undefined') {
853 helpMap = proxmoxOnlineHelpInfo; // eslint-disable-line no-undef
854 } else if (typeof pveOnlineHelpInfo !== 'undefined') {
855 // be backward compatible with older pve-doc-generators
856 helpMap = pveOnlineHelpInfo; // eslint-disable-line no-undef
857 } else {
858 throw "no global OnlineHelpInfo map declared";
859 }
860
861 if (helpMap[section]) {
862 return helpMap[section];
863 }
864 // try to normalize - and _ separators, to support asciidoc and sphinx
865 // references at the same time.
866 let section_minus_normalized = section.replace(/_/, '-');
867 if (helpMap[section_minus_normalized]) {
868 return helpMap[section_minus_normalized];
869 }
870 let section_underscore_normalized = section.replace(/-/, '_');
871 return helpMap[section_underscore_normalized];
872 },
873
874 get_help_link: function(section) {
875 let info = Proxmox.Utils.get_help_info(section);
876 if (!info) {
877 return undefined;
878 }
879 return window.location.origin + info.link;
880 },
881
882 openXtermJsViewer: function(vmtype, vmid, nodename, vmname, cmd) {
883 let url = Ext.Object.toQueryString({
884 console: vmtype, // kvm, lxc, upgrade or shell
885 xtermjs: 1,
886 vmid: vmid,
887 vmname: vmname,
888 node: nodename,
889 cmd: cmd,
890
891 });
892 let nw = window.open("?" + url, '_blank', 'toolbar=no,location=no,status=no,menubar=no,resizable=yes,width=800,height=420');
893 if (nw) {
894 nw.focus();
895 }
896 },
897
898 },
899
900 singleton: true,
901 constructor: function() {
902 let me = this;
903 Ext.apply(me, me.utilities);
904
905 let IPV4_OCTET = "(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])";
906 let IPV4_REGEXP = "(?:(?:" + IPV4_OCTET + "\\.){3}" + IPV4_OCTET + ")";
907 let IPV6_H16 = "(?:[0-9a-fA-F]{1,4})";
908 let IPV6_LS32 = "(?:(?:" + IPV6_H16 + ":" + IPV6_H16 + ")|" + IPV4_REGEXP + ")";
909 let IPV4_CIDR_MASK = "([0-9]{1,2})";
910 let IPV6_CIDR_MASK = "([0-9]{1,3})";
911
912
913 me.IP4_match = new RegExp("^(?:" + IPV4_REGEXP + ")$");
914 me.IP4_cidr_match = new RegExp("^(?:" + IPV4_REGEXP + ")/" + IPV4_CIDR_MASK + "$");
915
916 /* eslint-disable no-useless-concat,no-multi-spaces */
917 let IPV6_REGEXP = "(?:" +
918 "(?:(?:" + "(?:" + IPV6_H16 + ":){6})" + IPV6_LS32 + ")|" +
919 "(?:(?:" + "::" + "(?:" + IPV6_H16 + ":){5})" + IPV6_LS32 + ")|" +
920 "(?:(?:(?:" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){4})" + IPV6_LS32 + ")|" +
921 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,1}" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){3})" + IPV6_LS32 + ")|" +
922 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,2}" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){2})" + IPV6_LS32 + ")|" +
923 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,3}" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){1})" + IPV6_LS32 + ")|" +
924 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,4}" + IPV6_H16 + ")?::" + ")" + IPV6_LS32 + ")|" +
925 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,5}" + IPV6_H16 + ")?::" + ")" + IPV6_H16 + ")|" +
926 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,7}" + IPV6_H16 + ")?::" + ")" + ")" +
927 ")";
928 /* eslint-enable no-useless-concat,no-multi-spaces */
929
930 me.IP6_match = new RegExp("^(?:" + IPV6_REGEXP + ")$");
931 me.IP6_cidr_match = new RegExp("^(?:" + IPV6_REGEXP + ")/" + IPV6_CIDR_MASK + "$");
932 me.IP6_bracket_match = new RegExp("^\\[(" + IPV6_REGEXP + ")\\]");
933
934 me.IP64_match = new RegExp("^(?:" + IPV6_REGEXP + "|" + IPV4_REGEXP + ")$");
935 me.IP64_cidr_match = new RegExp("^(?:" + IPV6_REGEXP + "/" + IPV6_CIDR_MASK + ")|(?:" + IPV4_REGEXP + "/" + IPV4_CIDR_MASK + ")$");
936
937 let DnsName_REGEXP = "(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\\-]*[a-zA-Z0-9])?)\\.)*(?:[A-Za-z0-9](?:[A-Za-z0-9\\-]*[A-Za-z0-9])?))";
938 me.DnsName_match = new RegExp("^" + DnsName_REGEXP + "$");
939
940 me.HostPort_match = new RegExp("^(" + IPV4_REGEXP + "|" + DnsName_REGEXP + ")(?::(\\d+))?$");
941 me.HostPortBrackets_match = new RegExp("^\\[(" + IPV6_REGEXP + "|" + IPV4_REGEXP + "|" + DnsName_REGEXP + ")\\](?::(\\d+))?$");
942 me.IP6_dotnotation_match = new RegExp("^(" + IPV6_REGEXP + ")(?:\\.(\\d+))?$");
943 me.Vlan_match = /^vlan(\\d+)/;
944 me.VlanInterface_match = /(\\w+)\\.(\\d+)/;
945 },
946 });