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 // returns username + realm
242 parse_userid: function(userid
) {
243 if (!Ext
.isString(userid
)) {
244 return [undefined, undefined];
247 let match
= userid
.match(/^(.+)@([^@]+)$/);
248 if (match
!== null) {
249 return [match
[1], match
[2]];
252 return [undefined, undefined];
255 render_username: function(userid
) {
256 let username
= Proxmox
.Utils
.parse_userid(userid
)[0] || "";
257 return Ext
.htmlEncode(username
);
260 render_realm: function(userid
) {
261 let username
= Proxmox
.Utils
.parse_userid(userid
)[1] || "";
262 return Ext
.htmlEncode(username
);
265 getStoredAuth: function() {
266 let storedAuth
= JSON
.parse(window
.localStorage
.getItem('ProxmoxUser'));
267 return storedAuth
|| {};
270 setAuthData: function(data
) {
271 Proxmox
.UserName
= data
.username
;
272 Proxmox
.LoggedOut
= data
.LoggedOut
;
273 // creates a session cookie (expire = null)
274 // that way the cookie gets deleted after the browser window is closed
276 Proxmox
.CSRFPreventionToken
= data
.CSRFPreventionToken
;
277 Ext
.util
.Cookies
.set(Proxmox
.Setup
.auth_cookie_name
, data
.ticket
, null, '/', null, true);
281 window
.localStorage
.setItem('ProxmoxUser', JSON
.stringify(data
));
286 if (Proxmox
.LoggedOut
) {
289 let storedAuth
= Proxmox
.Utils
.getStoredAuth();
290 let cookie
= Ext
.util
.Cookies
.get(Proxmox
.Setup
.auth_cookie_name
);
291 if ((Proxmox
.UserName
!== '' && cookie
&& !cookie
.startsWith("PVE:tfa!")) || storedAuth
.token
) {
292 return cookie
|| storedAuth
.token
;
298 authClear: function() {
299 if (Proxmox
.LoggedOut
) {
302 Ext
.util
.Cookies
.clear(Proxmox
.Setup
.auth_cookie_name
);
303 window
.localStorage
.removeItem("ProxmoxUser");
306 // The End-User gets redirected back here after login on the OpenID auth. portal, and in the
307 // redirection URL the state and auth.code are passed as URL GET params, this helper parses those
308 getOpenIDRedirectionAuthorization: function() {
309 const auth
= Ext
.Object
.fromQueryString(window
.location
.search
);
310 if (auth
.state
!== undefined && auth
.code
!== undefined) {
316 // comp.setLoading() is buggy in ExtJS 4.0.7, so we
317 // use el.mask() instead
318 setErrorMask: function(comp
, msg
) {
325 } else if (msg
=== true) {
326 el
.mask(gettext("Loading..."));
332 getResponseErrorMessage
: (err
) => {
333 if (!err
.statusText
) {
334 return gettext('Connection error');
336 let msg
= [`${err.statusText} (${err.status})`];
337 if (err
.response
&& err
.response
.responseText
) {
338 let txt
= err
.response
.responseText
;
340 let res
= JSON
.parse(txt
);
341 if (res
.errors
&& typeof res
.errors
=== 'object') {
342 for (let [key
, value
] of Object
.entries(res
.errors
)) {
343 msg
.push(Ext
.String
.htmlEncode(`${key}: ${value}`));
347 // fallback to string
348 msg
.push(Ext
.String
.htmlEncode(txt
));
351 return msg
.join('<br>');
354 monStoreErrors: function(component
, store
, clearMaskBeforeLoad
, errorCallback
) {
355 if (clearMaskBeforeLoad
) {
356 component
.mon(store
, 'beforeload', function(s
, operation
, eOpts
) {
357 Proxmox
.Utils
.setErrorMask(component
, false);
360 component
.mon(store
, 'beforeload', function(s
, operation
, eOpts
) {
361 if (!component
.loadCount
) {
362 component
.loadCount
= 0; // make sure it is nucomponent.ic
363 Proxmox
.Utils
.setErrorMask(component
, true);
368 // only works with 'proxmox' proxy
369 component
.mon(store
.proxy
, 'afterload', function(proxy
, request
, success
) {
370 component
.loadCount
++;
373 Proxmox
.Utils
.setErrorMask(component
, false);
377 let error
= request
._operation
.getError();
378 let msg
= Proxmox
.Utils
.getResponseErrorMessage(error
);
379 if (!errorCallback
|| !errorCallback(error
, msg
)) {
380 Proxmox
.Utils
.setErrorMask(component
, msg
);
385 extractRequestError: function(result
, verbose
) {
386 let msg
= gettext('Successful');
388 if (!result
.success
) {
389 msg
= gettext("Unknown error");
390 if (result
.message
) {
391 msg
= result
.message
;
393 msg
+= ' (' + result
.status
+ ')';
396 if (verbose
&& Ext
.isObject(result
.errors
)) {
398 Ext
.Object
.each(result
.errors
, function(prop
, desc
) {
399 msg
+= "<br><b>" + Ext
.htmlEncode(prop
) + "</b>: " +
400 Ext
.htmlEncode(desc
);
409 API2Request: function(reqOpts
) {
410 let newopts
= Ext
.apply({
411 waitMsg
: gettext('Please wait...'),
414 if (!newopts
.url
.match(/^\/api2/)) {
415 newopts
.url
= '/api2/extjs' + newopts
.url
;
417 delete newopts
.callback
;
419 let createWrapper = function(successFn
, callbackFn
, failureFn
) {
421 success: function(response
, options
) {
422 if (options
.waitMsgTarget
) {
423 if (Proxmox
.Utils
.toolkit
=== 'touch') {
424 options
.waitMsgTarget
.setMasked(false);
426 options
.waitMsgTarget
.setLoading(false);
429 let result
= Ext
.decode(response
.responseText
);
430 response
.result
= result
;
431 if (!result
.success
) {
432 response
.htmlStatus
= Proxmox
.Utils
.extractRequestError(result
, true);
433 Ext
.callback(callbackFn
, options
.scope
, [options
, false, response
]);
434 Ext
.callback(failureFn
, options
.scope
, [response
, options
]);
437 Ext
.callback(callbackFn
, options
.scope
, [options
, true, response
]);
438 Ext
.callback(successFn
, options
.scope
, [response
, options
]);
440 failure: function(response
, options
) {
441 if (options
.waitMsgTarget
) {
442 if (Proxmox
.Utils
.toolkit
=== 'touch') {
443 options
.waitMsgTarget
.setMasked(false);
445 options
.waitMsgTarget
.setLoading(false);
448 response
.result
= {};
450 response
.result
= Ext
.decode(response
.responseText
);
454 let msg
= gettext('Connection error') + ' - server offline?';
455 if (response
.aborted
) {
456 msg
= gettext('Connection error') + ' - aborted.';
457 } else if (response
.timedout
) {
458 msg
= gettext('Connection error') + ' - Timeout.';
459 } else if (response
.status
&& response
.statusText
) {
460 msg
= gettext('Connection error') + ' ' + response
.status
+ ': ' + response
.statusText
;
462 response
.htmlStatus
= msg
;
463 Ext
.callback(callbackFn
, options
.scope
, [options
, false, response
]);
464 Ext
.callback(failureFn
, options
.scope
, [response
, options
]);
469 createWrapper(reqOpts
.success
, reqOpts
.callback
, reqOpts
.failure
);
471 let target
= newopts
.waitMsgTarget
;
473 if (Proxmox
.Utils
.toolkit
=== 'touch') {
474 target
.setMasked({ xtype
: 'loadmask', message
: newopts
.waitMsg
});
476 // Note: ExtJS bug - this does not work when component is not rendered
477 target
.setLoading(newopts
.waitMsg
);
480 Ext
.Ajax
.request(newopts
);
483 // can be useful for catching displaying errors from the API, e.g.:
484 // Proxmox.Async.api2({
486 // }).catch(Proxmox.Utils.alertResponseFailure);
487 alertResponseFailure
: (response
) => {
490 response
.htmlStatus
|| response
.result
.message
,
494 checked_command: function(orig_cmd
) {
495 Proxmox
.Utils
.API2Request(
497 url
: '/nodes/localhost/subscription',
499 failure: function(response
, opts
) {
500 Ext
.Msg
.alert(gettext('Error'), response
.htmlStatus
);
502 success: function(response
, opts
) {
503 let res
= response
.result
;
504 if (res
=== null || res
=== undefined || !res
|| res
505 .data
.status
.toLowerCase() !== 'active') {
507 title
: gettext('No valid subscription'),
508 icon
: Ext
.Msg
.WARNING
,
509 message
: Proxmox
.Utils
.getNoSubKeyHtml(res
.data
.url
),
511 callback: function(btn
) {
526 assemble_field_data: function(values
, data
) {
527 if (!Ext
.isObject(data
)) {
530 Ext
.Object
.each(data
, function(name
, val
) {
531 if (Object
.prototype.hasOwnProperty
.call(values
, name
)) {
532 let bucket
= values
[name
];
533 if (!Ext
.isArray(bucket
)) {
534 bucket
= values
[name
] = [bucket
];
536 if (Ext
.isArray(val
)) {
537 values
[name
] = bucket
.concat(val
);
547 updateColumnWidth: function(container
, thresholdWidth
) {
548 let mode
= Ext
.state
.Manager
.get('summarycolumns') || 'auto';
550 if (mode
!== 'auto') {
551 factor
= parseInt(mode
, 10);
552 if (Number
.isNaN(factor
)) {
556 thresholdWidth
= (thresholdWidth
|| 1400) + 1;
557 factor
= Math
.ceil(container
.getSize().width
/ thresholdWidth
);
560 if (container
.oldFactor
=== factor
) {
564 let items
= container
.query('>'); // direct childs
565 factor
= Math
.min(factor
, items
.length
);
566 container
.oldFactor
= factor
;
568 items
.forEach((item
) => {
569 item
.columnWidth
= 1 / factor
;
572 // we have to update the layout twice, since the first layout change
573 // can trigger the scrollbar which reduces the amount of space left
574 container
.updateLayout();
575 container
.updateLayout();
578 // NOTE: depreacated, use updateColumnWidth
579 updateColumns
: container
=> Proxmox
.Utils
.updateColumnWidth(container
),
581 dialog_title: function(subject
, create
, isAdd
) {
584 return gettext('Add') + ': ' + subject
;
586 return gettext('Create') + ': ' + subject
;
589 return gettext('Edit') + ': ' + subject
;
593 network_iface_types
: {
594 eth
: gettext("Network Device"),
595 bridge
: 'Linux Bridge',
598 OVSBridge
: 'OVS Bridge',
601 OVSIntPort
: 'OVS IntPort',
604 render_network_iface_type: function(value
) {
605 return Proxmox
.Utils
.network_iface_types
[value
] ||
606 Proxmox
.Utils
.unknownText
;
609 // NOTE: only add general, product agnostic, ones here! Else use override helper in product repos
611 aptupdate
: ['', gettext('Update package database')],
612 diskinit
: ['Disk', gettext('Initialize Disk with GPT')],
613 spiceshell
: ['', gettext('Shell') + ' (Spice)'],
614 srvreload
: ['SRV', gettext('Reload')],
615 srvrestart
: ['SRV', gettext('Restart')],
616 srvstart
: ['SRV', gettext('Start')],
617 srvstop
: ['SRV', gettext('Stop')],
618 termproxy
: ['', gettext('Console') + ' (xterm.js)'],
619 vncshell
: ['', gettext('Shell')],
622 // to add or change existing for product specific ones
623 override_task_descriptions: function(extra
) {
624 for (const [key
, value
] of Object
.entries(extra
)) {
625 Proxmox
.Utils
.task_desc_table
[key
] = value
;
629 format_task_description: function(type
, id
) {
630 let farray
= Proxmox
.Utils
.task_desc_table
[type
];
638 } else if (Ext
.isFunction(farray
)) {
639 return farray(type
, id
);
641 let prefix
= farray
[0];
643 if (prefix
&& id
!== undefined) {
644 return prefix
+ ' ' + id
+ ' - ' + text
;
649 format_size: function(size
, useSI
) {
650 let units
= ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'];
652 const baseValue
= useSI
? 1000 : 1024;
653 while (size
>= baseValue
&& order
< units
.length
) {
654 size
= size
/ baseValue
;
658 let unit
= units
[order
], commaDigits
= 2;
664 return `${size.toFixed(commaDigits)} ${unit}B`;
667 render_upid: function(value
, metaData
, record
) {
668 let task
= record
.data
;
669 let type
= task
.type
|| task
.worker_type
;
670 let id
= task
.id
|| task
.worker_id
;
672 return Proxmox
.Utils
.format_task_description(type
, id
);
675 render_uptime: function(value
) {
678 if (uptime
=== undefined) {
686 return Proxmox
.Utils
.format_duration_long(uptime
);
689 systemd_unescape: function(string_value
) {
690 const charcode_0
= '0'.charCodeAt(0);
691 const charcode_9
= '9'.charCodeAt(0);
692 const charcode_A
= 'A'.charCodeAt(0);
693 const charcode_F
= 'F'.charCodeAt(0);
694 const charcode_a
= 'a'.charCodeAt(0);
695 const charcode_f
= 'f'.charCodeAt(0);
696 const charcode_x
= 'x'.charCodeAt(0);
697 const charcode_minus
= '-'.charCodeAt(0);
698 const charcode_slash
= '/'.charCodeAt(0);
699 const charcode_backslash
= '\\'.charCodeAt(0);
701 let parse_hex_digit = function(d
) {
702 if (d
>= charcode_0
&& d
<= charcode_9
) {
703 return d
- charcode_0
;
705 if (d
>= charcode_A
&& d
<= charcode_F
) {
706 return d
- charcode_A
+ 10;
708 if (d
>= charcode_a
&& d
<= charcode_f
) {
709 return d
- charcode_a
+ 10;
711 throw "got invalid hex digit";
714 let value
= new TextEncoder().encode(string_value
);
715 let result
= new Uint8Array(value
.length
);
720 while (i
< value
.length
) {
722 if (c0
=== charcode_minus
) {
723 result
.set([charcode_slash
], result_len
);
728 if ((i
+ 4) < value
.length
) {
730 if (c0
=== charcode_backslash
&& c1
=== charcode_x
) {
731 let h1
= parse_hex_digit(value
[i
+2]);
732 let h0
= parse_hex_digit(value
[i
+3]);
734 result
.set([ord
], result_len
);
740 result
.set([c0
], result_len
);
745 return new TextDecoder().decode(result
.slice(0, result
.len
));
748 parse_task_upid: function(upid
) {
751 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]+):$/);
753 throw "unable to parse upid '" + upid
+ "'";
756 task
.pid
= parseInt(res
[2], 16);
757 task
.pstart
= parseInt(res
[3], 16);
758 if (res
[5] !== undefined) {
759 task
.task_id
= parseInt(res
[5], 16);
761 task
.starttime
= parseInt(res
[6], 16);
763 task
.id
= Proxmox
.Utils
.systemd_unescape(res
[8]);
766 task
.desc
= Proxmox
.Utils
.format_task_description(task
.type
, task
.id
);
771 parse_task_status: function(status
) {
772 if (status
=== 'OK') {
776 if (status
=== 'unknown') {
780 let match
= status
.match(/^WARNINGS: (.*)$/);
788 format_task_status: function(status
) {
789 let parsed
= Proxmox
.Utils
.parse_task_status(status
);
791 case 'unknown': return Proxmox
.Utils
.unknownText
;
792 case 'error': return Proxmox
.Utils
.errorText
+ ': ' + status
;
793 case 'warning': return status
.replace('WARNINGS', Proxmox
.Utils
.warningsText
);
794 case 'ok': // fall-through
795 default: return status
;
799 render_duration: function(value
) {
800 if (value
=== undefined) {
803 return Proxmox
.Utils
.format_duration_human(value
);
806 render_timestamp: function(value
, metaData
, record
, rowIndex
, colIndex
, store
) {
807 let servertime
= new Date(value
* 1000);
808 return Ext
.Date
.format(servertime
, 'Y-m-d H:i:s');
811 render_zfs_health: function(value
) {
812 if (typeof value
=== 'undefined') {
815 var iconCls
= 'question-circle';
819 iconCls
= 'check-circle good';
823 iconCls
= 'exclamation-circle warning';
828 iconCls
= 'times-circle critical';
833 return '<i class="fa fa-' + iconCls
+ '"></i> ' + value
;
836 get_help_info: function(section
) {
838 if (typeof proxmoxOnlineHelpInfo
!== 'undefined') {
839 helpMap
= proxmoxOnlineHelpInfo
; // eslint-disable-line no-undef
840 } else if (typeof pveOnlineHelpInfo
!== 'undefined') {
841 // be backward compatible with older pve-doc-generators
842 helpMap
= pveOnlineHelpInfo
; // eslint-disable-line no-undef
844 throw "no global OnlineHelpInfo map declared";
847 if (helpMap
[section
]) {
848 return helpMap
[section
];
850 // try to normalize - and _ separators, to support asciidoc and sphinx
851 // references at the same time.
852 let section_minus_normalized
= section
.replace(/_
/g
, '-');
853 if (helpMap
[section_minus_normalized
]) {
854 return helpMap
[section_minus_normalized
];
856 let section_underscore_normalized
= section
.replace(/-/g
, '_');
857 return helpMap
[section_underscore_normalized
];
860 get_help_link: function(section
) {
861 let info
= Proxmox
.Utils
.get_help_info(section
);
865 return window
.location
.origin
+ info
.link
;
868 openXtermJsViewer: function(vmtype
, vmid
, nodename
, vmname
, cmd
) {
869 let url
= Ext
.Object
.toQueryString({
870 console
: vmtype
, // kvm, lxc, upgrade or shell
878 let nw
= window
.open("?" + url
, '_blank', 'toolbar=no,location=no,status=no,menubar=no,resizable=yes,width=800,height=420');
884 render_optional_url: function(value
) {
885 if (value
&& value
.match(/^https?:\/\//) !== null) {
886 return '<a target="_blank" href="' + value
+ '">' + value
+ '</a>';
891 render_san: function(value
) {
893 if (Ext
.isArray(value
)) {
894 value
.forEach(function(val
) {
895 if (!Ext
.isNumber(val
)) {
899 return names
.join('<br>');
904 render_usage
: val
=> (val
* 100).toFixed(2) + '%',
906 render_cpu_usage: function(val
, max
) {
907 return Ext
.String
.format(
908 `${gettext('{0}% of {1}')} ${gettext('CPU(s)')}`,
909 (val
*100).toFixed(2),
914 render_size_usage: function(val
, max
, useSI
) {
916 return gettext('N/A');
918 let fmt
= v
=> Proxmox
.Utils
.format_size(v
, useSI
);
919 let ratio
= (val
* 100 / max
).toFixed(2);
920 return ratio
+ '% (' + Ext
.String
.format(gettext('{0} of {1}'), fmt(val
), fmt(max
)) + ')';
923 render_cpu: function(value
, metaData
, record
, rowIndex
, colIndex
, store
) {
924 if (!(record
.data
.uptime
&& Ext
.isNumeric(value
))) {
928 let maxcpu
= record
.data
.maxcpu
|| 1;
929 if (!Ext
.isNumeric(maxcpu
) || maxcpu
< 1) {
932 let cpuText
= maxcpu
> 1 ? 'CPUs' : 'CPU';
933 let ratio
= (value
* 100).toFixed(1);
934 return `${ratio}% of ${maxcpu.toString()} ${cpuText}`;
937 render_size: function(value
, metaData
, record
, rowIndex
, colIndex
, store
) {
938 if (!Ext
.isNumeric(value
)) {
941 return Proxmox
.Utils
.format_size(value
);
944 render_cpu_model: function(cpu
) {
945 let socketText
= cpu
.sockets
> 1 ? gettext('Sockets') : gettext('Socket');
946 return `${cpu.cpus} x ${cpu.model} (${cpu.sockets.toString()} ${socketText})`;
949 /* this is different for nodes */
950 render_node_cpu_usage: function(value
, record
) {
951 return Proxmox
.Utils
.render_cpu_usage(value
, record
.cpus
);
954 render_node_size_usage: function(record
) {
955 return Proxmox
.Utils
.render_size_usage(record
.used
, record
.total
);
958 loadTextFromFile: function(file
, callback
, maxBytes
) {
959 let maxSize
= maxBytes
|| 8192;
960 if (file
.size
> maxSize
) {
961 Ext
.Msg
.alert(gettext('Error'), gettext("Invalid file size: ") + file
.size
);
964 let reader
= new FileReader();
965 reader
.onload
= evt
=> callback(evt
.target
.result
);
966 reader
.readAsText(file
);
969 parsePropertyString: function(value
, defaultKey
) {
973 if (typeof value
!== 'string' || value
=== '') {
977 Ext
.Array
.each(value
.split(','), function(p
) {
978 var kv
= p
.split('=', 2);
979 if (Ext
.isDefined(kv
[1])) {
981 } else if (Ext
.isDefined(defaultKey
)) {
982 if (Ext
.isDefined(res
[defaultKey
])) {
983 error
= 'defaultKey may be only defined once in propertyString';
984 return false; // break
986 res
[defaultKey
] = kv
[0];
988 error
= 'invalid propertyString, not a key=value pair and no defaultKey defined';
989 return false; // break
994 if (error
!== undefined) {
995 console
.error(error
);
1002 printPropertyString: function(data
, defaultKey
) {
1003 var stringparts
= [],
1004 gotDefaultKeyVal
= false,
1007 Ext
.Object
.each(data
, function(key
, value
) {
1008 if (defaultKey
!== undefined && key
=== defaultKey
) {
1009 gotDefaultKeyVal
= true;
1010 defaultKeyVal
= value
;
1011 } else if (Ext
.isArray(value
)) {
1012 stringparts
.push(key
+ '=' + value
.join(';'));
1013 } else if (value
!== '') {
1014 stringparts
.push(key
+ '=' + value
);
1018 stringparts
= stringparts
.sort();
1019 if (gotDefaultKeyVal
) {
1020 stringparts
.unshift(defaultKeyVal
);
1023 return stringparts
.join(',');
1026 acmedomain_count
: 5,
1028 parseACMEPluginData: function(data
) {
1031 data
.split('\n').forEach((line
) => {
1032 // capture everything after the first = as value
1033 let [key
, value
] = line
.split('=');
1034 if (value
!== undefined) {
1037 extradata
.push(line
);
1040 return [res
, extradata
];
1043 delete_if_default: function(values
, fieldname
, default_val
, create
) {
1044 if (values
[fieldname
] === '' || values
[fieldname
] === default_val
) {
1046 if (values
.delete) {
1047 if (Ext
.isArray(values
.delete)) {
1048 values
.delete.push(fieldname
);
1050 values
.delete += ',' + fieldname
;
1053 values
.delete = fieldname
;
1057 delete values
[fieldname
];
1061 printACME: function(value
) {
1062 if (Ext
.isArray(value
.domains
)) {
1063 value
.domains
= value
.domains
.join(';');
1065 return Proxmox
.Utils
.printPropertyString(value
);
1068 parseACME: function(value
) {
1076 Ext
.Array
.each(value
.split(','), function(p
) {
1077 var kv
= p
.split('=', 2);
1078 if (Ext
.isDefined(kv
[1])) {
1081 error
= 'Failed to parse key-value pair: '+p
;
1087 if (error
!== undefined) {
1088 console
.error(error
);
1092 if (res
.domains
!== undefined) {
1093 res
.domains
= res
.domains
.split(/;/);
1099 add_domain_to_acme: function(acme
, domain
) {
1100 if (acme
.domains
=== undefined) {
1101 acme
.domains
= [domain
];
1103 acme
.domains
.push(domain
);
1104 acme
.domains
= acme
.domains
.filter((value
, index
, self
) => self
.indexOf(value
) === index
);
1109 remove_domain_from_acme: function(acme
, domain
) {
1110 if (acme
.domains
!== undefined) {
1111 acme
.domains
= acme
.domains
.filter(
1112 (value
, index
, self
) => self
.indexOf(value
) === index
&& value
!== domain
,
1118 get_health_icon: function(state
, circle
) {
1119 if (circle
=== undefined) {
1123 if (state
=== undefined) {
1127 var icon
= 'faded fa-question';
1130 icon
= 'good fa-check';
1133 icon
= 'warning fa-upload';
1136 icon
= 'warning fa-refresh';
1139 icon
= 'warning fa-exclamation';
1142 icon
= 'critical fa-times';
1154 formatNodeRepoStatus: function(status
, product
) {
1155 let fmt
= (txt
, cls
) => `<i class="fa fa-fw fa-lg fa-${cls}"></i>${txt}`;
1157 let getUpdates
= Ext
.String
.format(gettext('{0} updates'), product
);
1158 let noRepo
= Ext
.String
.format(gettext('No {0} repository enabled!'), product
);
1160 if (status
=== 'ok') {
1161 return fmt(getUpdates
, 'check-circle good') + ' ' +
1162 fmt(gettext('Production-ready Enterprise repository enabled'), 'check-circle good');
1163 } else if (status
=== 'no-sub') {
1164 return fmt(gettext('Production-ready Enterprise repository enabled'), 'check-circle good') + ' ' +
1165 fmt(gettext('Enterprise repository needs valid subscription'), 'exclamation-circle warning');
1166 } else if (status
=== 'non-production') {
1167 return fmt(getUpdates
, 'check-circle good') + ' ' +
1168 fmt(gettext('Non production-ready repository enabled!'), 'exclamation-circle warning');
1169 } else if (status
=== 'no-repo') {
1170 return fmt(noRepo
, 'exclamation-circle critical');
1173 return Proxmox
.Utils
.unknownText
;
1176 render_u2f_error: function(error
) {
1178 '1': gettext('Other Error'),
1179 '2': gettext('Bad Request'),
1180 '3': gettext('Configuration Unsupported'),
1181 '4': gettext('Device Ineligible'),
1182 '5': gettext('Timeout'),
1184 return "U2F Error: " + ErrorNames
[error
] || Proxmox
.Utils
.unknownText
;
1187 // Convert an ArrayBuffer to a base64url encoded string.
1188 // A `null` value will be preserved for convenience.
1189 bytes_to_base64url: function(bytes
) {
1190 if (bytes
=== null) {
1195 .from(new Uint8Array(bytes
))
1196 .map(val
=> String
.fromCharCode(val
))
1199 .replace(/\+/g, '-')
1200 .replace(/\//g, '_')
1201 .replace(/[=]/g, '');
1204 // Convert an a base64url string to an ArrayBuffer.
1205 // A `null` value will be preserved for convenience.
1206 base64url_to_bytes: function(b64u
) {
1207 if (b64u
=== null) {
1211 return new Uint8Array(
1214 .replace(/_/g, '/'),
1217 .map(val => val.charCodeAt(0)),
1223 constructor: function() {
1225 Ext.apply(me, me.utilities);
1227 let IPV4_OCTET = "(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])";
1228 let IPV4_REGEXP = "(?:(?:" + IPV4_OCTET + "\\.){3}" + IPV4_OCTET + ")";
1229 let IPV6_H16 = "(?:[0-9a-fA-F]{1,4})";
1230 let IPV6_LS32 = "(?:(?:" + IPV6_H16 + ":" + IPV6_H16 + ")|" + IPV4_REGEXP + ")";
1231 let IPV4_CIDR_MASK = "([0-9]{1,2})";
1232 let IPV6_CIDR_MASK = "([0-9]{1,3})";
1235 me.IP4_match = new RegExp("^(?:" + IPV4_REGEXP + ")$");
1236 me.IP4_cidr_match = new RegExp("^(?:" + IPV4_REGEXP + ")/" + IPV4_CIDR_MASK + "$");
1238 /* eslint-disable no-useless-concat,no-multi-spaces */
1239 let IPV6_REGEXP = "(?:" +
1240 "(?:(?:" + "(?:" + IPV6_H16 + ":){6})" + IPV6_LS32 + ")|" +
1241 "(?:(?:" + "::" + "(?:" + IPV6_H16 + ":){5})" + IPV6_LS32 + ")|" +
1242 "(?:(?:(?:" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){4})" + IPV6_LS32 + ")|" +
1243 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,1}" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){3})" + IPV6_LS32 + ")|" +
1244 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,2}" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){2})" + IPV6_LS32 + ")|" +
1245 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,3}" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){1})" + IPV6_LS32 + ")|" +
1246 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,4}" + IPV6_H16 + ")?::" + ")" + IPV6_LS32 + ")|" +
1247 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,5}" + IPV6_H16 + ")?::" + ")" + IPV6_H16 + ")|" +
1248 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,7}" + IPV6_H16 + ")?::" + ")" + ")" +
1250 /* eslint-enable no-useless-concat,no-multi-spaces */
1252 me.IP6_match = new RegExp("^(?:" + IPV6_REGEXP + ")$");
1253 me.IP6_cidr_match = new RegExp("^(?:" + IPV6_REGEXP + ")/" + IPV6_CIDR_MASK + "$");
1254 me.IP6_bracket_match = new RegExp("^\\[(" + IPV6_REGEXP + ")\\]");
1256 me.IP64_match = new RegExp("^(?:" + IPV6_REGEXP + "|" + IPV4_REGEXP + ")$");
1257 me.IP64_cidr_match = new RegExp("^(?:" + IPV6_REGEXP + "/" + IPV6_CIDR_MASK + ")|(?:" + IPV4_REGEXP + "/" + IPV4_CIDR_MASK + ")$");
1259 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])?))";
1260 me.DnsName_match = new RegExp("^" + DnsName_REGEXP + "$");
1261 me.DnsName_or_Wildcard_match = new RegExp("^(?:\\*\\.)?" + DnsName_REGEXP + "$");
1263 me.HostPort_match = new RegExp("^(" + IPV4_REGEXP + "|" + DnsName_REGEXP + ")(?::(\\d+))?$");
1264 me.HostPortBrackets_match = new RegExp("^\\[(" + IPV6_REGEXP + "|" + IPV4_REGEXP + "|" + DnsName_REGEXP + ")\\](?::(\\d+))?$");
1265 me.IP6_dotnotation_match = new RegExp("^(" + IPV6_REGEXP + ")(?:\\.(\\d+))?$");
1266 me.Vlan_match = /^vlan(\d+)/;
1267 me.VlanInterface_match = /(\w+)\.(\d+)/;
1271 Ext.define('Proxmox
.Async
', {
1274 // Returns a Promise resolving to the result of an `API2Request` or rejecting to the error
1275 // repsonse on failure
1276 api2: function(reqOpts) {
1277 return new Promise((resolve, reject) => {
1278 delete reqOpts.callback; // not allowed in this api
1279 reqOpts.success = response => resolve(response);
1280 reqOpts.failure = response => reject(response);
1281 Proxmox.Utils.API2Request(reqOpts);
1285 // Delay for a number of milliseconds.
1286 sleep: function(millis) {
1287 return new Promise((resolve, _reject) => setTimeout(resolve, millis));