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
) {
93 if (!value
|| value
=== '__default__') {
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, years
= 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);
174 days
= remaining
% 365;
175 remaining
= Math
.trunc(remaining
/ 365); // yea, just lets ignore leap years...
184 let add
= (t
, unit
) => {
185 if (t
> 0) res
.push(t
+ unit
);
189 let addMinutes
= !add(years
, 'y');
190 let addSeconds
= !add(days
, 'd');
198 return res
.join(' ');
201 format_duration_long: function(ut
) {
202 let days
= Math
.floor(ut
/ 86400);
204 let hours
= Math
.floor(ut
/ 3600);
206 let mins
= Math
.floor(ut
/ 60);
209 let hours_str
= '00' + hours
.toString();
210 hours_str
= hours_str
.substr(hours_str
.length
- 2);
211 let mins_str
= "00" + mins
.toString();
212 mins_str
= mins_str
.substr(mins_str
.length
- 2);
213 let ut_str
= "00" + ut
.toString();
214 ut_str
= ut_str
.substr(ut_str
.length
- 2);
217 let ds
= days
> 1 ? Proxmox
.Utils
.daysText
: Proxmox
.Utils
.dayText
;
218 return days
.toString() + ' ' + ds
+ ' ' +
219 hours_str
+ ':' + mins_str
+ ':' + ut_str
;
221 return hours_str
+ ':' + mins_str
+ ':' + ut_str
;
225 format_subscription_level: function(level
) {
228 } else if (level
=== 'b') {
230 } else if (level
=== 's') {
232 } else if (level
=== 'p') {
235 return Proxmox
.Utils
.noneText
;
239 compute_min_label_width: function(text
, width
) {
240 if (width
=== undefined) { width
= 100; }
242 let tm
= new Ext
.util
.TextMetrics();
243 let min
= tm
.getWidth(text
+ ':');
245 return min
< width
? width
: min
;
248 // returns username + realm
249 parse_userid: function(userid
) {
250 if (!Ext
.isString(userid
)) {
251 return [undefined, undefined];
254 let match
= userid
.match(/^(.+)@([^@]+)$/);
255 if (match
!== null) {
256 return [match
[1], match
[2]];
259 return [undefined, undefined];
262 render_username: function(userid
) {
263 let username
= Proxmox
.Utils
.parse_userid(userid
)[0] || "";
264 return Ext
.htmlEncode(username
);
267 render_realm: function(userid
) {
268 let username
= Proxmox
.Utils
.parse_userid(userid
)[1] || "";
269 return Ext
.htmlEncode(username
);
272 getStoredAuth: function() {
273 let storedAuth
= JSON
.parse(window
.localStorage
.getItem('ProxmoxUser'));
274 return storedAuth
|| {};
277 setAuthData: function(data
) {
278 Proxmox
.UserName
= data
.username
;
279 Proxmox
.LoggedOut
= data
.LoggedOut
;
280 // creates a session cookie (expire = null)
281 // that way the cookie gets deleted after the browser window is closed
283 Proxmox
.CSRFPreventionToken
= data
.CSRFPreventionToken
;
284 Ext
.util
.Cookies
.set(Proxmox
.Setup
.auth_cookie_name
, data
.ticket
, null, '/', null, true);
288 window
.localStorage
.setItem('ProxmoxUser', JSON
.stringify(data
));
293 if (Proxmox
.LoggedOut
) {
296 let storedAuth
= Proxmox
.Utils
.getStoredAuth();
297 let cookie
= Ext
.util
.Cookies
.get(Proxmox
.Setup
.auth_cookie_name
);
298 if ((Proxmox
.UserName
!== '' && cookie
&& !cookie
.startsWith("PVE:tfa!")) || storedAuth
.token
) {
299 return cookie
|| storedAuth
.token
;
305 authClear: function() {
306 if (Proxmox
.LoggedOut
) {
309 // ExtJS clear is basically the same, but browser may complain if any cookie isn't "secure"
310 Ext
.util
.Cookies
.set(Proxmox
.Setup
.auth_cookie_name
, "", new Date(0), null, null, true);
311 window
.localStorage
.removeItem("ProxmoxUser");
314 // The End-User gets redirected back here after login on the OpenID auth. portal, and in the
315 // redirection URL the state and auth.code are passed as URL GET params, this helper parses those
316 getOpenIDRedirectionAuthorization: function() {
317 const auth
= Ext
.Object
.fromQueryString(window
.location
.search
);
318 if (auth
.state
!== undefined && auth
.code
!== undefined) {
324 // comp.setLoading() is buggy in ExtJS 4.0.7, so we
325 // use el.mask() instead
326 setErrorMask: function(comp
, msg
) {
333 } else if (msg
=== true) {
334 el
.mask(gettext("Loading..."));
340 getResponseErrorMessage
: (err
) => {
341 if (!err
.statusText
) {
342 return gettext('Connection error');
344 let msg
= [`${err.statusText} (${err.status})`];
345 if (err
.response
&& err
.response
.responseText
) {
346 let txt
= err
.response
.responseText
;
348 let res
= JSON
.parse(txt
);
349 if (res
.errors
&& typeof res
.errors
=== 'object') {
350 for (let [key
, value
] of Object
.entries(res
.errors
)) {
351 msg
.push(Ext
.String
.htmlEncode(`${key}: ${value}`));
355 // fallback to string
356 msg
.push(Ext
.String
.htmlEncode(txt
));
359 return msg
.join('<br>');
362 monStoreErrors: function(component
, store
, clearMaskBeforeLoad
, errorCallback
) {
363 if (clearMaskBeforeLoad
) {
364 component
.mon(store
, 'beforeload', function(s
, operation
, eOpts
) {
365 Proxmox
.Utils
.setErrorMask(component
, false);
368 component
.mon(store
, 'beforeload', function(s
, operation
, eOpts
) {
369 if (!component
.loadCount
) {
370 component
.loadCount
= 0; // make sure it is nucomponent.ic
371 Proxmox
.Utils
.setErrorMask(component
, true);
376 // only works with 'proxmox' proxy
377 component
.mon(store
.proxy
, 'afterload', function(proxy
, request
, success
) {
378 component
.loadCount
++;
381 Proxmox
.Utils
.setErrorMask(component
, false);
385 let error
= request
._operation
.getError();
386 let msg
= Proxmox
.Utils
.getResponseErrorMessage(error
);
387 if (!errorCallback
|| !errorCallback(error
, msg
)) {
388 Proxmox
.Utils
.setErrorMask(component
, msg
);
393 extractRequestError: function(result
, verbose
) {
394 let msg
= gettext('Successful');
396 if (!result
.success
) {
397 msg
= gettext("Unknown error");
398 if (result
.message
) {
399 msg
= Ext
.htmlEncode(result
.message
);
401 msg
+= ` (${result.status})`;
404 if (verbose
&& Ext
.isObject(result
.errors
)) {
406 Ext
.Object
.each(result
.errors
, (prop
, desc
) => {
407 msg
+= `<br><b>${Ext.htmlEncode(prop)}</b>: ${Ext.htmlEncode(desc)}`;
416 API2Request: function(reqOpts
) {
417 let newopts
= Ext
.apply({
418 waitMsg
: gettext('Please wait...'),
421 // default to enable if user isn't handling the failure already explicitly
422 let autoErrorAlert
= reqOpts
.autoErrorAlert
??
423 (typeof reqOpts
.failure
!== 'function' && typeof reqOpts
.callback
!== 'function');
425 if (!newopts
.url
.match(/^\/api2/)) {
426 newopts
.url
= '/api2/extjs' + newopts
.url
;
428 delete newopts
.callback
;
430 let createWrapper = function(successFn
, callbackFn
, failureFn
) {
432 success: function(response
, options
) {
433 if (options
.waitMsgTarget
) {
434 if (Proxmox
.Utils
.toolkit
=== 'touch') {
435 options
.waitMsgTarget
.setMasked(false);
437 options
.waitMsgTarget
.setLoading(false);
440 let result
= Ext
.decode(response
.responseText
);
441 response
.result
= result
;
442 if (!result
.success
) {
443 response
.htmlStatus
= Proxmox
.Utils
.extractRequestError(result
, true);
444 Ext
.callback(callbackFn
, options
.scope
, [options
, false, response
]);
445 Ext
.callback(failureFn
, options
.scope
, [response
, options
]);
446 if (autoErrorAlert
) {
447 Ext
.Msg
.alert(gettext('Error'), response
.htmlStatus
);
451 Ext
.callback(callbackFn
, options
.scope
, [options
, true, response
]);
452 Ext
.callback(successFn
, options
.scope
, [response
, options
]);
454 failure: function(response
, options
) {
455 if (options
.waitMsgTarget
) {
456 if (Proxmox
.Utils
.toolkit
=== 'touch') {
457 options
.waitMsgTarget
.setMasked(false);
459 options
.waitMsgTarget
.setLoading(false);
462 response
.result
= {};
464 response
.result
= Ext
.decode(response
.responseText
);
468 let msg
= gettext('Connection error') + ' - server offline?';
469 if (response
.aborted
) {
470 msg
= gettext('Connection error') + ' - aborted.';
471 } else if (response
.timedout
) {
472 msg
= gettext('Connection error') + ' - Timeout.';
473 } else if (response
.status
&& response
.statusText
) {
474 msg
= gettext('Connection error') + ' ' + response
.status
+ ': ' + response
.statusText
;
476 response
.htmlStatus
= msg
;
477 Ext
.callback(callbackFn
, options
.scope
, [options
, false, response
]);
478 Ext
.callback(failureFn
, options
.scope
, [response
, options
]);
483 createWrapper(reqOpts
.success
, reqOpts
.callback
, reqOpts
.failure
);
485 let target
= newopts
.waitMsgTarget
;
487 if (Proxmox
.Utils
.toolkit
=== 'touch') {
488 target
.setMasked({ xtype
: 'loadmask', message
: newopts
.waitMsg
});
490 // Note: ExtJS bug - this does not work when component is not rendered
491 target
.setLoading(newopts
.waitMsg
);
494 Ext
.Ajax
.request(newopts
);
497 // can be useful for catching displaying errors from the API, e.g.:
498 // Proxmox.Async.api2({
500 // }).catch(Proxmox.Utils.alertResponseFailure);
501 alertResponseFailure
: (response
) => {
504 response
.htmlStatus
|| response
.result
.message
,
508 checked_command: function(orig_cmd
) {
509 Proxmox
.Utils
.API2Request(
511 url
: '/nodes/localhost/subscription',
513 failure: function(response
, opts
) {
514 Ext
.Msg
.alert(gettext('Error'), response
.htmlStatus
);
516 success: function(response
, opts
) {
517 let res
= response
.result
;
518 if (res
=== null || res
=== undefined || !res
|| res
519 .data
.status
.toLowerCase() !== 'active') {
521 title
: gettext('No valid subscription'),
522 icon
: Ext
.Msg
.WARNING
,
523 message
: Proxmox
.Utils
.getNoSubKeyHtml(res
.data
.url
),
525 callback: function(btn
) {
540 assemble_field_data: function(values
, data
) {
541 if (!Ext
.isObject(data
)) {
544 Ext
.Object
.each(data
, function(name
, val
) {
545 if (Object
.prototype.hasOwnProperty
.call(values
, name
)) {
546 let bucket
= values
[name
];
547 if (!Ext
.isArray(bucket
)) {
548 bucket
= values
[name
] = [bucket
];
550 if (Ext
.isArray(val
)) {
551 values
[name
] = bucket
.concat(val
);
561 updateColumnWidth: function(container
, thresholdWidth
) {
562 let mode
= Ext
.state
.Manager
.get('summarycolumns') || 'auto';
564 if (mode
!== 'auto') {
565 factor
= parseInt(mode
, 10);
566 if (Number
.isNaN(factor
)) {
570 thresholdWidth
= (thresholdWidth
|| 1400) + 1;
571 factor
= Math
.ceil(container
.getSize().width
/ thresholdWidth
);
574 if (container
.oldFactor
=== factor
) {
578 let items
= container
.query('>'); // direct children
579 factor
= Math
.min(factor
, items
.length
);
580 container
.oldFactor
= factor
;
582 items
.forEach((item
) => {
583 item
.columnWidth
= 1 / factor
;
586 // we have to update the layout twice, since the first layout change
587 // can trigger the scrollbar which reduces the amount of space left
588 container
.updateLayout();
589 container
.updateLayout();
592 // NOTE: depreacated, use updateColumnWidth
593 updateColumns
: container
=> Proxmox
.Utils
.updateColumnWidth(container
),
595 dialog_title: function(subject
, create
, isAdd
) {
598 return gettext('Add') + ': ' + subject
;
600 return gettext('Create') + ': ' + subject
;
603 return gettext('Edit') + ': ' + subject
;
607 network_iface_types
: {
608 eth
: gettext("Network Device"),
609 bridge
: 'Linux Bridge',
612 OVSBridge
: 'OVS Bridge',
615 OVSIntPort
: 'OVS IntPort',
618 render_network_iface_type: function(value
) {
619 return Proxmox
.Utils
.network_iface_types
[value
] ||
620 Proxmox
.Utils
.unknownText
;
623 // NOTE: only add general, product agnostic, ones here! Else use override helper in product repos
625 aptupdate
: ['', gettext('Update package database')],
626 diskinit
: ['Disk', gettext('Initialize Disk with GPT')],
627 spiceshell
: ['', gettext('Shell') + ' (Spice)'],
628 srvreload
: ['SRV', gettext('Reload')],
629 srvrestart
: ['SRV', gettext('Restart')],
630 srvstart
: ['SRV', gettext('Start')],
631 srvstop
: ['SRV', gettext('Stop')],
632 termproxy
: ['', gettext('Console') + ' (xterm.js)'],
633 vncshell
: ['', gettext('Shell')],
636 // to add or change existing for product specific ones
637 override_task_descriptions: function(extra
) {
638 for (const [key
, value
] of Object
.entries(extra
)) {
639 Proxmox
.Utils
.task_desc_table
[key
] = value
;
643 format_task_description: function(type
, id
) {
644 let farray
= Proxmox
.Utils
.task_desc_table
[type
];
652 } else if (Ext
.isFunction(farray
)) {
653 return farray(type
, id
);
655 let prefix
= farray
[0];
657 if (prefix
&& id
!== undefined) {
658 return prefix
+ ' ' + id
+ ' - ' + text
;
663 format_size: function(size
, useSI
) {
664 let units
= ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'];
666 const baseValue
= useSI
? 1000 : 1024;
667 while (size
>= baseValue
&& order
< units
.length
) {
668 size
= size
/ baseValue
;
672 let unit
= units
[order
], commaDigits
= 2;
678 return `${size.toFixed(commaDigits)} ${unit}B`;
686 'GiB': 1024*1024*1024,
687 'TiB': 1024*1024*1024*1024,
688 'PiB': 1024*1024*1024*1024*1024,
692 'GB': 1000*1000*1000,
693 'TB': 1000*1000*1000*1000,
694 'PB': 1000*1000*1000*1000*1000,
697 parse_size_unit: function(val
) {
698 //let m = val.match(/([.\d])+\s?([KMGTP]?)(i?)B?\s*$/i);
699 let m
= val
.match(/(\d+(?:\.\d+)?)\s?([KMGTP]?)(i?)B?\s*$/i);
700 let size
= parseFloat(m
[1]);
701 let scale
= m
[2].toUpperCase();
702 let binary
= m
[3].toLowerCase();
704 let unit
= `${scale}${binary}B`;
705 let factor
= Proxmox
.Utils
.SizeUnits
[unit
];
707 return { size
, factor
, unit
, binary
}; // for convenience return all we got
710 size_unit_to_bytes: function(val
) {
711 let { size
, factor
} = Proxmox
.Utils
.parse_size_unit(val
);
712 return size
* factor
;
715 autoscale_size_unit: function(val
) {
716 let { size
, factor
, binary
} = Proxmox
.Utils
.parse_size_unit(val
);
717 return Proxmox
.Utils
.format_size(size
* factor
, binary
!== "i");
720 size_unit_ratios: function(a
, b
) {
721 a
= typeof a
!== "undefined" ? a
: 0;
722 b
= typeof b
!== "undefined" ? b
: Infinity
;
723 let aBytes
= typeof a
=== "number" ? a
: Proxmox
.Utils
.size_unit_to_bytes(a
);
724 let bBytes
= typeof b
=== "number" ? b
: Proxmox
.Utils
.size_unit_to_bytes(b
);
725 return aBytes
/ (bBytes
|| Infinity
); // avoid division by zero
728 render_upid: function(value
, metaData
, record
) {
729 let task
= record
.data
;
730 let type
= task
.type
|| task
.worker_type
;
731 let id
= task
.id
|| task
.worker_id
;
733 return Proxmox
.Utils
.format_task_description(type
, id
);
736 render_uptime: function(value
) {
739 if (uptime
=== undefined) {
747 return Proxmox
.Utils
.format_duration_long(uptime
);
750 systemd_unescape: function(string_value
) {
751 const charcode_0
= '0'.charCodeAt(0);
752 const charcode_9
= '9'.charCodeAt(0);
753 const charcode_A
= 'A'.charCodeAt(0);
754 const charcode_F
= 'F'.charCodeAt(0);
755 const charcode_a
= 'a'.charCodeAt(0);
756 const charcode_f
= 'f'.charCodeAt(0);
757 const charcode_x
= 'x'.charCodeAt(0);
758 const charcode_minus
= '-'.charCodeAt(0);
759 const charcode_slash
= '/'.charCodeAt(0);
760 const charcode_backslash
= '\\'.charCodeAt(0);
762 let parse_hex_digit = function(d
) {
763 if (d
>= charcode_0
&& d
<= charcode_9
) {
764 return d
- charcode_0
;
766 if (d
>= charcode_A
&& d
<= charcode_F
) {
767 return d
- charcode_A
+ 10;
769 if (d
>= charcode_a
&& d
<= charcode_f
) {
770 return d
- charcode_a
+ 10;
772 throw "got invalid hex digit";
775 let value
= new TextEncoder().encode(string_value
);
776 let result
= new Uint8Array(value
.length
);
781 while (i
< value
.length
) {
783 if (c0
=== charcode_minus
) {
784 result
.set([charcode_slash
], result_len
);
789 if ((i
+ 4) < value
.length
) {
791 if (c0
=== charcode_backslash
&& c1
=== charcode_x
) {
792 let h1
= parse_hex_digit(value
[i
+2]);
793 let h0
= parse_hex_digit(value
[i
+3]);
795 result
.set([ord
], result_len
);
801 result
.set([c0
], result_len
);
806 return new TextDecoder().decode(result
.slice(0, result
.len
));
809 parse_task_upid: function(upid
) {
812 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]+):$/);
814 throw "unable to parse upid '" + upid
+ "'";
817 task
.pid
= parseInt(res
[2], 16);
818 task
.pstart
= parseInt(res
[3], 16);
819 if (res
[5] !== undefined) {
820 task
.task_id
= parseInt(res
[5], 16);
822 task
.starttime
= parseInt(res
[6], 16);
824 task
.id
= Proxmox
.Utils
.systemd_unescape(res
[8]);
827 task
.desc
= Proxmox
.Utils
.format_task_description(task
.type
, task
.id
);
832 parse_task_status: function(status
) {
833 if (status
=== 'OK') {
837 if (status
=== 'unknown') {
841 let match
= status
.match(/^WARNINGS: (.*)$/);
849 format_task_status: function(status
) {
850 let parsed
= Proxmox
.Utils
.parse_task_status(status
);
852 case 'unknown': return Proxmox
.Utils
.unknownText
;
853 case 'error': return Proxmox
.Utils
.errorText
+ ': ' + status
;
854 case 'warning': return status
.replace('WARNINGS', Proxmox
.Utils
.warningsText
);
855 case 'ok': // fall-through
856 default: return status
;
860 render_duration: function(value
) {
861 if (value
=== undefined) {
864 return Proxmox
.Utils
.format_duration_human(value
);
867 render_timestamp: function(value
, metaData
, record
, rowIndex
, colIndex
, store
) {
868 let servertime
= new Date(value
* 1000);
869 return Ext
.Date
.format(servertime
, 'Y-m-d H:i:s');
872 render_zfs_health: function(value
) {
873 if (typeof value
=== 'undefined') {
876 var iconCls
= 'question-circle';
880 iconCls
= 'check-circle good';
884 iconCls
= 'exclamation-circle warning';
889 iconCls
= 'times-circle critical';
894 return '<i class="fa fa-' + iconCls
+ '"></i> ' + value
;
897 get_help_info: function(section
) {
899 if (typeof proxmoxOnlineHelpInfo
!== 'undefined') {
900 helpMap
= proxmoxOnlineHelpInfo
; // eslint-disable-line no-undef
901 } else if (typeof pveOnlineHelpInfo
!== 'undefined') {
902 // be backward compatible with older pve-doc-generators
903 helpMap
= pveOnlineHelpInfo
; // eslint-disable-line no-undef
905 throw "no global OnlineHelpInfo map declared";
908 if (helpMap
[section
]) {
909 return helpMap
[section
];
911 // try to normalize - and _ separators, to support asciidoc and sphinx
912 // references at the same time.
913 let section_minus_normalized
= section
.replace(/_
/g
, '-');
914 if (helpMap
[section_minus_normalized
]) {
915 return helpMap
[section_minus_normalized
];
917 let section_underscore_normalized
= section
.replace(/-/g
, '_');
918 return helpMap
[section_underscore_normalized
];
921 get_help_link: function(section
) {
922 let info
= Proxmox
.Utils
.get_help_info(section
);
926 return window
.location
.origin
+ info
.link
;
929 openXtermJsViewer: function(vmtype
, vmid
, nodename
, vmname
, cmd
) {
930 let url
= Ext
.Object
.toQueryString({
931 console
: vmtype
, // kvm, lxc, upgrade or shell
939 let nw
= window
.open("?" + url
, '_blank', 'toolbar=no,location=no,status=no,menubar=no,resizable=yes,width=800,height=420');
945 render_optional_url: function(value
) {
946 if (value
&& value
.match(/^https?:\/\//) !== null) {
947 return '<a target="_blank" href="' + value
+ '">' + value
+ '</a>';
952 render_san: function(value
) {
954 if (Ext
.isArray(value
)) {
955 value
.forEach(function(val
) {
956 if (!Ext
.isNumber(val
)) {
960 return names
.join('<br>');
965 render_usage
: val
=> (val
* 100).toFixed(2) + '%',
967 render_cpu_usage: function(val
, max
) {
968 return Ext
.String
.format(
969 `${gettext('{0}% of {1}')} ${gettext('CPU(s)')}`,
970 (val
*100).toFixed(2),
975 render_size_usage: function(val
, max
, useSI
) {
977 return gettext('N/A');
979 let fmt
= v
=> Proxmox
.Utils
.format_size(v
, useSI
);
980 let ratio
= (val
* 100 / max
).toFixed(2);
981 return ratio
+ '% (' + Ext
.String
.format(gettext('{0} of {1}'), fmt(val
), fmt(max
)) + ')';
984 render_cpu: function(value
, metaData
, record
, rowIndex
, colIndex
, store
) {
985 if (!(record
.data
.uptime
&& Ext
.isNumeric(value
))) {
989 let maxcpu
= record
.data
.maxcpu
|| 1;
990 if (!Ext
.isNumeric(maxcpu
) || maxcpu
< 1) {
993 let cpuText
= maxcpu
> 1 ? 'CPUs' : 'CPU';
994 let ratio
= (value
* 100).toFixed(1);
995 return `${ratio}% of ${maxcpu.toString()} ${cpuText}`;
998 render_size: function(value
, metaData
, record
, rowIndex
, colIndex
, store
) {
999 if (!Ext
.isNumeric(value
)) {
1002 return Proxmox
.Utils
.format_size(value
);
1005 render_cpu_model: function(cpu
) {
1006 let socketText
= cpu
.sockets
> 1 ? gettext('Sockets') : gettext('Socket');
1007 return `${cpu.cpus} x ${cpu.model} (${cpu.sockets.toString()} ${socketText})`;
1010 /* this is different for nodes */
1011 render_node_cpu_usage: function(value
, record
) {
1012 return Proxmox
.Utils
.render_cpu_usage(value
, record
.cpus
);
1015 render_node_size_usage: function(record
) {
1016 return Proxmox
.Utils
.render_size_usage(record
.used
, record
.total
);
1019 loadTextFromFile: function(file
, callback
, maxBytes
) {
1020 let maxSize
= maxBytes
|| 8192;
1021 if (file
.size
> maxSize
) {
1022 Ext
.Msg
.alert(gettext('Error'), gettext("Invalid file size: ") + file
.size
);
1025 let reader
= new FileReader();
1026 reader
.onload
= evt
=> callback(evt
.target
.result
);
1027 reader
.readAsText(file
);
1030 parsePropertyString: function(value
, defaultKey
) {
1034 if (typeof value
!== 'string' || value
=== '') {
1038 Ext
.Array
.each(value
.split(','), function(p
) {
1039 var kv
= p
.split('=', 2);
1040 if (Ext
.isDefined(kv
[1])) {
1042 } else if (Ext
.isDefined(defaultKey
)) {
1043 if (Ext
.isDefined(res
[defaultKey
])) {
1044 error
= 'defaultKey may be only defined once in propertyString';
1045 return false; // break
1047 res
[defaultKey
] = kv
[0];
1049 error
= 'invalid propertyString, not a key=value pair and no defaultKey defined';
1050 return false; // break
1055 if (error
!== undefined) {
1056 console
.error(error
);
1063 printPropertyString: function(data
, defaultKey
) {
1064 var stringparts
= [],
1065 gotDefaultKeyVal
= false,
1068 Ext
.Object
.each(data
, function(key
, value
) {
1069 if (defaultKey
!== undefined && key
=== defaultKey
) {
1070 gotDefaultKeyVal
= true;
1071 defaultKeyVal
= value
;
1072 } else if (Ext
.isArray(value
)) {
1073 stringparts
.push(key
+ '=' + value
.join(';'));
1074 } else if (value
!== '') {
1075 stringparts
.push(key
+ '=' + value
);
1079 stringparts
= stringparts
.sort();
1080 if (gotDefaultKeyVal
) {
1081 stringparts
.unshift(defaultKeyVal
);
1084 return stringparts
.join(',');
1087 acmedomain_count
: 5,
1089 parseACMEPluginData: function(data
) {
1092 data
.split('\n').forEach((line
) => {
1093 // capture everything after the first = as value
1094 let [key
, value
] = line
.split('=');
1095 if (value
!== undefined) {
1098 extradata
.push(line
);
1101 return [res
, extradata
];
1104 delete_if_default: function(values
, fieldname
, default_val
, create
) {
1105 if (values
[fieldname
] === '' || values
[fieldname
] === default_val
) {
1107 if (values
.delete) {
1108 if (Ext
.isArray(values
.delete)) {
1109 values
.delete.push(fieldname
);
1111 values
.delete += ',' + fieldname
;
1114 values
.delete = fieldname
;
1118 delete values
[fieldname
];
1122 printACME: function(value
) {
1123 if (Ext
.isArray(value
.domains
)) {
1124 value
.domains
= value
.domains
.join(';');
1126 return Proxmox
.Utils
.printPropertyString(value
);
1129 parseACME: function(value
) {
1137 Ext
.Array
.each(value
.split(','), function(p
) {
1138 var kv
= p
.split('=', 2);
1139 if (Ext
.isDefined(kv
[1])) {
1142 error
= 'Failed to parse key-value pair: '+p
;
1148 if (error
!== undefined) {
1149 console
.error(error
);
1153 if (res
.domains
!== undefined) {
1154 res
.domains
= res
.domains
.split(/;/);
1160 add_domain_to_acme: function(acme
, domain
) {
1161 if (acme
.domains
=== undefined) {
1162 acme
.domains
= [domain
];
1164 acme
.domains
.push(domain
);
1165 acme
.domains
= acme
.domains
.filter((value
, index
, self
) => self
.indexOf(value
) === index
);
1170 remove_domain_from_acme: function(acme
, domain
) {
1171 if (acme
.domains
!== undefined) {
1172 acme
.domains
= acme
.domains
.filter(
1173 (value
, index
, self
) => self
.indexOf(value
) === index
&& value
!== domain
,
1179 get_health_icon: function(state
, circle
) {
1180 if (circle
=== undefined) {
1184 if (state
=== undefined) {
1188 var icon
= 'faded fa-question';
1191 icon
= 'good fa-check';
1194 icon
= 'warning fa-upload';
1197 icon
= 'warning fa-refresh';
1200 icon
= 'warning fa-exclamation';
1203 icon
= 'critical fa-times';
1215 formatNodeRepoStatus: function(status
, product
) {
1216 let fmt
= (txt
, cls
) => `<i class="fa fa-fw fa-lg fa-${cls}"></i>${txt}`;
1218 let getUpdates
= Ext
.String
.format(gettext('{0} updates'), product
);
1219 let noRepo
= Ext
.String
.format(gettext('No {0} repository enabled!'), product
);
1221 if (status
=== 'ok') {
1222 return fmt(getUpdates
, 'check-circle good') + ' ' +
1223 fmt(gettext('Production-ready Enterprise repository enabled'), 'check-circle good');
1224 } else if (status
=== 'no-sub') {
1225 return fmt(gettext('Production-ready Enterprise repository enabled'), 'check-circle good') + ' ' +
1226 fmt(gettext('Enterprise repository needs valid subscription'), 'exclamation-circle warning');
1227 } else if (status
=== 'non-production') {
1228 return fmt(getUpdates
, 'check-circle good') + ' ' +
1229 fmt(gettext('Non production-ready repository enabled!'), 'exclamation-circle warning');
1230 } else if (status
=== 'no-repo') {
1231 return fmt(noRepo
, 'exclamation-circle critical');
1234 return Proxmox
.Utils
.unknownText
;
1237 render_u2f_error: function(error
) {
1239 '1': gettext('Other Error'),
1240 '2': gettext('Bad Request'),
1241 '3': gettext('Configuration Unsupported'),
1242 '4': gettext('Device Ineligible'),
1243 '5': gettext('Timeout'),
1245 return "U2F Error: " + ErrorNames
[error
] || Proxmox
.Utils
.unknownText
;
1248 // Convert an ArrayBuffer to a base64url encoded string.
1249 // A `null` value will be preserved for convenience.
1250 bytes_to_base64url: function(bytes
) {
1251 if (bytes
=== null) {
1256 .from(new Uint8Array(bytes
))
1257 .map(val
=> String
.fromCharCode(val
))
1260 .replace(/\+/g, '-')
1261 .replace(/\//g, '_')
1262 .replace(/[=]/g, '');
1265 // Convert an a base64url string to an ArrayBuffer.
1266 // A `null` value will be preserved for convenience.
1267 base64url_to_bytes: function(b64u
) {
1268 if (b64u
=== null) {
1272 return new Uint8Array(
1275 .replace(/_/g, '/'),
1278 .map(val => val.charCodeAt(0)),
1282 stringToRGB: function(string) {
1287 string += 'prox
'; // give short strings more variance
1288 for (let i = 0; i < string.length; i++) {
1289 hash = string.charCodeAt(i) + ((hash << 5) - hash);
1290 hash = hash & hash; // to int
1293 let alpha = 0.7; // make the color a bit brighter
1294 let bg = 255; // assume white background
1297 (hash & 255) * alpha + bg * (1 - alpha),
1298 ((hash >> 8) & 255) * alpha + bg * (1 - alpha),
1299 ((hash >> 16) & 255) * alpha + bg * (1 - alpha),
1303 rgbToCss: function(rgb) {
1304 return `rgb(${rgb[0]}, ${rgb[1]}, ${rgb[2]})`;
1307 rgbToHex: function(rgb) {
1308 let r = Math.round(rgb[0]).toString(16);
1309 let g = Math.round(rgb[1]).toString(16);
1310 let b = Math.round(rgb[2]).toString(16);
1311 return `${r}${g}${b}`;
1314 hexToRGB: function(hex) {
1318 if (hex.length === 7) {
1321 let r = parseInt(hex.slice(0, 2), 16);
1322 let g = parseInt(hex.slice(2, 4), 16);
1323 let b = parseInt(hex.slice(4, 6), 16);
1327 // optimized & simplified SAPC function
1328 // https://github.com/Myndex/SAPC-APCA
1329 getTextContrastClass: function(rgb) {
1330 const blkThrs = 0.022;
1331 const blkClmp = 1.414;
1333 // linearize & gamma correction
1334 let r = (rgb[0] / 255) ** 2.4;
1335 let g = (rgb[1] / 255) ** 2.4;
1336 let b = (rgb[2] / 255) ** 2.4;
1338 // relative luminance sRGB
1339 let bg = r * 0.2126729 + g * 0.7151522 + b * 0.0721750;
1342 bg = bg > blkThrs ? bg : bg + (blkThrs - bg) ** blkClmp;
1344 // SAPC with white text
1345 let contrastLight = bg ** 0.65 - 1;
1346 // SAPC with black text
1347 let contrastDark = bg ** 0.56 - 0.046134502;
1349 if (Math.abs(contrastLight) >= Math.abs(contrastDark)) {
1356 getTagElement: function(string, color_overrides) {
1357 let rgb = color_overrides?.[string] || Proxmox.Utils.stringToRGB(string);
1358 let style = `background-color: ${Proxmox.Utils.rgbToCss(rgb)};`;
1360 if (rgb.length > 3) {
1361 style += `color: ${Proxmox.Utils.rgbToCss([rgb[3], rgb[4], rgb[5]])}`;
1362 cls = "proxmox-tag-dark";
1364 let txtCls = Proxmox.Utils.getTextContrastClass(rgb);
1365 cls = `proxmox-tag-${txtCls}`;
1367 return `<span class="${cls}" style="${style}">${string}</span>`;
1370 // Setting filename here when downloading from a remote url sometimes fails in chromium browsers
1371 // because of a bug when using attribute download in conjunction with a self signed certificate.
1372 // For more info see https://bugs.chromium.org/p/chromium/issues/detail?id=993362
1373 downloadAsFile: function(source, fileName) {
1374 let hiddenElement = document.createElement('a
');
1375 hiddenElement.href = source;
1376 hiddenElement.target = '_blank
';
1378 hiddenElement.download = fileName;
1380 hiddenElement.click();
1385 constructor: function() {
1387 Ext.apply(me, me.utilities);
1389 let IPV4_OCTET = "(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])";
1390 let IPV4_REGEXP = "(?:(?:" + IPV4_OCTET + "\\.){3}" + IPV4_OCTET + ")";
1391 let IPV6_H16 = "(?:[0-9a-fA-F]{1,4})";
1392 let IPV6_LS32 = "(?:(?:" + IPV6_H16 + ":" + IPV6_H16 + ")|" + IPV4_REGEXP + ")";
1393 let IPV4_CIDR_MASK = "([0-9]{1,2})";
1394 let IPV6_CIDR_MASK = "([0-9]{1,3})";
1397 me.IP4_match = new RegExp("^(?:" + IPV4_REGEXP + ")$");
1398 me.IP4_cidr_match = new RegExp("^(?:" + IPV4_REGEXP + ")/" + IPV4_CIDR_MASK + "$");
1400 /* eslint-disable no-useless-concat,no-multi-spaces */
1401 let IPV6_REGEXP = "(?:" +
1402 "(?:(?:" + "(?:" + IPV6_H16 + ":){6})" + IPV6_LS32 + ")|" +
1403 "(?:(?:" + "::" + "(?:" + IPV6_H16 + ":){5})" + IPV6_LS32 + ")|" +
1404 "(?:(?:(?:" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){4})" + IPV6_LS32 + ")|" +
1405 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,1}" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){3})" + IPV6_LS32 + ")|" +
1406 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,2}" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){2})" + IPV6_LS32 + ")|" +
1407 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,3}" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){1})" + IPV6_LS32 + ")|" +
1408 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,4}" + IPV6_H16 + ")?::" + ")" + IPV6_LS32 + ")|" +
1409 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,5}" + IPV6_H16 + ")?::" + ")" + IPV6_H16 + ")|" +
1410 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,7}" + IPV6_H16 + ")?::" + ")" + ")" +
1412 /* eslint-enable no-useless-concat,no-multi-spaces */
1414 me.IP6_match = new RegExp("^(?:" + IPV6_REGEXP + ")$");
1415 me.IP6_cidr_match = new RegExp("^(?:" + IPV6_REGEXP + ")/" + IPV6_CIDR_MASK + "$");
1416 me.IP6_bracket_match = new RegExp("^\\[(" + IPV6_REGEXP + ")\\]");
1418 me.IP64_match = new RegExp("^(?:" + IPV6_REGEXP + "|" + IPV4_REGEXP + ")$");
1419 me.IP64_cidr_match = new RegExp("^(?:" + IPV6_REGEXP + "/" + IPV6_CIDR_MASK + ")|(?:" + IPV4_REGEXP + "/" + IPV4_CIDR_MASK + ")$");
1421 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])?))";
1422 me.DnsName_match = new RegExp("^" + DnsName_REGEXP + "$");
1423 me.DnsName_or_Wildcard_match = new RegExp("^(?:\\*\\.)?" + DnsName_REGEXP + "$");
1425 me.CpuSet_match = /^[0-9]+(?:-[0-9]+)?(?:,[0-9]+(?:-[0-9]+)?)*$/;
1427 me.HostPort_match = new RegExp("^(" + IPV4_REGEXP + "|" + DnsName_REGEXP + ")(?::(\\d+))?$");
1428 me.HostPortBrackets_match = new RegExp("^\\[(" + IPV6_REGEXP + "|" + IPV4_REGEXP + "|" + DnsName_REGEXP + ")\\](?::(\\d+))?$");
1429 me.IP6_dotnotation_match = new RegExp("^(" + IPV6_REGEXP + ")(?:\\.(\\d+))?$");
1430 me.Vlan_match = /^vlan(\d+)/;
1431 me.VlanInterface_match = /(\w+)\.(\d+)/;
1435 Ext.define('Proxmox
.Async
', {
1438 // Returns a Promise resolving to the result of an `API2Request` or rejecting to the error
1439 // response on failure
1440 api2: function(reqOpts) {
1441 return new Promise((resolve, reject) => {
1442 delete reqOpts.callback; // not allowed in this api
1443 reqOpts.success = response => resolve(response);
1444 reqOpts.failure = response => reject(response);
1445 Proxmox.Utils.API2Request(reqOpts);
1449 // Delay for a number of milliseconds.
1450 sleep: function(millis) {
1451 return new Promise((resolve, _reject) => setTimeout(resolve, millis));
1455 Ext.override(Ext.data.Store, {
1456 // If the store's proxy is changed
while it is waiting
for an AJAX
1457 // response, `onProxyLoad` will still be called for the outdated response.
1458 // To avoid displaying inconsistent information, only process responses
1459 // belonging to the current proxy.
1460 onProxyLoad: function(operation
) {
1462 if (operation
.getProxy() === me
.getProxy()) {
1463 me
.callParent(arguments
);
1465 console
.log(`ignored outdated response: ${operation.getRequest().getUrl()}`);