2 Ext
.ns('Proxmox.Setup');
4 if (!Ext
.isDefined(Proxmox
.Setup
.auth_cookie_name
)) {
5 throw "Proxmox library not initialized";
8 // avoid errors when running without development tools
9 if (!Ext
.isDefined(Ext
.global
.console
)) {
21 Ext
.global
.console
= console
;
24 Ext
.Ajax
.defaultHeaders
= {
25 'Accept': 'application/json',
28 Ext
.Ajax
.on('beforerequest', function(conn
, options
) {
29 if (Proxmox
.CSRFPreventionToken
) {
30 if (!options
.headers
) {
33 options
.headers
.CSRFPreventionToken
= Proxmox
.CSRFPreventionToken
;
35 let storedAuth
= Proxmox
.Utils
.getStoredAuth();
36 if (storedAuth
.token
) {
37 options
.headers
.Authorization
= storedAuth
.token
;
41 Ext
.define('Proxmox.Utils', { // a singleton
44 yesText
: gettext('Yes'),
45 noText
: gettext('No'),
46 enabledText
: gettext('Enabled'),
47 disabledText
: gettext('Disabled'),
48 noneText
: gettext('none'),
49 NoneText
: gettext('None'),
50 errorText
: gettext('Error'),
51 warningsText
: gettext('Warnings'),
52 unknownText
: gettext('Unknown'),
53 defaultText
: gettext('Default'),
54 daysText
: gettext('days'),
55 dayText
: gettext('day'),
56 runningText
: gettext('running'),
57 stoppedText
: gettext('stopped'),
58 neverText
: gettext('never'),
59 totalText
: gettext('Total'),
60 usedText
: gettext('Used'),
61 directoryText
: gettext('Directory'),
62 stateText
: gettext('State'),
63 groupText
: gettext('Group'),
68 zh_CN
: 'Chinese (Simplified)',
69 zh_TW
: 'Chinese (Traditional)',
73 eu
: 'Euskera (Basque)',
80 nb
: 'Norwegian (Bokmal)',
81 nn
: 'Norwegian (Nynorsk)',
82 fa
: 'Persian (Farsi)',
84 pt_BR
: 'Portuguese (Brazil)',
92 render_language: function(value
) {
94 return Proxmox
.Utils
.defaultText
+ ' (English)';
96 let text
= Proxmox
.Utils
.language_map
[value
];
98 return text
+ ' (' + value
+ ')';
103 language_array: function() {
104 let data
= [['__default__', Proxmox
.Utils
.render_language('')]];
105 Ext
.Object
.each(Proxmox
.Utils
.language_map
, function(key
, value
) {
106 data
.push([key
, Proxmox
.Utils
.render_language(value
)]);
112 bond_mode_gettext_map
: {
113 '802.3ad': 'LACP (802.3ad)',
114 'lacp-balance-slb': 'LACP (balance-slb)',
115 'lacp-balance-tcp': 'LACP (balance-tcp)',
118 render_bond_mode
: value
=> Proxmox
.Utils
.bond_mode_gettext_map
[value
] || value
|| '',
120 bond_mode_array: function(modes
) {
121 return modes
.map(mode
=> [mode
, Proxmox
.Utils
.render_bond_mode(mode
)]);
124 getNoSubKeyHtml: function(url
) {
125 // url http://www.proxmox.com/products/proxmox-ve/subscription-service-plans
126 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');
129 format_boolean_with_default: function(value
) {
130 if (Ext
.isDefined(value
) && value
!== '__default__') {
131 return value
? Proxmox
.Utils
.yesText
: Proxmox
.Utils
.noText
;
133 return Proxmox
.Utils
.defaultText
;
136 format_boolean: function(value
) {
137 return value
? Proxmox
.Utils
.yesText
: Proxmox
.Utils
.noText
;
140 format_neg_boolean: function(value
) {
141 return !value
? Proxmox
.Utils
.yesText
: Proxmox
.Utils
.noText
;
144 format_enabled_toggle: function(value
) {
145 return value
? Proxmox
.Utils
.enabledText
: Proxmox
.Utils
.disabledText
;
148 format_expire: function(date
) {
150 return Proxmox
.Utils
.neverText
;
152 return Ext
.Date
.format(date
, "Y-m-d");
155 // somewhat like a human would tell durations, omit zero values and do not
156 // give seconds precision if we talk days already
157 format_duration_human: function(ut
) {
158 let seconds
= 0, minutes
= 0, hours
= 0, days
= 0;
165 seconds
= Number((remaining
% 60).toFixed(1));
166 remaining
= Math
.trunc(remaining
/ 60);
168 minutes
= remaining
% 60;
169 remaining
= Math
.trunc(remaining
/ 60);
171 hours
= remaining
% 24;
172 remaining
= Math
.trunc(remaining
/ 24);
180 let add
= (t
, unit
) => {
181 if (t
> 0) res
.push(t
+ unit
);
185 let addSeconds
= !add(days
, 'd');
191 return res
.join(' ');
194 format_duration_long: function(ut
) {
195 let days
= Math
.floor(ut
/ 86400);
197 let hours
= Math
.floor(ut
/ 3600);
199 let mins
= Math
.floor(ut
/ 60);
202 let hours_str
= '00' + hours
.toString();
203 hours_str
= hours_str
.substr(hours_str
.length
- 2);
204 let mins_str
= "00" + mins
.toString();
205 mins_str
= mins_str
.substr(mins_str
.length
- 2);
206 let ut_str
= "00" + ut
.toString();
207 ut_str
= ut_str
.substr(ut_str
.length
- 2);
210 let ds
= days
> 1 ? Proxmox
.Utils
.daysText
: Proxmox
.Utils
.dayText
;
211 return days
.toString() + ' ' + ds
+ ' ' +
212 hours_str
+ ':' + mins_str
+ ':' + ut_str
;
214 return hours_str
+ ':' + mins_str
+ ':' + ut_str
;
218 format_subscription_level: function(level
) {
221 } else if (level
=== 'b') {
223 } else if (level
=== 's') {
225 } else if (level
=== 'p') {
228 return Proxmox
.Utils
.noneText
;
232 compute_min_label_width: function(text
, width
) {
233 if (width
=== undefined) { width
= 100; }
235 let tm
= new Ext
.util
.TextMetrics();
236 let min
= tm
.getWidth(text
+ ':');
238 return min
< width
? width
: min
;
241 getStoredAuth: function() {
242 let storedAuth
= JSON
.parse(window
.localStorage
.getItem('ProxmoxUser'));
243 return storedAuth
|| {};
246 setAuthData: function(data
) {
247 Proxmox
.UserName
= data
.username
;
248 Proxmox
.LoggedOut
= data
.LoggedOut
;
249 // creates a session cookie (expire = null)
250 // that way the cookie gets deleted after the browser window is closed
252 Proxmox
.CSRFPreventionToken
= data
.CSRFPreventionToken
;
253 Ext
.util
.Cookies
.set(Proxmox
.Setup
.auth_cookie_name
, data
.ticket
, null, '/', null, true);
257 window
.localStorage
.setItem('ProxmoxUser', JSON
.stringify(data
));
262 if (Proxmox
.LoggedOut
) {
265 let storedAuth
= Proxmox
.Utils
.getStoredAuth();
266 let cookie
= Ext
.util
.Cookies
.get(Proxmox
.Setup
.auth_cookie_name
);
267 if ((Proxmox
.UserName
!== '' && cookie
&& !cookie
.startsWith("PVE:tfa!")) || storedAuth
.token
) {
268 return cookie
|| storedAuth
.token
;
274 authClear: function() {
275 if (Proxmox
.LoggedOut
) {
278 Ext
.util
.Cookies
.clear(Proxmox
.Setup
.auth_cookie_name
);
279 window
.localStorage
.removeItem("ProxmoxUser");
282 // comp.setLoading() is buggy in ExtJS 4.0.7, so we
283 // use el.mask() instead
284 setErrorMask: function(comp
, msg
) {
291 } else if (msg
=== true) {
292 el
.mask(gettext("Loading..."));
298 getResponseErrorMessage
: (err
) => {
299 if (!err
.statusText
) {
300 return gettext('Connection error');
302 let msg
= [`${err.statusText} (${err.status})`];
303 if (err
.response
&& err
.response
.responseText
) {
304 let txt
= err
.response
.responseText
;
306 let res
= JSON
.parse(txt
);
307 if (res
.errors
&& typeof res
.errors
=== 'object') {
308 for (let [key
, value
] of Object
.entries(res
.errors
)) {
309 msg
.push(Ext
.String
.htmlEncode(`${key}: ${value}`));
313 // fallback to string
314 msg
.push(Ext
.String
.htmlEncode(txt
));
317 return msg
.join('<br>');
320 monStoreErrors: function(component
, store
, clearMaskBeforeLoad
, errorCallback
) {
321 if (clearMaskBeforeLoad
) {
322 component
.mon(store
, 'beforeload', function(s
, operation
, eOpts
) {
323 Proxmox
.Utils
.setErrorMask(component
, false);
326 component
.mon(store
, 'beforeload', function(s
, operation
, eOpts
) {
327 if (!component
.loadCount
) {
328 component
.loadCount
= 0; // make sure it is nucomponent.ic
329 Proxmox
.Utils
.setErrorMask(component
, true);
334 // only works with 'proxmox' proxy
335 component
.mon(store
.proxy
, 'afterload', function(proxy
, request
, success
) {
336 component
.loadCount
++;
339 Proxmox
.Utils
.setErrorMask(component
, false);
343 let error
= request
._operation
.getError();
344 let msg
= Proxmox
.Utils
.getResponseErrorMessage(error
);
345 if (!errorCallback
|| !errorCallback(error
, msg
)) {
346 Proxmox
.Utils
.setErrorMask(component
, msg
);
351 extractRequestError: function(result
, verbose
) {
352 let msg
= gettext('Successful');
354 if (!result
.success
) {
355 msg
= gettext("Unknown error");
356 if (result
.message
) {
357 msg
= result
.message
;
359 msg
+= ' (' + result
.status
+ ')';
362 if (verbose
&& Ext
.isObject(result
.errors
)) {
364 Ext
.Object
.each(result
.errors
, function(prop
, desc
) {
365 msg
+= "<br><b>" + Ext
.htmlEncode(prop
) + "</b>: " +
366 Ext
.htmlEncode(desc
);
375 API2Request: function(reqOpts
) {
376 let newopts
= Ext
.apply({
377 waitMsg
: gettext('Please wait...'),
380 if (!newopts
.url
.match(/^\/api2/)) {
381 newopts
.url
= '/api2/extjs' + newopts
.url
;
383 delete newopts
.callback
;
385 let createWrapper = function(successFn
, callbackFn
, failureFn
) {
387 success: function(response
, options
) {
388 if (options
.waitMsgTarget
) {
389 if (Proxmox
.Utils
.toolkit
=== 'touch') {
390 options
.waitMsgTarget
.setMasked(false);
392 options
.waitMsgTarget
.setLoading(false);
395 let result
= Ext
.decode(response
.responseText
);
396 response
.result
= result
;
397 if (!result
.success
) {
398 response
.htmlStatus
= Proxmox
.Utils
.extractRequestError(result
, true);
399 Ext
.callback(callbackFn
, options
.scope
, [options
, false, response
]);
400 Ext
.callback(failureFn
, options
.scope
, [response
, options
]);
403 Ext
.callback(callbackFn
, options
.scope
, [options
, true, response
]);
404 Ext
.callback(successFn
, options
.scope
, [response
, options
]);
406 failure: function(response
, options
) {
407 if (options
.waitMsgTarget
) {
408 if (Proxmox
.Utils
.toolkit
=== 'touch') {
409 options
.waitMsgTarget
.setMasked(false);
411 options
.waitMsgTarget
.setLoading(false);
414 response
.result
= {};
416 response
.result
= Ext
.decode(response
.responseText
);
420 let msg
= gettext('Connection error') + ' - server offline?';
421 if (response
.aborted
) {
422 msg
= gettext('Connection error') + ' - aborted.';
423 } else if (response
.timedout
) {
424 msg
= gettext('Connection error') + ' - Timeout.';
425 } else if (response
.status
&& response
.statusText
) {
426 msg
= gettext('Connection error') + ' ' + response
.status
+ ': ' + response
.statusText
;
428 response
.htmlStatus
= msg
;
429 Ext
.callback(callbackFn
, options
.scope
, [options
, false, response
]);
430 Ext
.callback(failureFn
, options
.scope
, [response
, options
]);
435 createWrapper(reqOpts
.success
, reqOpts
.callback
, reqOpts
.failure
);
437 let target
= newopts
.waitMsgTarget
;
439 if (Proxmox
.Utils
.toolkit
=== 'touch') {
440 target
.setMasked({ xtype
: 'loadmask', message
: newopts
.waitMsg
});
442 // Note: ExtJS bug - this does not work when component is not rendered
443 target
.setLoading(newopts
.waitMsg
);
446 Ext
.Ajax
.request(newopts
);
449 // can be useful for catching displaying errors from the API, e.g.:
450 // Proxmox.Async.api2({
452 // }).catch(Proxmox.Utils.alertResponseFailure);
453 alertResponseFailure
: (response
) => {
456 response
.htmlStatus
|| response
.result
.message
,
460 checked_command: function(orig_cmd
) {
461 Proxmox
.Utils
.API2Request(
463 url
: '/nodes/localhost/subscription',
465 failure: function(response
, opts
) {
466 Ext
.Msg
.alert(gettext('Error'), response
.htmlStatus
);
468 success: function(response
, opts
) {
469 let res
= response
.result
;
470 if (res
=== null || res
=== undefined || !res
|| res
471 .data
.status
.toLowerCase() !== 'active') {
473 title
: gettext('No valid subscription'),
474 icon
: Ext
.Msg
.WARNING
,
475 message
: Proxmox
.Utils
.getNoSubKeyHtml(res
.data
.url
),
477 callback: function(btn
) {
492 assemble_field_data: function(values
, data
) {
493 if (!Ext
.isObject(data
)) {
496 Ext
.Object
.each(data
, function(name
, val
) {
497 if (Object
.prototype.hasOwnProperty
.call(values
, name
)) {
498 let bucket
= values
[name
];
499 if (!Ext
.isArray(bucket
)) {
500 bucket
= values
[name
] = [bucket
];
502 if (Ext
.isArray(val
)) {
503 values
[name
] = bucket
.concat(val
);
513 updateColumnWidth: function(container
) {
514 let mode
= Ext
.state
.Manager
.get('summarycolumns') || 'auto';
516 if (mode
!== 'auto') {
517 factor
= parseInt(mode
, 10);
518 if (Number
.isNaN(factor
)) {
522 factor
= container
.getSize().width
< 1600 ? 1 : 2;
525 if (container
.oldFactor
=== factor
) {
529 let items
= container
.query('>'); // direct childs
530 factor
= Math
.min(factor
, items
.length
);
531 container
.oldFactor
= factor
;
533 items
.forEach((item
) => {
534 item
.columnWidth
= 1 / factor
;
537 // we have to update the layout twice, since the first layout change
538 // can trigger the scrollbar which reduces the amount of space left
539 container
.updateLayout();
540 container
.updateLayout();
543 dialog_title: function(subject
, create
, isAdd
) {
546 return gettext('Add') + ': ' + subject
;
548 return gettext('Create') + ': ' + subject
;
551 return gettext('Edit') + ': ' + subject
;
555 network_iface_types
: {
556 eth
: gettext("Network Device"),
557 bridge
: 'Linux Bridge',
560 OVSBridge
: 'OVS Bridge',
563 OVSIntPort
: 'OVS IntPort',
566 render_network_iface_type: function(value
) {
567 return Proxmox
.Utils
.network_iface_types
[value
] ||
568 Proxmox
.Utils
.unknownText
;
571 // NOTE: only add general, product agnostic, ones here! Else use override helper in product repos
573 aptupdate
: ['', gettext('Update package database')],
574 diskinit
: ['Disk', gettext('Initialize Disk with GPT')],
575 spiceshell
: ['', gettext('Shell') + ' (Spice)'],
576 srvreload
: ['SRV', gettext('Reload')],
577 srvrestart
: ['SRV', gettext('Restart')],
578 srvstart
: ['SRV', gettext('Start')],
579 srvstop
: ['SRV', gettext('Stop')],
580 termproxy
: ['', gettext('Console') + ' (xterm.js)'],
581 vncshell
: ['', gettext('Shell')],
584 // to add or change existing for product specific ones
585 override_task_descriptions: function(extra
) {
586 for (const [key
, value
] of Object
.entries(extra
)) {
587 Proxmox
.Utils
.task_desc_table
[key
] = value
;
591 format_task_description: function(type
, id
) {
592 let farray
= Proxmox
.Utils
.task_desc_table
[type
];
600 } else if (Ext
.isFunction(farray
)) {
601 return farray(type
, id
);
603 let prefix
= farray
[0];
605 if (prefix
&& id
!== undefined) {
606 return prefix
+ ' ' + id
+ ' - ' + text
;
611 format_size: function(size
, useSI
) {
612 let units
= ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'];
614 const baseValue
= useSI
? 1000 : 1024;
615 while (size
>= baseValue
&& order
< units
.length
) {
616 size
= size
/ baseValue
;
620 let unit
= units
[order
], commaDigits
= 2;
626 return `${size.toFixed(commaDigits)} ${unit}B`;
629 render_upid: function(value
, metaData
, record
) {
630 let task
= record
.data
;
631 let type
= task
.type
|| task
.worker_type
;
632 let id
= task
.id
|| task
.worker_id
;
634 return Proxmox
.Utils
.format_task_description(type
, id
);
637 render_uptime: function(value
) {
640 if (uptime
=== undefined) {
648 return Proxmox
.Utils
.format_duration_long(uptime
);
651 systemd_unescape: function(string_value
) {
652 const charcode_0
= '0'.charCodeAt(0);
653 const charcode_9
= '9'.charCodeAt(0);
654 const charcode_A
= 'A'.charCodeAt(0);
655 const charcode_F
= 'F'.charCodeAt(0);
656 const charcode_a
= 'a'.charCodeAt(0);
657 const charcode_f
= 'f'.charCodeAt(0);
658 const charcode_x
= 'x'.charCodeAt(0);
659 const charcode_minus
= '-'.charCodeAt(0);
660 const charcode_slash
= '/'.charCodeAt(0);
661 const charcode_backslash
= '\\'.charCodeAt(0);
663 let parse_hex_digit = function(d
) {
664 if (d
>= charcode_0
&& d
<= charcode_9
) {
665 return d
- charcode_0
;
667 if (d
>= charcode_A
&& d
<= charcode_F
) {
668 return d
- charcode_A
+ 10;
670 if (d
>= charcode_a
&& d
<= charcode_f
) {
671 return d
- charcode_a
+ 10;
673 throw "got invalid hex digit";
676 let value
= new TextEncoder().encode(string_value
);
677 let result
= new Uint8Array(value
.length
);
682 while (i
< value
.length
) {
684 if (c0
=== charcode_minus
) {
685 result
.set([charcode_slash
], result_len
);
690 if ((i
+ 4) < value
.length
) {
692 if (c0
=== charcode_backslash
&& c1
=== charcode_x
) {
693 let h1
= parse_hex_digit(value
[i
+2]);
694 let h0
= parse_hex_digit(value
[i
+3]);
696 result
.set([ord
], result_len
);
702 result
.set([c0
], result_len
);
707 return new TextDecoder().decode(result
.slice(0, result
.len
));
710 parse_task_upid: function(upid
) {
713 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]+):$/);
715 throw "unable to parse upid '" + upid
+ "'";
718 task
.pid
= parseInt(res
[2], 16);
719 task
.pstart
= parseInt(res
[3], 16);
720 if (res
[5] !== undefined) {
721 task
.task_id
= parseInt(res
[5], 16);
723 task
.starttime
= parseInt(res
[6], 16);
725 task
.id
= Proxmox
.Utils
.systemd_unescape(res
[8]);
728 task
.desc
= Proxmox
.Utils
.format_task_description(task
.type
, task
.id
);
733 parse_task_status: function(status
) {
734 if (status
=== 'OK') {
738 if (status
=== 'unknown') {
742 let match
= status
.match(/^WARNINGS: (.*)$/);
750 format_task_status: function(status
) {
751 let parsed
= Proxmox
.Utils
.parse_task_status(status
);
753 case 'unknown': return Proxmox
.Utils
.unknownText
;
754 case 'error': return Proxmox
.Utils
.errorText
+ ': ' + status
;
755 case 'warning': return status
.replace('WARNINGS', Proxmox
.Utils
.warningsText
);
756 case 'ok': // fall-through
757 default: return status
;
761 render_duration: function(value
) {
762 if (value
=== undefined) {
765 return Proxmox
.Utils
.format_duration_human(value
);
768 render_timestamp: function(value
, metaData
, record
, rowIndex
, colIndex
, store
) {
769 let servertime
= new Date(value
* 1000);
770 return Ext
.Date
.format(servertime
, 'Y-m-d H:i:s');
773 render_zfs_health: function(value
) {
774 if (typeof value
=== 'undefined') {
777 var iconCls
= 'question-circle';
781 iconCls
= 'check-circle good';
785 iconCls
= 'exclamation-circle warning';
790 iconCls
= 'times-circle critical';
795 return '<i class="fa fa-' + iconCls
+ '"></i> ' + value
;
798 get_help_info: function(section
) {
800 if (typeof proxmoxOnlineHelpInfo
!== 'undefined') {
801 helpMap
= proxmoxOnlineHelpInfo
; // eslint-disable-line no-undef
802 } else if (typeof pveOnlineHelpInfo
!== 'undefined') {
803 // be backward compatible with older pve-doc-generators
804 helpMap
= pveOnlineHelpInfo
; // eslint-disable-line no-undef
806 throw "no global OnlineHelpInfo map declared";
809 if (helpMap
[section
]) {
810 return helpMap
[section
];
812 // try to normalize - and _ separators, to support asciidoc and sphinx
813 // references at the same time.
814 let section_minus_normalized
= section
.replace(/_
/g
, '-');
815 if (helpMap
[section_minus_normalized
]) {
816 return helpMap
[section_minus_normalized
];
818 let section_underscore_normalized
= section
.replace(/-/g
, '_');
819 return helpMap
[section_underscore_normalized
];
822 get_help_link: function(section
) {
823 let info
= Proxmox
.Utils
.get_help_info(section
);
827 return window
.location
.origin
+ info
.link
;
830 openXtermJsViewer: function(vmtype
, vmid
, nodename
, vmname
, cmd
) {
831 let url
= Ext
.Object
.toQueryString({
832 console
: vmtype
, // kvm, lxc, upgrade or shell
840 let nw
= window
.open("?" + url
, '_blank', 'toolbar=no,location=no,status=no,menubar=no,resizable=yes,width=800,height=420');
846 render_optional_url: function(value
) {
847 if (value
&& value
.match(/^https?:\/\//) !== null) {
848 return '<a target="_blank" href="' + value
+ '">' + value
+ '</a>';
853 render_san: function(value
) {
855 if (Ext
.isArray(value
)) {
856 value
.forEach(function(val
) {
857 if (!Ext
.isNumber(val
)) {
861 return names
.join('<br>');
866 render_usage
: val
=> (val
* 100).toFixed(2) + '%',
868 render_cpu_usage: function(val
, max
) {
869 return Ext
.String
.format(
870 `${gettext('{0}% of {1}')} ${gettext('CPU(s)')}`,
871 (val
*100).toFixed(2),
876 render_size_usage: function(val
, max
, useSI
) {
878 return gettext('N/A');
880 let fmt
= v
=> Proxmox
.Utils
.format_size(v
, useSI
);
881 let ratio
= (val
* 100 / max
).toFixed(2);
882 return ratio
+ '% (' + Ext
.String
.format(gettext('{0} of {1}'), fmt(val
), fmt(max
)) + ')';
885 render_cpu: function(value
, metaData
, record
, rowIndex
, colIndex
, store
) {
886 if (!(record
.data
.uptime
&& Ext
.isNumeric(value
))) {
890 let maxcpu
= record
.data
.maxcpu
|| 1;
891 if (!Ext
.isNumeric(maxcpu
) || maxcpu
< 1) {
894 let cpuText
= maxcpu
> 1 ? 'CPUs' : 'CPU';
895 let ratio
= (value
* 100).toFixed(1);
896 return `${ratio}% of ${maxcpu.toString()} ${cpuText}`;
899 render_size: function(value
, metaData
, record
, rowIndex
, colIndex
, store
) {
900 if (!Ext
.isNumeric(value
)) {
903 return Proxmox
.Utils
.format_size(value
);
906 render_cpu_model: function(cpu
) {
907 let socketText
= cpu
.sockets
> 1 ? gettext('Sockets') : gettext('Socket');
908 return `${cpu.cpus} x ${cpu.model} (${cpu.sockets.toString()} ${socketText})`;
911 /* this is different for nodes */
912 render_node_cpu_usage: function(value
, record
) {
913 return Proxmox
.Utils
.render_cpu_usage(value
, record
.cpus
);
916 render_node_size_usage: function(record
) {
917 return Proxmox
.Utils
.render_size_usage(record
.used
, record
.total
);
920 loadTextFromFile: function(file
, callback
, maxBytes
) {
921 let maxSize
= maxBytes
|| 8192;
922 if (file
.size
> maxSize
) {
923 Ext
.Msg
.alert(gettext('Error'), gettext("Invalid file size: ") + file
.size
);
926 let reader
= new FileReader();
927 reader
.onload
= evt
=> callback(evt
.target
.result
);
928 reader
.readAsText(file
);
931 parsePropertyString: function(value
, defaultKey
) {
935 if (typeof value
!== 'string' || value
=== '') {
939 Ext
.Array
.each(value
.split(','), function(p
) {
940 var kv
= p
.split('=', 2);
941 if (Ext
.isDefined(kv
[1])) {
943 } else if (Ext
.isDefined(defaultKey
)) {
944 if (Ext
.isDefined(res
[defaultKey
])) {
945 error
= 'defaultKey may be only defined once in propertyString';
946 return false; // break
948 res
[defaultKey
] = kv
[0];
950 error
= 'invalid propertyString, not a key=value pair and no defaultKey defined';
951 return false; // break
956 if (error
!== undefined) {
957 console
.error(error
);
964 printPropertyString: function(data
, defaultKey
) {
965 var stringparts
= [],
966 gotDefaultKeyVal
= false,
969 Ext
.Object
.each(data
, function(key
, value
) {
970 if (defaultKey
!== undefined && key
=== defaultKey
) {
971 gotDefaultKeyVal
= true;
972 defaultKeyVal
= value
;
973 } else if (Ext
.isArray(value
)) {
974 stringparts
.push(key
+ '=' + value
.join(';'));
975 } else if (value
!== '') {
976 stringparts
.push(key
+ '=' + value
);
980 stringparts
= stringparts
.sort();
981 if (gotDefaultKeyVal
) {
982 stringparts
.unshift(defaultKeyVal
);
985 return stringparts
.join(',');
990 parseACMEPluginData: function(data
) {
993 data
.split('\n').forEach((line
) => {
994 // capture everything after the first = as value
995 let [key
, value
] = line
.split('=');
996 if (value
!== undefined) {
999 extradata
.push(line
);
1002 return [res
, extradata
];
1005 delete_if_default: function(values
, fieldname
, default_val
, create
) {
1006 if (values
[fieldname
] === '' || values
[fieldname
] === default_val
) {
1008 if (values
.delete) {
1009 if (Ext
.isArray(values
.delete)) {
1010 values
.delete.push(fieldname
);
1012 values
.delete += ',' + fieldname
;
1015 values
.delete = fieldname
;
1019 delete values
[fieldname
];
1023 printACME: function(value
) {
1024 if (Ext
.isArray(value
.domains
)) {
1025 value
.domains
= value
.domains
.join(';');
1027 return Proxmox
.Utils
.printPropertyString(value
);
1030 parseACME: function(value
) {
1038 Ext
.Array
.each(value
.split(','), function(p
) {
1039 var kv
= p
.split('=', 2);
1040 if (Ext
.isDefined(kv
[1])) {
1043 error
= 'Failed to parse key-value pair: '+p
;
1049 if (error
!== undefined) {
1050 console
.error(error
);
1054 if (res
.domains
!== undefined) {
1055 res
.domains
= res
.domains
.split(/;/);
1061 add_domain_to_acme: function(acme
, domain
) {
1062 if (acme
.domains
=== undefined) {
1063 acme
.domains
= [domain
];
1065 acme
.domains
.push(domain
);
1066 acme
.domains
= acme
.domains
.filter((value
, index
, self
) => self
.indexOf(value
) === index
);
1071 remove_domain_from_acme: function(acme
, domain
) {
1072 if (acme
.domains
!== undefined) {
1073 acme
.domains
= acme
.domains
.filter(
1074 (value
, index
, self
) => self
.indexOf(value
) === index
&& value
!== domain
,
1080 updateColumns: function(container
) {
1081 let mode
= Ext
.state
.Manager
.get('summarycolumns') || 'auto';
1083 if (mode
!== 'auto') {
1084 factor
= parseInt(mode
, 10);
1085 if (Number
.isNaN(factor
)) {
1089 factor
= container
.getSize().width
< 1400 ? 1 : 2;
1092 if (container
.oldFactor
=== factor
) {
1096 let items
= container
.query('>'); // direct childs
1097 factor
= Math
.min(factor
, items
.length
);
1098 container
.oldFactor
= factor
;
1100 items
.forEach((item
) => {
1101 item
.columnWidth
= 1 / factor
;
1104 // we have to update the layout twice, since the first layout change
1105 // can trigger the scrollbar which reduces the amount of space left
1106 container
.updateLayout();
1107 container
.updateLayout();
1112 constructor: function() {
1114 Ext
.apply(me
, me
.utilities
);
1116 let IPV4_OCTET
= "(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])";
1117 let IPV4_REGEXP
= "(?:(?:" + IPV4_OCTET
+ "\\.){3}" + IPV4_OCTET
+ ")";
1118 let IPV6_H16
= "(?:[0-9a-fA-F]{1,4})";
1119 let IPV6_LS32
= "(?:(?:" + IPV6_H16
+ ":" + IPV6_H16
+ ")|" + IPV4_REGEXP
+ ")";
1120 let IPV4_CIDR_MASK
= "([0-9]{1,2})";
1121 let IPV6_CIDR_MASK
= "([0-9]{1,3})";
1124 me
.IP4_match
= new RegExp("^(?:" + IPV4_REGEXP
+ ")$");
1125 me
.IP4_cidr_match
= new RegExp("^(?:" + IPV4_REGEXP
+ ")/" + IPV4_CIDR_MASK
+ "$");
1127 /* eslint-disable no-useless-concat,no-multi-spaces */
1128 let IPV6_REGEXP
= "(?:" +
1129 "(?:(?:" + "(?:" + IPV6_H16
+ ":){6})" + IPV6_LS32
+ ")|" +
1130 "(?:(?:" + "::" + "(?:" + IPV6_H16
+ ":){5})" + IPV6_LS32
+ ")|" +
1131 "(?:(?:(?:" + IPV6_H16
+ ")?::" + "(?:" + IPV6_H16
+ ":){4})" + IPV6_LS32
+ ")|" +
1132 "(?:(?:(?:(?:" + IPV6_H16
+ ":){0,1}" + IPV6_H16
+ ")?::" + "(?:" + IPV6_H16
+ ":){3})" + IPV6_LS32
+ ")|" +
1133 "(?:(?:(?:(?:" + IPV6_H16
+ ":){0,2}" + IPV6_H16
+ ")?::" + "(?:" + IPV6_H16
+ ":){2})" + IPV6_LS32
+ ")|" +
1134 "(?:(?:(?:(?:" + IPV6_H16
+ ":){0,3}" + IPV6_H16
+ ")?::" + "(?:" + IPV6_H16
+ ":){1})" + IPV6_LS32
+ ")|" +
1135 "(?:(?:(?:(?:" + IPV6_H16
+ ":){0,4}" + IPV6_H16
+ ")?::" + ")" + IPV6_LS32
+ ")|" +
1136 "(?:(?:(?:(?:" + IPV6_H16
+ ":){0,5}" + IPV6_H16
+ ")?::" + ")" + IPV6_H16
+ ")|" +
1137 "(?:(?:(?:(?:" + IPV6_H16
+ ":){0,7}" + IPV6_H16
+ ")?::" + ")" + ")" +
1139 /* eslint-enable no-useless-concat,no-multi-spaces */
1141 me
.IP6_match
= new RegExp("^(?:" + IPV6_REGEXP
+ ")$");
1142 me
.IP6_cidr_match
= new RegExp("^(?:" + IPV6_REGEXP
+ ")/" + IPV6_CIDR_MASK
+ "$");
1143 me
.IP6_bracket_match
= new RegExp("^\\[(" + IPV6_REGEXP
+ ")\\]");
1145 me
.IP64_match
= new RegExp("^(?:" + IPV6_REGEXP
+ "|" + IPV4_REGEXP
+ ")$");
1146 me
.IP64_cidr_match
= new RegExp("^(?:" + IPV6_REGEXP
+ "/" + IPV6_CIDR_MASK
+ ")|(?:" + IPV4_REGEXP
+ "/" + IPV4_CIDR_MASK
+ ")$");
1148 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])?))";
1149 me
.DnsName_match
= new RegExp("^" + DnsName_REGEXP
+ "$");
1151 me
.HostPort_match
= new RegExp("^(" + IPV4_REGEXP
+ "|" + DnsName_REGEXP
+ ")(?::(\\d+))?$");
1152 me
.HostPortBrackets_match
= new RegExp("^\\[(" + IPV6_REGEXP
+ "|" + IPV4_REGEXP
+ "|" + DnsName_REGEXP
+ ")\\](?::(\\d+))?$");
1153 me
.IP6_dotnotation_match
= new RegExp("^(" + IPV6_REGEXP
+ ")(?:\\.(\\d+))?$");
1154 me
.Vlan_match
= /^vlan(\d+)/;
1155 me
.VlanInterface_match
= /(\w+)\.(\d+)/;
1159 Ext
.define('Proxmox.Async', {
1162 // Returns a Promise resolving to the result of an `API2Request` or rejecting to the error
1163 // repsonse on failure
1164 api2: function(reqOpts
) {
1165 return new Promise((resolve
, reject
) => {
1166 delete reqOpts
.callback
; // not allowed in this api
1167 reqOpts
.success
= response
=> resolve(response
);
1168 reqOpts
.failure
= response
=> reject(response
);
1169 Proxmox
.Utils
.API2Request(reqOpts
);
1173 // Delay for a number of milliseconds.
1174 sleep: function(millis
) {
1175 return new Promise((resolve
, _reject
) => setTimeout(resolve
, millis
));