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
)]);
113 crisp
: 'Light theme',
114 "proxmox-dark": 'Proxmox Dark',
117 render_theme: function(value
) {
118 if (!value
|| value
=== '__default__') {
119 return Proxmox
.Utils
.defaultText
+ ' (auto)';
121 let text
= Proxmox
.Utils
.theme_map
[value
];
128 theme_array: function() {
129 let data
= [['__default__', Proxmox
.Utils
.render_theme('')]];
130 Ext
.Object
.each(Proxmox
.Utils
.theme_map
, function(key
, value
) {
131 data
.push([key
, Proxmox
.Utils
.render_theme(value
)]);
137 bond_mode_gettext_map
: {
138 '802.3ad': 'LACP (802.3ad)',
139 'lacp-balance-slb': 'LACP (balance-slb)',
140 'lacp-balance-tcp': 'LACP (balance-tcp)',
143 render_bond_mode
: value
=> Proxmox
.Utils
.bond_mode_gettext_map
[value
] || value
|| '',
145 bond_mode_array: function(modes
) {
146 return modes
.map(mode
=> [mode
, Proxmox
.Utils
.render_bond_mode(mode
)]);
149 getNoSubKeyHtml: function(url
) {
150 // url http://www.proxmox.com/products/proxmox-ve/subscription-service-plans
151 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');
154 format_boolean_with_default: function(value
) {
155 if (Ext
.isDefined(value
) && value
!== '__default__') {
156 return value
? Proxmox
.Utils
.yesText
: Proxmox
.Utils
.noText
;
158 return Proxmox
.Utils
.defaultText
;
161 format_boolean: function(value
) {
162 return value
? Proxmox
.Utils
.yesText
: Proxmox
.Utils
.noText
;
165 format_neg_boolean: function(value
) {
166 return !value
? Proxmox
.Utils
.yesText
: Proxmox
.Utils
.noText
;
169 format_enabled_toggle: function(value
) {
170 return value
? Proxmox
.Utils
.enabledText
: Proxmox
.Utils
.disabledText
;
173 format_expire: function(date
) {
175 return Proxmox
.Utils
.neverText
;
177 return Ext
.Date
.format(date
, "Y-m-d");
180 // somewhat like a human would tell durations, omit zero values and do not
181 // give seconds precision if we talk days already
182 format_duration_human: function(ut
) {
183 let seconds
= 0, minutes
= 0, hours
= 0, days
= 0, years
= 0;
190 seconds
= Number((remaining
% 60).toFixed(1));
191 remaining
= Math
.trunc(remaining
/ 60);
193 minutes
= remaining
% 60;
194 remaining
= Math
.trunc(remaining
/ 60);
196 hours
= remaining
% 24;
197 remaining
= Math
.trunc(remaining
/ 24);
199 days
= remaining
% 365;
200 remaining
= Math
.trunc(remaining
/ 365); // yea, just lets ignore leap years...
209 let add
= (t
, unit
) => {
210 if (t
> 0) res
.push(t
+ unit
);
214 let addMinutes
= !add(years
, 'y');
215 let addSeconds
= !add(days
, 'd');
223 return res
.join(' ');
226 format_duration_long: function(ut
) {
227 let days
= Math
.floor(ut
/ 86400);
229 let hours
= Math
.floor(ut
/ 3600);
231 let mins
= Math
.floor(ut
/ 60);
234 let hours_str
= '00' + hours
.toString();
235 hours_str
= hours_str
.substr(hours_str
.length
- 2);
236 let mins_str
= "00" + mins
.toString();
237 mins_str
= mins_str
.substr(mins_str
.length
- 2);
238 let ut_str
= "00" + ut
.toString();
239 ut_str
= ut_str
.substr(ut_str
.length
- 2);
242 let ds
= days
> 1 ? Proxmox
.Utils
.daysText
: Proxmox
.Utils
.dayText
;
243 return days
.toString() + ' ' + ds
+ ' ' +
244 hours_str
+ ':' + mins_str
+ ':' + ut_str
;
246 return hours_str
+ ':' + mins_str
+ ':' + ut_str
;
250 format_subscription_level: function(level
) {
253 } else if (level
=== 'b') {
255 } else if (level
=== 's') {
257 } else if (level
=== 'p') {
260 return Proxmox
.Utils
.noneText
;
264 compute_min_label_width: function(text
, width
) {
265 if (width
=== undefined) { width
= 100; }
267 let tm
= new Ext
.util
.TextMetrics();
268 let min
= tm
.getWidth(text
+ ':');
270 return min
< width
? width
: min
;
273 // returns username + realm
274 parse_userid: function(userid
) {
275 if (!Ext
.isString(userid
)) {
276 return [undefined, undefined];
279 let match
= userid
.match(/^(.+)@([^@]+)$/);
280 if (match
!== null) {
281 return [match
[1], match
[2]];
284 return [undefined, undefined];
287 render_username: function(userid
) {
288 let username
= Proxmox
.Utils
.parse_userid(userid
)[0] || "";
289 return Ext
.htmlEncode(username
);
292 render_realm: function(userid
) {
293 let username
= Proxmox
.Utils
.parse_userid(userid
)[1] || "";
294 return Ext
.htmlEncode(username
);
297 getStoredAuth: function() {
298 let storedAuth
= JSON
.parse(window
.localStorage
.getItem('ProxmoxUser'));
299 return storedAuth
|| {};
302 setAuthData: function(data
) {
303 Proxmox
.UserName
= data
.username
;
304 Proxmox
.LoggedOut
= data
.LoggedOut
;
305 // creates a session cookie (expire = null)
306 // that way the cookie gets deleted after the browser window is closed
308 Proxmox
.CSRFPreventionToken
= data
.CSRFPreventionToken
;
309 Ext
.util
.Cookies
.set(Proxmox
.Setup
.auth_cookie_name
, data
.ticket
, null, '/', null, true);
313 window
.localStorage
.setItem('ProxmoxUser', JSON
.stringify(data
));
318 if (Proxmox
.LoggedOut
) {
321 let storedAuth
= Proxmox
.Utils
.getStoredAuth();
322 let cookie
= Ext
.util
.Cookies
.get(Proxmox
.Setup
.auth_cookie_name
);
323 if ((Proxmox
.UserName
!== '' && cookie
&& !cookie
.startsWith("PVE:tfa!")) || storedAuth
.token
) {
324 return cookie
|| storedAuth
.token
;
330 authClear: function() {
331 if (Proxmox
.LoggedOut
) {
334 // ExtJS clear is basically the same, but browser may complain if any cookie isn't "secure"
335 Ext
.util
.Cookies
.set(Proxmox
.Setup
.auth_cookie_name
, "", new Date(0), null, null, true);
336 window
.localStorage
.removeItem("ProxmoxUser");
339 // The End-User gets redirected back here after login on the OpenID auth. portal, and in the
340 // redirection URL the state and auth.code are passed as URL GET params, this helper parses those
341 getOpenIDRedirectionAuthorization: function() {
342 const auth
= Ext
.Object
.fromQueryString(window
.location
.search
);
343 if (auth
.state
!== undefined && auth
.code
!== undefined) {
349 // comp.setLoading() is buggy in ExtJS 4.0.7, so we
350 // use el.mask() instead
351 setErrorMask: function(comp
, msg
) {
358 } else if (msg
=== true) {
359 el
.mask(gettext("Loading..."));
365 getResponseErrorMessage
: (err
) => {
366 if (!err
.statusText
) {
367 return gettext('Connection error');
369 let msg
= [`${err.statusText} (${err.status})`];
370 if (err
.response
&& err
.response
.responseText
) {
371 let txt
= err
.response
.responseText
;
373 let res
= JSON
.parse(txt
);
374 if (res
.errors
&& typeof res
.errors
=== 'object') {
375 for (let [key
, value
] of Object
.entries(res
.errors
)) {
376 msg
.push(Ext
.String
.htmlEncode(`${key}: ${value}`));
380 // fallback to string
381 msg
.push(Ext
.String
.htmlEncode(txt
));
384 return msg
.join('<br>');
387 monStoreErrors: function(component
, store
, clearMaskBeforeLoad
, errorCallback
) {
388 if (clearMaskBeforeLoad
) {
389 component
.mon(store
, 'beforeload', function(s
, operation
, eOpts
) {
390 Proxmox
.Utils
.setErrorMask(component
, false);
393 component
.mon(store
, 'beforeload', function(s
, operation
, eOpts
) {
394 if (!component
.loadCount
) {
395 component
.loadCount
= 0; // make sure it is nucomponent.ic
396 Proxmox
.Utils
.setErrorMask(component
, true);
401 // only works with 'proxmox' proxy
402 component
.mon(store
.proxy
, 'afterload', function(proxy
, request
, success
) {
403 component
.loadCount
++;
406 Proxmox
.Utils
.setErrorMask(component
, false);
410 let error
= request
._operation
.getError();
411 let msg
= Proxmox
.Utils
.getResponseErrorMessage(error
);
412 if (!errorCallback
|| !errorCallback(error
, msg
)) {
413 Proxmox
.Utils
.setErrorMask(component
, msg
);
418 extractRequestError: function(result
, verbose
) {
419 let msg
= gettext('Successful');
421 if (!result
.success
) {
422 msg
= gettext("Unknown error");
423 if (result
.message
) {
424 msg
= Ext
.htmlEncode(result
.message
);
426 msg
+= ` (${result.status})`;
429 if (verbose
&& Ext
.isObject(result
.errors
)) {
431 Ext
.Object
.each(result
.errors
, (prop
, desc
) => {
432 msg
+= `<br><b>${Ext.htmlEncode(prop)}</b>: ${Ext.htmlEncode(desc)}`;
441 API2Request: function(reqOpts
) {
442 let newopts
= Ext
.apply({
443 waitMsg
: gettext('Please wait...'),
446 // default to enable if user isn't handling the failure already explicitly
447 let autoErrorAlert
= reqOpts
.autoErrorAlert
??
448 (typeof reqOpts
.failure
!== 'function' && typeof reqOpts
.callback
!== 'function');
450 if (!newopts
.url
.match(/^\/api2/)) {
451 newopts
.url
= '/api2/extjs' + newopts
.url
;
453 delete newopts
.callback
;
455 let createWrapper = function(successFn
, callbackFn
, failureFn
) {
457 success: function(response
, options
) {
458 if (options
.waitMsgTarget
) {
459 if (Proxmox
.Utils
.toolkit
=== 'touch') {
460 options
.waitMsgTarget
.setMasked(false);
462 options
.waitMsgTarget
.setLoading(false);
465 let result
= Ext
.decode(response
.responseText
);
466 response
.result
= result
;
467 if (!result
.success
) {
468 response
.htmlStatus
= Proxmox
.Utils
.extractRequestError(result
, true);
469 Ext
.callback(callbackFn
, options
.scope
, [options
, false, response
]);
470 Ext
.callback(failureFn
, options
.scope
, [response
, options
]);
471 if (autoErrorAlert
) {
472 Ext
.Msg
.alert(gettext('Error'), response
.htmlStatus
);
476 Ext
.callback(callbackFn
, options
.scope
, [options
, true, response
]);
477 Ext
.callback(successFn
, options
.scope
, [response
, options
]);
479 failure: function(response
, options
) {
480 if (options
.waitMsgTarget
) {
481 if (Proxmox
.Utils
.toolkit
=== 'touch') {
482 options
.waitMsgTarget
.setMasked(false);
484 options
.waitMsgTarget
.setLoading(false);
487 response
.result
= {};
489 response
.result
= Ext
.decode(response
.responseText
);
493 let msg
= gettext('Connection error') + ' - server offline?';
494 if (response
.aborted
) {
495 msg
= gettext('Connection error') + ' - aborted.';
496 } else if (response
.timedout
) {
497 msg
= gettext('Connection error') + ' - Timeout.';
498 } else if (response
.status
&& response
.statusText
) {
499 msg
= gettext('Connection error') + ' ' + response
.status
+ ': ' + response
.statusText
;
501 response
.htmlStatus
= msg
;
502 Ext
.callback(callbackFn
, options
.scope
, [options
, false, response
]);
503 Ext
.callback(failureFn
, options
.scope
, [response
, options
]);
508 createWrapper(reqOpts
.success
, reqOpts
.callback
, reqOpts
.failure
);
510 let target
= newopts
.waitMsgTarget
;
512 if (Proxmox
.Utils
.toolkit
=== 'touch') {
513 target
.setMasked({ xtype
: 'loadmask', message
: newopts
.waitMsg
});
515 // Note: ExtJS bug - this does not work when component is not rendered
516 target
.setLoading(newopts
.waitMsg
);
519 Ext
.Ajax
.request(newopts
);
522 // can be useful for catching displaying errors from the API, e.g.:
523 // Proxmox.Async.api2({
525 // }).catch(Proxmox.Utils.alertResponseFailure);
526 alertResponseFailure
: (response
) => {
529 response
.htmlStatus
|| response
.result
.message
,
533 checked_command: function(orig_cmd
) {
534 Proxmox
.Utils
.API2Request(
536 url
: '/nodes/localhost/subscription',
538 failure: function(response
, opts
) {
539 Ext
.Msg
.alert(gettext('Error'), response
.htmlStatus
);
541 success: function(response
, opts
) {
542 let res
= response
.result
;
543 if (res
=== null || res
=== undefined || !res
|| res
544 .data
.status
.toLowerCase() !== 'active') {
546 title
: gettext('No valid subscription'),
547 icon
: Ext
.Msg
.WARNING
,
548 message
: Proxmox
.Utils
.getNoSubKeyHtml(res
.data
.url
),
550 callback: function(btn
) {
565 assemble_field_data: function(values
, data
) {
566 if (!Ext
.isObject(data
)) {
569 Ext
.Object
.each(data
, function(name
, val
) {
570 if (Object
.prototype.hasOwnProperty
.call(values
, name
)) {
571 let bucket
= values
[name
];
572 if (!Ext
.isArray(bucket
)) {
573 bucket
= values
[name
] = [bucket
];
575 if (Ext
.isArray(val
)) {
576 values
[name
] = bucket
.concat(val
);
586 updateColumnWidth: function(container
, thresholdWidth
) {
587 let mode
= Ext
.state
.Manager
.get('summarycolumns') || 'auto';
589 if (mode
!== 'auto') {
590 factor
= parseInt(mode
, 10);
591 if (Number
.isNaN(factor
)) {
595 thresholdWidth
= (thresholdWidth
|| 1400) + 1;
596 factor
= Math
.ceil(container
.getSize().width
/ thresholdWidth
);
599 if (container
.oldFactor
=== factor
) {
603 let items
= container
.query('>'); // direct children
604 factor
= Math
.min(factor
, items
.length
);
605 container
.oldFactor
= factor
;
607 items
.forEach((item
) => {
608 item
.columnWidth
= 1 / factor
;
611 // we have to update the layout twice, since the first layout change
612 // can trigger the scrollbar which reduces the amount of space left
613 container
.updateLayout();
614 container
.updateLayout();
617 // NOTE: depreacated, use updateColumnWidth
618 updateColumns
: container
=> Proxmox
.Utils
.updateColumnWidth(container
),
620 dialog_title: function(subject
, create
, isAdd
) {
623 return gettext('Add') + ': ' + subject
;
625 return gettext('Create') + ': ' + subject
;
628 return gettext('Edit') + ': ' + subject
;
632 network_iface_types
: {
633 eth
: gettext("Network Device"),
634 bridge
: 'Linux Bridge',
637 OVSBridge
: 'OVS Bridge',
640 OVSIntPort
: 'OVS IntPort',
643 render_network_iface_type: function(value
) {
644 return Proxmox
.Utils
.network_iface_types
[value
] ||
645 Proxmox
.Utils
.unknownText
;
648 // NOTE: only add general, product agnostic, ones here! Else use override helper in product repos
650 aptupdate
: ['', gettext('Update package database')],
651 diskinit
: ['Disk', gettext('Initialize Disk with GPT')],
652 spiceshell
: ['', gettext('Shell') + ' (Spice)'],
653 srvreload
: ['SRV', gettext('Reload')],
654 srvrestart
: ['SRV', gettext('Restart')],
655 srvstart
: ['SRV', gettext('Start')],
656 srvstop
: ['SRV', gettext('Stop')],
657 termproxy
: ['', gettext('Console') + ' (xterm.js)'],
658 vncshell
: ['', gettext('Shell')],
661 // to add or change existing for product specific ones
662 override_task_descriptions: function(extra
) {
663 for (const [key
, value
] of Object
.entries(extra
)) {
664 Proxmox
.Utils
.task_desc_table
[key
] = value
;
668 format_task_description: function(type
, id
) {
669 let farray
= Proxmox
.Utils
.task_desc_table
[type
];
677 } else if (Ext
.isFunction(farray
)) {
678 return farray(type
, id
);
680 let prefix
= farray
[0];
682 if (prefix
&& id
!== undefined) {
683 return prefix
+ ' ' + id
+ ' - ' + text
;
688 format_size: function(size
, useSI
) {
689 let units
= ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'];
691 const baseValue
= useSI
? 1000 : 1024;
692 while (size
>= baseValue
&& order
< units
.length
) {
693 size
= size
/ baseValue
;
697 let unit
= units
[order
], commaDigits
= 2;
703 return `${size.toFixed(commaDigits)} ${unit}B`;
711 'GiB': 1024*1024*1024,
712 'TiB': 1024*1024*1024*1024,
713 'PiB': 1024*1024*1024*1024*1024,
717 'GB': 1000*1000*1000,
718 'TB': 1000*1000*1000*1000,
719 'PB': 1000*1000*1000*1000*1000,
722 parse_size_unit: function(val
) {
723 //let m = val.match(/([.\d])+\s?([KMGTP]?)(i?)B?\s*$/i);
724 let m
= val
.match(/(\d+(?:\.\d+)?)\s?([KMGTP]?)(i?)B?\s*$/i);
725 let size
= parseFloat(m
[1]);
726 let scale
= m
[2].toUpperCase();
727 let binary
= m
[3].toLowerCase();
729 let unit
= `${scale}${binary}B`;
730 let factor
= Proxmox
.Utils
.SizeUnits
[unit
];
732 return { size
, factor
, unit
, binary
}; // for convenience return all we got
735 size_unit_to_bytes: function(val
) {
736 let { size
, factor
} = Proxmox
.Utils
.parse_size_unit(val
);
737 return size
* factor
;
740 autoscale_size_unit: function(val
) {
741 let { size
, factor
, binary
} = Proxmox
.Utils
.parse_size_unit(val
);
742 return Proxmox
.Utils
.format_size(size
* factor
, binary
!== "i");
745 size_unit_ratios: function(a
, b
) {
746 a
= typeof a
!== "undefined" ? a
: 0;
747 b
= typeof b
!== "undefined" ? b
: Infinity
;
748 let aBytes
= typeof a
=== "number" ? a
: Proxmox
.Utils
.size_unit_to_bytes(a
);
749 let bBytes
= typeof b
=== "number" ? b
: Proxmox
.Utils
.size_unit_to_bytes(b
);
750 return aBytes
/ (bBytes
|| Infinity
); // avoid division by zero
753 render_upid: function(value
, metaData
, record
) {
754 let task
= record
.data
;
755 let type
= task
.type
|| task
.worker_type
;
756 let id
= task
.id
|| task
.worker_id
;
758 return Proxmox
.Utils
.format_task_description(type
, id
);
761 render_uptime: function(value
) {
764 if (uptime
=== undefined) {
772 return Proxmox
.Utils
.format_duration_long(uptime
);
775 systemd_unescape: function(string_value
) {
776 const charcode_0
= '0'.charCodeAt(0);
777 const charcode_9
= '9'.charCodeAt(0);
778 const charcode_A
= 'A'.charCodeAt(0);
779 const charcode_F
= 'F'.charCodeAt(0);
780 const charcode_a
= 'a'.charCodeAt(0);
781 const charcode_f
= 'f'.charCodeAt(0);
782 const charcode_x
= 'x'.charCodeAt(0);
783 const charcode_minus
= '-'.charCodeAt(0);
784 const charcode_slash
= '/'.charCodeAt(0);
785 const charcode_backslash
= '\\'.charCodeAt(0);
787 let parse_hex_digit = function(d
) {
788 if (d
>= charcode_0
&& d
<= charcode_9
) {
789 return d
- charcode_0
;
791 if (d
>= charcode_A
&& d
<= charcode_F
) {
792 return d
- charcode_A
+ 10;
794 if (d
>= charcode_a
&& d
<= charcode_f
) {
795 return d
- charcode_a
+ 10;
797 throw "got invalid hex digit";
800 let value
= new TextEncoder().encode(string_value
);
801 let result
= new Uint8Array(value
.length
);
806 while (i
< value
.length
) {
808 if (c0
=== charcode_minus
) {
809 result
.set([charcode_slash
], result_len
);
814 if ((i
+ 4) < value
.length
) {
816 if (c0
=== charcode_backslash
&& c1
=== charcode_x
) {
817 let h1
= parse_hex_digit(value
[i
+2]);
818 let h0
= parse_hex_digit(value
[i
+3]);
820 result
.set([ord
], result_len
);
826 result
.set([c0
], result_len
);
831 return new TextDecoder().decode(result
.slice(0, result
.len
));
834 parse_task_upid: function(upid
) {
837 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]+):$/);
839 throw "unable to parse upid '" + upid
+ "'";
842 task
.pid
= parseInt(res
[2], 16);
843 task
.pstart
= parseInt(res
[3], 16);
844 if (res
[5] !== undefined) {
845 task
.task_id
= parseInt(res
[5], 16);
847 task
.starttime
= parseInt(res
[6], 16);
849 task
.id
= Proxmox
.Utils
.systemd_unescape(res
[8]);
852 task
.desc
= Proxmox
.Utils
.format_task_description(task
.type
, task
.id
);
857 parse_task_status: function(status
) {
858 if (status
=== 'OK') {
862 if (status
=== 'unknown') {
866 let match
= status
.match(/^WARNINGS: (.*)$/);
874 format_task_status: function(status
) {
875 let parsed
= Proxmox
.Utils
.parse_task_status(status
);
877 case 'unknown': return Proxmox
.Utils
.unknownText
;
878 case 'error': return Proxmox
.Utils
.errorText
+ ': ' + status
;
879 case 'warning': return status
.replace('WARNINGS', Proxmox
.Utils
.warningsText
);
880 case 'ok': // fall-through
881 default: return status
;
885 render_duration: function(value
) {
886 if (value
=== undefined) {
889 return Proxmox
.Utils
.format_duration_human(value
);
892 render_timestamp: function(value
, metaData
, record
, rowIndex
, colIndex
, store
) {
893 let servertime
= new Date(value
* 1000);
894 return Ext
.Date
.format(servertime
, 'Y-m-d H:i:s');
897 render_zfs_health: function(value
) {
898 if (typeof value
=== 'undefined') {
901 var iconCls
= 'question-circle';
905 iconCls
= 'check-circle good';
909 iconCls
= 'exclamation-circle warning';
914 iconCls
= 'times-circle critical';
919 return '<i class="fa fa-' + iconCls
+ '"></i> ' + value
;
922 get_help_info: function(section
) {
924 if (typeof proxmoxOnlineHelpInfo
!== 'undefined') {
925 helpMap
= proxmoxOnlineHelpInfo
; // eslint-disable-line no-undef
926 } else if (typeof pveOnlineHelpInfo
!== 'undefined') {
927 // be backward compatible with older pve-doc-generators
928 helpMap
= pveOnlineHelpInfo
; // eslint-disable-line no-undef
930 throw "no global OnlineHelpInfo map declared";
933 if (helpMap
[section
]) {
934 return helpMap
[section
];
936 // try to normalize - and _ separators, to support asciidoc and sphinx
937 // references at the same time.
938 let section_minus_normalized
= section
.replace(/_
/g
, '-');
939 if (helpMap
[section_minus_normalized
]) {
940 return helpMap
[section_minus_normalized
];
942 let section_underscore_normalized
= section
.replace(/-/g
, '_');
943 return helpMap
[section_underscore_normalized
];
946 get_help_link: function(section
) {
947 let info
= Proxmox
.Utils
.get_help_info(section
);
951 return window
.location
.origin
+ info
.link
;
954 openXtermJsViewer: function(vmtype
, vmid
, nodename
, vmname
, cmd
) {
955 let url
= Ext
.Object
.toQueryString({
956 console
: vmtype
, // kvm, lxc, upgrade or shell
964 let nw
= window
.open("?" + url
, '_blank', 'toolbar=no,location=no,status=no,menubar=no,resizable=yes,width=800,height=420');
970 render_optional_url: function(value
) {
971 if (value
&& value
.match(/^https?:\/\//) !== null) {
972 return '<a target="_blank" href="' + value
+ '">' + value
+ '</a>';
977 render_san: function(value
) {
979 if (Ext
.isArray(value
)) {
980 value
.forEach(function(val
) {
981 if (!Ext
.isNumber(val
)) {
985 return names
.join('<br>');
990 render_usage
: val
=> (val
* 100).toFixed(2) + '%',
992 render_cpu_usage: function(val
, max
) {
993 return Ext
.String
.format(
994 `${gettext('{0}% of {1}')} ${gettext('CPU(s)')}`,
995 (val
*100).toFixed(2),
1000 render_size_usage: function(val
, max
, useSI
) {
1002 return gettext('N/A');
1004 let fmt
= v
=> Proxmox
.Utils
.format_size(v
, useSI
);
1005 let ratio
= (val
* 100 / max
).toFixed(2);
1006 return ratio
+ '% (' + Ext
.String
.format(gettext('{0} of {1}'), fmt(val
), fmt(max
)) + ')';
1009 render_cpu: function(value
, metaData
, record
, rowIndex
, colIndex
, store
) {
1010 if (!(record
.data
.uptime
&& Ext
.isNumeric(value
))) {
1014 let maxcpu
= record
.data
.maxcpu
|| 1;
1015 if (!Ext
.isNumeric(maxcpu
) || maxcpu
< 1) {
1018 let cpuText
= maxcpu
> 1 ? 'CPUs' : 'CPU';
1019 let ratio
= (value
* 100).toFixed(1);
1020 return `${ratio}% of ${maxcpu.toString()} ${cpuText}`;
1023 render_size: function(value
, metaData
, record
, rowIndex
, colIndex
, store
) {
1024 if (!Ext
.isNumeric(value
)) {
1027 return Proxmox
.Utils
.format_size(value
);
1030 render_cpu_model: function(cpu
) {
1031 let socketText
= cpu
.sockets
> 1 ? gettext('Sockets') : gettext('Socket');
1032 return `${cpu.cpus} x ${cpu.model} (${cpu.sockets.toString()} ${socketText})`;
1035 /* this is different for nodes */
1036 render_node_cpu_usage: function(value
, record
) {
1037 return Proxmox
.Utils
.render_cpu_usage(value
, record
.cpus
);
1040 render_node_size_usage: function(record
) {
1041 return Proxmox
.Utils
.render_size_usage(record
.used
, record
.total
);
1044 loadTextFromFile: function(file
, callback
, maxBytes
) {
1045 let maxSize
= maxBytes
|| 8192;
1046 if (file
.size
> maxSize
) {
1047 Ext
.Msg
.alert(gettext('Error'), gettext("Invalid file size: ") + file
.size
);
1050 let reader
= new FileReader();
1051 reader
.onload
= evt
=> callback(evt
.target
.result
);
1052 reader
.readAsText(file
);
1055 parsePropertyString: function(value
, defaultKey
) {
1059 if (typeof value
!== 'string' || value
=== '') {
1063 Ext
.Array
.each(value
.split(','), function(p
) {
1064 var kv
= p
.split('=', 2);
1065 if (Ext
.isDefined(kv
[1])) {
1067 } else if (Ext
.isDefined(defaultKey
)) {
1068 if (Ext
.isDefined(res
[defaultKey
])) {
1069 error
= 'defaultKey may be only defined once in propertyString';
1070 return false; // break
1072 res
[defaultKey
] = kv
[0];
1074 error
= 'invalid propertyString, not a key=value pair and no defaultKey defined';
1075 return false; // break
1080 if (error
!== undefined) {
1081 console
.error(error
);
1088 printPropertyString: function(data
, defaultKey
) {
1089 var stringparts
= [],
1090 gotDefaultKeyVal
= false,
1093 Ext
.Object
.each(data
, function(key
, value
) {
1094 if (defaultKey
!== undefined && key
=== defaultKey
) {
1095 gotDefaultKeyVal
= true;
1096 defaultKeyVal
= value
;
1097 } else if (Ext
.isArray(value
)) {
1098 stringparts
.push(key
+ '=' + value
.join(';'));
1099 } else if (value
!== '') {
1100 stringparts
.push(key
+ '=' + value
);
1104 stringparts
= stringparts
.sort();
1105 if (gotDefaultKeyVal
) {
1106 stringparts
.unshift(defaultKeyVal
);
1109 return stringparts
.join(',');
1112 acmedomain_count
: 5,
1114 parseACMEPluginData: function(data
) {
1117 data
.split('\n').forEach((line
) => {
1118 // capture everything after the first = as value
1119 let [key
, value
] = line
.split('=');
1120 if (value
!== undefined) {
1123 extradata
.push(line
);
1126 return [res
, extradata
];
1129 delete_if_default: function(values
, fieldname
, default_val
, create
) {
1130 if (values
[fieldname
] === '' || values
[fieldname
] === default_val
) {
1132 if (values
.delete) {
1133 if (Ext
.isArray(values
.delete)) {
1134 values
.delete.push(fieldname
);
1136 values
.delete += ',' + fieldname
;
1139 values
.delete = fieldname
;
1143 delete values
[fieldname
];
1147 printACME: function(value
) {
1148 if (Ext
.isArray(value
.domains
)) {
1149 value
.domains
= value
.domains
.join(';');
1151 return Proxmox
.Utils
.printPropertyString(value
);
1154 parseACME: function(value
) {
1162 Ext
.Array
.each(value
.split(','), function(p
) {
1163 var kv
= p
.split('=', 2);
1164 if (Ext
.isDefined(kv
[1])) {
1167 error
= 'Failed to parse key-value pair: '+p
;
1173 if (error
!== undefined) {
1174 console
.error(error
);
1178 if (res
.domains
!== undefined) {
1179 res
.domains
= res
.domains
.split(/;/);
1185 add_domain_to_acme: function(acme
, domain
) {
1186 if (acme
.domains
=== undefined) {
1187 acme
.domains
= [domain
];
1189 acme
.domains
.push(domain
);
1190 acme
.domains
= acme
.domains
.filter((value
, index
, self
) => self
.indexOf(value
) === index
);
1195 remove_domain_from_acme: function(acme
, domain
) {
1196 if (acme
.domains
!== undefined) {
1197 acme
.domains
= acme
.domains
.filter(
1198 (value
, index
, self
) => self
.indexOf(value
) === index
&& value
!== domain
,
1204 get_health_icon: function(state
, circle
) {
1205 if (circle
=== undefined) {
1209 if (state
=== undefined) {
1213 var icon
= 'faded fa-question';
1216 icon
= 'good fa-check';
1219 icon
= 'warning fa-upload';
1222 icon
= 'warning fa-refresh';
1225 icon
= 'warning fa-exclamation';
1228 icon
= 'critical fa-times';
1240 formatNodeRepoStatus: function(status
, product
) {
1241 let fmt
= (txt
, cls
) => `<i class="fa fa-fw fa-lg fa-${cls}"></i>${txt}`;
1243 let getUpdates
= Ext
.String
.format(gettext('{0} updates'), product
);
1244 let noRepo
= Ext
.String
.format(gettext('No {0} repository enabled!'), product
);
1246 if (status
=== 'ok') {
1247 return fmt(getUpdates
, 'check-circle good') + ' ' +
1248 fmt(gettext('Production-ready Enterprise repository enabled'), 'check-circle good');
1249 } else if (status
=== 'no-sub') {
1250 return fmt(gettext('Production-ready Enterprise repository enabled'), 'check-circle good') + ' ' +
1251 fmt(gettext('Enterprise repository needs valid subscription'), 'exclamation-circle warning');
1252 } else if (status
=== 'non-production') {
1253 return fmt(getUpdates
, 'check-circle good') + ' ' +
1254 fmt(gettext('Non production-ready repository enabled!'), 'exclamation-circle warning');
1255 } else if (status
=== 'no-repo') {
1256 return fmt(noRepo
, 'exclamation-circle critical');
1259 return Proxmox
.Utils
.unknownText
;
1262 render_u2f_error: function(error
) {
1264 '1': gettext('Other Error'),
1265 '2': gettext('Bad Request'),
1266 '3': gettext('Configuration Unsupported'),
1267 '4': gettext('Device Ineligible'),
1268 '5': gettext('Timeout'),
1270 return "U2F Error: " + ErrorNames
[error
] || Proxmox
.Utils
.unknownText
;
1273 // Convert an ArrayBuffer to a base64url encoded string.
1274 // A `null` value will be preserved for convenience.
1275 bytes_to_base64url: function(bytes
) {
1276 if (bytes
=== null) {
1281 .from(new Uint8Array(bytes
))
1282 .map(val
=> String
.fromCharCode(val
))
1285 .replace(/\+/g, '-')
1286 .replace(/\//g, '_')
1287 .replace(/[=]/g, '');
1290 // Convert an a base64url string to an ArrayBuffer.
1291 // A `null` value will be preserved for convenience.
1292 base64url_to_bytes: function(b64u
) {
1293 if (b64u
=== null) {
1297 return new Uint8Array(
1300 .replace(/_/g, '/'),
1303 .map(val => val.charCodeAt(0)),
1307 stringToRGB: function(string) {
1312 string += 'prox
'; // give short strings more variance
1313 for (let i = 0; i < string.length; i++) {
1314 hash = string.charCodeAt(i) + ((hash << 5) - hash);
1315 hash = hash & hash; // to int
1318 let alpha = 0.7; // make the color a bit brighter
1319 let bg = 255; // assume white background
1322 (hash & 255) * alpha + bg * (1 - alpha),
1323 ((hash >> 8) & 255) * alpha + bg * (1 - alpha),
1324 ((hash >> 16) & 255) * alpha + bg * (1 - alpha),
1328 rgbToCss: function(rgb) {
1329 return `rgb(${rgb[0]}, ${rgb[1]}, ${rgb[2]})`;
1332 rgbToHex: function(rgb) {
1333 let r = Math.round(rgb[0]).toString(16);
1334 let g = Math.round(rgb[1]).toString(16);
1335 let b = Math.round(rgb[2]).toString(16);
1336 return `${r}${g}${b}`;
1339 hexToRGB: function(hex) {
1343 if (hex.length === 7) {
1346 let r = parseInt(hex.slice(0, 2), 16);
1347 let g = parseInt(hex.slice(2, 4), 16);
1348 let b = parseInt(hex.slice(4, 6), 16);
1352 // optimized & simplified SAPC function
1353 // https://github.com/Myndex/SAPC-APCA
1354 getTextContrastClass: function(rgb) {
1355 const blkThrs = 0.022;
1356 const blkClmp = 1.414;
1358 // linearize & gamma correction
1359 let r = (rgb[0] / 255) ** 2.4;
1360 let g = (rgb[1] / 255) ** 2.4;
1361 let b = (rgb[2] / 255) ** 2.4;
1363 // relative luminance sRGB
1364 let bg = r * 0.2126729 + g * 0.7151522 + b * 0.0721750;
1367 bg = bg > blkThrs ? bg : bg + (blkThrs - bg) ** blkClmp;
1369 // SAPC with white text
1370 let contrastLight = bg ** 0.65 - 1;
1371 // SAPC with black text
1372 let contrastDark = bg ** 0.56 - 0.046134502;
1374 if (Math.abs(contrastLight) >= Math.abs(contrastDark)) {
1381 getTagElement: function(string, color_overrides) {
1382 let rgb = color_overrides?.[string] || Proxmox.Utils.stringToRGB(string);
1383 let style = `background-color: ${Proxmox.Utils.rgbToCss(rgb)};`;
1385 if (rgb.length > 3) {
1386 style += `color: ${Proxmox.Utils.rgbToCss([rgb[3], rgb[4], rgb[5]])}`;
1387 cls = "proxmox-tag-dark";
1389 let txtCls = Proxmox.Utils.getTextContrastClass(rgb);
1390 cls = `proxmox-tag-${txtCls}`;
1392 return `<span class="${cls}" style="${style}">${string}</span>`;
1395 // Setting filename here when downloading from a remote url sometimes fails in chromium browsers
1396 // because of a bug when using attribute download in conjunction with a self signed certificate.
1397 // For more info see https://bugs.chromium.org/p/chromium/issues/detail?id=993362
1398 downloadAsFile: function(source, fileName) {
1399 let hiddenElement = document.createElement('a
');
1400 hiddenElement.href = source;
1401 hiddenElement.target = '_blank
';
1403 hiddenElement.download = fileName;
1405 hiddenElement.click();
1410 constructor: function() {
1412 Ext.apply(me, me.utilities);
1414 let IPV4_OCTET = "(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])";
1415 let IPV4_REGEXP = "(?:(?:" + IPV4_OCTET + "\\.){3}" + IPV4_OCTET + ")";
1416 let IPV6_H16 = "(?:[0-9a-fA-F]{1,4})";
1417 let IPV6_LS32 = "(?:(?:" + IPV6_H16 + ":" + IPV6_H16 + ")|" + IPV4_REGEXP + ")";
1418 let IPV4_CIDR_MASK = "([0-9]{1,2})";
1419 let IPV6_CIDR_MASK = "([0-9]{1,3})";
1422 me.IP4_match = new RegExp("^(?:" + IPV4_REGEXP + ")$");
1423 me.IP4_cidr_match = new RegExp("^(?:" + IPV4_REGEXP + ")/" + IPV4_CIDR_MASK + "$");
1425 /* eslint-disable no-useless-concat,no-multi-spaces */
1426 let IPV6_REGEXP = "(?:" +
1427 "(?:(?:" + "(?:" + IPV6_H16 + ":){6})" + IPV6_LS32 + ")|" +
1428 "(?:(?:" + "::" + "(?:" + IPV6_H16 + ":){5})" + IPV6_LS32 + ")|" +
1429 "(?:(?:(?:" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){4})" + IPV6_LS32 + ")|" +
1430 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,1}" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){3})" + IPV6_LS32 + ")|" +
1431 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,2}" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){2})" + IPV6_LS32 + ")|" +
1432 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,3}" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){1})" + IPV6_LS32 + ")|" +
1433 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,4}" + IPV6_H16 + ")?::" + ")" + IPV6_LS32 + ")|" +
1434 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,5}" + IPV6_H16 + ")?::" + ")" + IPV6_H16 + ")|" +
1435 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,7}" + IPV6_H16 + ")?::" + ")" + ")" +
1437 /* eslint-enable no-useless-concat,no-multi-spaces */
1439 me.IP6_match = new RegExp("^(?:" + IPV6_REGEXP + ")$");
1440 me.IP6_cidr_match = new RegExp("^(?:" + IPV6_REGEXP + ")/" + IPV6_CIDR_MASK + "$");
1441 me.IP6_bracket_match = new RegExp("^\\[(" + IPV6_REGEXP + ")\\]");
1443 me.IP64_match = new RegExp("^(?:" + IPV6_REGEXP + "|" + IPV4_REGEXP + ")$");
1444 me.IP64_cidr_match = new RegExp("^(?:" + IPV6_REGEXP + "/" + IPV6_CIDR_MASK + ")|(?:" + IPV4_REGEXP + "/" + IPV4_CIDR_MASK + ")$");
1446 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])?))";
1447 me.DnsName_match = new RegExp("^" + DnsName_REGEXP + "$");
1448 me.DnsName_or_Wildcard_match = new RegExp("^(?:\\*\\.)?" + DnsName_REGEXP + "$");
1450 me.CpuSet_match = /^[0-9]+(?:-[0-9]+)?(?:,[0-9]+(?:-[0-9]+)?)*$/;
1452 me.HostPort_match = new RegExp("^(" + IPV4_REGEXP + "|" + DnsName_REGEXP + ")(?::(\\d+))?$");
1453 me.HostPortBrackets_match = new RegExp("^\\[(" + IPV6_REGEXP + "|" + IPV4_REGEXP + "|" + DnsName_REGEXP + ")\\](?::(\\d+))?$");
1454 me.IP6_dotnotation_match = new RegExp("^(" + IPV6_REGEXP + ")(?:\\.(\\d+))?$");
1455 me.Vlan_match = /^vlan(\d+)/;
1456 me.VlanInterface_match = /(\w+)\.(\d+)/;
1460 Ext.define('Proxmox
.Async
', {
1463 // Returns a Promise resolving to the result of an `API2Request` or rejecting to the error
1464 // response on failure
1465 api2: function(reqOpts) {
1466 return new Promise((resolve, reject) => {
1467 delete reqOpts.callback; // not allowed in this api
1468 reqOpts.success = response => resolve(response);
1469 reqOpts.failure = response => reject(response);
1470 Proxmox.Utils.API2Request(reqOpts);
1474 // Delay for a number of milliseconds.
1475 sleep: function(millis) {
1476 return new Promise((resolve, _reject) => setTimeout(resolve, millis));
1480 Ext.override(Ext.data.Store, {
1481 // If the store's proxy is changed
while it is waiting
for an AJAX
1482 // response, `onProxyLoad` will still be called for the outdated response.
1483 // To avoid displaying inconsistent information, only process responses
1484 // belonging to the current proxy.
1485 onProxyLoad: function(operation
) {
1487 if (operation
.getProxy() === me
.getProxy()) {
1488 me
.callParent(arguments
);
1490 console
.log(`ignored outdated response: ${operation.getRequest().getUrl()}`);