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 Ext
.util
.Cookies
.clear(Proxmox
.Setup
.auth_cookie_name
);
310 window
.localStorage
.removeItem("ProxmoxUser");
313 // The End-User gets redirected back here after login on the OpenID auth. portal, and in the
314 // redirection URL the state and auth.code are passed as URL GET params, this helper parses those
315 getOpenIDRedirectionAuthorization: function() {
316 const auth
= Ext
.Object
.fromQueryString(window
.location
.search
);
317 if (auth
.state
!== undefined && auth
.code
!== undefined) {
323 // comp.setLoading() is buggy in ExtJS 4.0.7, so we
324 // use el.mask() instead
325 setErrorMask: function(comp
, msg
) {
332 } else if (msg
=== true) {
333 el
.mask(gettext("Loading..."));
339 getResponseErrorMessage
: (err
) => {
340 if (!err
.statusText
) {
341 return gettext('Connection error');
343 let msg
= [`${err.statusText} (${err.status})`];
344 if (err
.response
&& err
.response
.responseText
) {
345 let txt
= err
.response
.responseText
;
347 let res
= JSON
.parse(txt
);
348 if (res
.errors
&& typeof res
.errors
=== 'object') {
349 for (let [key
, value
] of Object
.entries(res
.errors
)) {
350 msg
.push(Ext
.String
.htmlEncode(`${key}: ${value}`));
354 // fallback to string
355 msg
.push(Ext
.String
.htmlEncode(txt
));
358 return msg
.join('<br>');
361 monStoreErrors: function(component
, store
, clearMaskBeforeLoad
, errorCallback
) {
362 if (clearMaskBeforeLoad
) {
363 component
.mon(store
, 'beforeload', function(s
, operation
, eOpts
) {
364 Proxmox
.Utils
.setErrorMask(component
, false);
367 component
.mon(store
, 'beforeload', function(s
, operation
, eOpts
) {
368 if (!component
.loadCount
) {
369 component
.loadCount
= 0; // make sure it is nucomponent.ic
370 Proxmox
.Utils
.setErrorMask(component
, true);
375 // only works with 'proxmox' proxy
376 component
.mon(store
.proxy
, 'afterload', function(proxy
, request
, success
) {
377 component
.loadCount
++;
380 Proxmox
.Utils
.setErrorMask(component
, false);
384 let error
= request
._operation
.getError();
385 let msg
= Proxmox
.Utils
.getResponseErrorMessage(error
);
386 if (!errorCallback
|| !errorCallback(error
, msg
)) {
387 Proxmox
.Utils
.setErrorMask(component
, msg
);
392 extractRequestError: function(result
, verbose
) {
393 let msg
= gettext('Successful');
395 if (!result
.success
) {
396 msg
= gettext("Unknown error");
397 if (result
.message
) {
398 msg
= result
.message
;
400 msg
+= ' (' + result
.status
+ ')';
403 if (verbose
&& Ext
.isObject(result
.errors
)) {
405 Ext
.Object
.each(result
.errors
, function(prop
, desc
) {
406 msg
+= "<br><b>" + Ext
.htmlEncode(prop
) + "</b>: " +
407 Ext
.htmlEncode(desc
);
416 API2Request: function(reqOpts
) {
417 let newopts
= Ext
.apply({
418 waitMsg
: gettext('Please wait...'),
421 if (!newopts
.url
.match(/^\/api2/)) {
422 newopts
.url
= '/api2/extjs' + newopts
.url
;
424 delete newopts
.callback
;
426 let createWrapper = function(successFn
, callbackFn
, failureFn
) {
428 success: function(response
, options
) {
429 if (options
.waitMsgTarget
) {
430 if (Proxmox
.Utils
.toolkit
=== 'touch') {
431 options
.waitMsgTarget
.setMasked(false);
433 options
.waitMsgTarget
.setLoading(false);
436 let result
= Ext
.decode(response
.responseText
);
437 response
.result
= result
;
438 if (!result
.success
) {
439 response
.htmlStatus
= Proxmox
.Utils
.extractRequestError(result
, true);
440 Ext
.callback(callbackFn
, options
.scope
, [options
, false, response
]);
441 Ext
.callback(failureFn
, options
.scope
, [response
, options
]);
444 Ext
.callback(callbackFn
, options
.scope
, [options
, true, response
]);
445 Ext
.callback(successFn
, options
.scope
, [response
, options
]);
447 failure: function(response
, options
) {
448 if (options
.waitMsgTarget
) {
449 if (Proxmox
.Utils
.toolkit
=== 'touch') {
450 options
.waitMsgTarget
.setMasked(false);
452 options
.waitMsgTarget
.setLoading(false);
455 response
.result
= {};
457 response
.result
= Ext
.decode(response
.responseText
);
461 let msg
= gettext('Connection error') + ' - server offline?';
462 if (response
.aborted
) {
463 msg
= gettext('Connection error') + ' - aborted.';
464 } else if (response
.timedout
) {
465 msg
= gettext('Connection error') + ' - Timeout.';
466 } else if (response
.status
&& response
.statusText
) {
467 msg
= gettext('Connection error') + ' ' + response
.status
+ ': ' + response
.statusText
;
469 response
.htmlStatus
= msg
;
470 Ext
.callback(callbackFn
, options
.scope
, [options
, false, response
]);
471 Ext
.callback(failureFn
, options
.scope
, [response
, options
]);
476 createWrapper(reqOpts
.success
, reqOpts
.callback
, reqOpts
.failure
);
478 let target
= newopts
.waitMsgTarget
;
480 if (Proxmox
.Utils
.toolkit
=== 'touch') {
481 target
.setMasked({ xtype
: 'loadmask', message
: newopts
.waitMsg
});
483 // Note: ExtJS bug - this does not work when component is not rendered
484 target
.setLoading(newopts
.waitMsg
);
487 Ext
.Ajax
.request(newopts
);
490 // can be useful for catching displaying errors from the API, e.g.:
491 // Proxmox.Async.api2({
493 // }).catch(Proxmox.Utils.alertResponseFailure);
494 alertResponseFailure
: (response
) => {
497 response
.htmlStatus
|| response
.result
.message
,
501 checked_command: function(orig_cmd
) {
502 Proxmox
.Utils
.API2Request(
504 url
: '/nodes/localhost/subscription',
506 failure: function(response
, opts
) {
507 Ext
.Msg
.alert(gettext('Error'), response
.htmlStatus
);
509 success: function(response
, opts
) {
510 let res
= response
.result
;
511 if (res
=== null || res
=== undefined || !res
|| res
512 .data
.status
.toLowerCase() !== 'active') {
514 title
: gettext('No valid subscription'),
515 icon
: Ext
.Msg
.WARNING
,
516 message
: Proxmox
.Utils
.getNoSubKeyHtml(res
.data
.url
),
518 callback: function(btn
) {
533 assemble_field_data: function(values
, data
) {
534 if (!Ext
.isObject(data
)) {
537 Ext
.Object
.each(data
, function(name
, val
) {
538 if (Object
.prototype.hasOwnProperty
.call(values
, name
)) {
539 let bucket
= values
[name
];
540 if (!Ext
.isArray(bucket
)) {
541 bucket
= values
[name
] = [bucket
];
543 if (Ext
.isArray(val
)) {
544 values
[name
] = bucket
.concat(val
);
554 updateColumnWidth: function(container
, thresholdWidth
) {
555 let mode
= Ext
.state
.Manager
.get('summarycolumns') || 'auto';
557 if (mode
!== 'auto') {
558 factor
= parseInt(mode
, 10);
559 if (Number
.isNaN(factor
)) {
563 thresholdWidth
= (thresholdWidth
|| 1400) + 1;
564 factor
= Math
.ceil(container
.getSize().width
/ thresholdWidth
);
567 if (container
.oldFactor
=== factor
) {
571 let items
= container
.query('>'); // direct children
572 factor
= Math
.min(factor
, items
.length
);
573 container
.oldFactor
= factor
;
575 items
.forEach((item
) => {
576 item
.columnWidth
= 1 / factor
;
579 // we have to update the layout twice, since the first layout change
580 // can trigger the scrollbar which reduces the amount of space left
581 container
.updateLayout();
582 container
.updateLayout();
585 // NOTE: depreacated, use updateColumnWidth
586 updateColumns
: container
=> Proxmox
.Utils
.updateColumnWidth(container
),
588 dialog_title: function(subject
, create
, isAdd
) {
591 return gettext('Add') + ': ' + subject
;
593 return gettext('Create') + ': ' + subject
;
596 return gettext('Edit') + ': ' + subject
;
600 network_iface_types
: {
601 eth
: gettext("Network Device"),
602 bridge
: 'Linux Bridge',
605 OVSBridge
: 'OVS Bridge',
608 OVSIntPort
: 'OVS IntPort',
611 render_network_iface_type: function(value
) {
612 return Proxmox
.Utils
.network_iface_types
[value
] ||
613 Proxmox
.Utils
.unknownText
;
616 // NOTE: only add general, product agnostic, ones here! Else use override helper in product repos
618 aptupdate
: ['', gettext('Update package database')],
619 diskinit
: ['Disk', gettext('Initialize Disk with GPT')],
620 spiceshell
: ['', gettext('Shell') + ' (Spice)'],
621 srvreload
: ['SRV', gettext('Reload')],
622 srvrestart
: ['SRV', gettext('Restart')],
623 srvstart
: ['SRV', gettext('Start')],
624 srvstop
: ['SRV', gettext('Stop')],
625 termproxy
: ['', gettext('Console') + ' (xterm.js)'],
626 vncshell
: ['', gettext('Shell')],
629 // to add or change existing for product specific ones
630 override_task_descriptions: function(extra
) {
631 for (const [key
, value
] of Object
.entries(extra
)) {
632 Proxmox
.Utils
.task_desc_table
[key
] = value
;
636 format_task_description: function(type
, id
) {
637 let farray
= Proxmox
.Utils
.task_desc_table
[type
];
645 } else if (Ext
.isFunction(farray
)) {
646 return farray(type
, id
);
648 let prefix
= farray
[0];
650 if (prefix
&& id
!== undefined) {
651 return prefix
+ ' ' + id
+ ' - ' + text
;
656 format_size: function(size
, useSI
) {
657 let units
= ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'];
659 const baseValue
= useSI
? 1000 : 1024;
660 while (size
>= baseValue
&& order
< units
.length
) {
661 size
= size
/ baseValue
;
665 let unit
= units
[order
], commaDigits
= 2;
671 return `${size.toFixed(commaDigits)} ${unit}B`;
679 'GiB': 1024*1024*1024,
680 'TiB': 1024*1024*1024*1024,
681 'PiB': 1024*1024*1024*1024*1024,
685 'GB': 1000*1000*1000,
686 'TB': 1000*1000*1000*1000,
687 'PB': 1000*1000*1000*1000*1000,
690 parse_size_unit: function(val
) {
691 //let m = val.match(/([.\d])+\s?([KMGTP]?)(i?)B?\s*$/i);
692 let m
= val
.match(/(\d+(?:\.\d+)?)\s?([KMGTP]?)(i?)B?\s*$/i);
693 let size
= parseFloat(m
[1]);
694 let scale
= m
[2].toUpperCase();
695 let binary
= m
[3].toLowerCase();
697 let unit
= `${scale}${binary}B`;
698 let factor
= Proxmox
.Utils
.SizeUnits
[unit
];
700 return { size
, factor
, unit
, binary
}; // for convenience return all we got
703 size_unit_to_bytes: function(val
) {
704 let { size
, factor
} = Proxmox
.Utils
.parse_size_unit(val
);
705 return size
* factor
;
708 autoscale_size_unit: function(val
) {
709 let { size
, factor
, binary
} = Proxmox
.Utils
.parse_size_unit(val
);
710 return Proxmox
.Utils
.format_size(size
* factor
, binary
!== "i");
713 size_unit_ratios: function(a
, b
) {
714 a
= typeof a
!== "undefined" ? a
: 0;
715 b
= typeof b
!== "undefined" ? b
: Infinity
;
716 let aBytes
= typeof a
=== "number" ? a
: Proxmox
.Utils
.size_unit_to_bytes(a
);
717 let bBytes
= typeof b
=== "number" ? b
: Proxmox
.Utils
.size_unit_to_bytes(b
);
718 return aBytes
/ (bBytes
|| Infinity
); // avoid division by zero
721 render_upid: function(value
, metaData
, record
) {
722 let task
= record
.data
;
723 let type
= task
.type
|| task
.worker_type
;
724 let id
= task
.id
|| task
.worker_id
;
726 return Proxmox
.Utils
.format_task_description(type
, id
);
729 render_uptime: function(value
) {
732 if (uptime
=== undefined) {
740 return Proxmox
.Utils
.format_duration_long(uptime
);
743 systemd_unescape: function(string_value
) {
744 const charcode_0
= '0'.charCodeAt(0);
745 const charcode_9
= '9'.charCodeAt(0);
746 const charcode_A
= 'A'.charCodeAt(0);
747 const charcode_F
= 'F'.charCodeAt(0);
748 const charcode_a
= 'a'.charCodeAt(0);
749 const charcode_f
= 'f'.charCodeAt(0);
750 const charcode_x
= 'x'.charCodeAt(0);
751 const charcode_minus
= '-'.charCodeAt(0);
752 const charcode_slash
= '/'.charCodeAt(0);
753 const charcode_backslash
= '\\'.charCodeAt(0);
755 let parse_hex_digit = function(d
) {
756 if (d
>= charcode_0
&& d
<= charcode_9
) {
757 return d
- charcode_0
;
759 if (d
>= charcode_A
&& d
<= charcode_F
) {
760 return d
- charcode_A
+ 10;
762 if (d
>= charcode_a
&& d
<= charcode_f
) {
763 return d
- charcode_a
+ 10;
765 throw "got invalid hex digit";
768 let value
= new TextEncoder().encode(string_value
);
769 let result
= new Uint8Array(value
.length
);
774 while (i
< value
.length
) {
776 if (c0
=== charcode_minus
) {
777 result
.set([charcode_slash
], result_len
);
782 if ((i
+ 4) < value
.length
) {
784 if (c0
=== charcode_backslash
&& c1
=== charcode_x
) {
785 let h1
= parse_hex_digit(value
[i
+2]);
786 let h0
= parse_hex_digit(value
[i
+3]);
788 result
.set([ord
], result_len
);
794 result
.set([c0
], result_len
);
799 return new TextDecoder().decode(result
.slice(0, result
.len
));
802 parse_task_upid: function(upid
) {
805 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]+):$/);
807 throw "unable to parse upid '" + upid
+ "'";
810 task
.pid
= parseInt(res
[2], 16);
811 task
.pstart
= parseInt(res
[3], 16);
812 if (res
[5] !== undefined) {
813 task
.task_id
= parseInt(res
[5], 16);
815 task
.starttime
= parseInt(res
[6], 16);
817 task
.id
= Proxmox
.Utils
.systemd_unescape(res
[8]);
820 task
.desc
= Proxmox
.Utils
.format_task_description(task
.type
, task
.id
);
825 parse_task_status: function(status
) {
826 if (status
=== 'OK') {
830 if (status
=== 'unknown') {
834 let match
= status
.match(/^WARNINGS: (.*)$/);
842 format_task_status: function(status
) {
843 let parsed
= Proxmox
.Utils
.parse_task_status(status
);
845 case 'unknown': return Proxmox
.Utils
.unknownText
;
846 case 'error': return Proxmox
.Utils
.errorText
+ ': ' + status
;
847 case 'warning': return status
.replace('WARNINGS', Proxmox
.Utils
.warningsText
);
848 case 'ok': // fall-through
849 default: return status
;
853 render_duration: function(value
) {
854 if (value
=== undefined) {
857 return Proxmox
.Utils
.format_duration_human(value
);
860 render_timestamp: function(value
, metaData
, record
, rowIndex
, colIndex
, store
) {
861 let servertime
= new Date(value
* 1000);
862 return Ext
.Date
.format(servertime
, 'Y-m-d H:i:s');
865 render_zfs_health: function(value
) {
866 if (typeof value
=== 'undefined') {
869 var iconCls
= 'question-circle';
873 iconCls
= 'check-circle good';
877 iconCls
= 'exclamation-circle warning';
882 iconCls
= 'times-circle critical';
887 return '<i class="fa fa-' + iconCls
+ '"></i> ' + value
;
890 get_help_info: function(section
) {
892 if (typeof proxmoxOnlineHelpInfo
!== 'undefined') {
893 helpMap
= proxmoxOnlineHelpInfo
; // eslint-disable-line no-undef
894 } else if (typeof pveOnlineHelpInfo
!== 'undefined') {
895 // be backward compatible with older pve-doc-generators
896 helpMap
= pveOnlineHelpInfo
; // eslint-disable-line no-undef
898 throw "no global OnlineHelpInfo map declared";
901 if (helpMap
[section
]) {
902 return helpMap
[section
];
904 // try to normalize - and _ separators, to support asciidoc and sphinx
905 // references at the same time.
906 let section_minus_normalized
= section
.replace(/_
/g
, '-');
907 if (helpMap
[section_minus_normalized
]) {
908 return helpMap
[section_minus_normalized
];
910 let section_underscore_normalized
= section
.replace(/-/g
, '_');
911 return helpMap
[section_underscore_normalized
];
914 get_help_link: function(section
) {
915 let info
= Proxmox
.Utils
.get_help_info(section
);
919 return window
.location
.origin
+ info
.link
;
922 openXtermJsViewer: function(vmtype
, vmid
, nodename
, vmname
, cmd
) {
923 let url
= Ext
.Object
.toQueryString({
924 console
: vmtype
, // kvm, lxc, upgrade or shell
932 let nw
= window
.open("?" + url
, '_blank', 'toolbar=no,location=no,status=no,menubar=no,resizable=yes,width=800,height=420');
938 render_optional_url: function(value
) {
939 if (value
&& value
.match(/^https?:\/\//) !== null) {
940 return '<a target="_blank" href="' + value
+ '">' + value
+ '</a>';
945 render_san: function(value
) {
947 if (Ext
.isArray(value
)) {
948 value
.forEach(function(val
) {
949 if (!Ext
.isNumber(val
)) {
953 return names
.join('<br>');
958 render_usage
: val
=> (val
* 100).toFixed(2) + '%',
960 render_cpu_usage: function(val
, max
) {
961 return Ext
.String
.format(
962 `${gettext('{0}% of {1}')} ${gettext('CPU(s)')}`,
963 (val
*100).toFixed(2),
968 render_size_usage: function(val
, max
, useSI
) {
970 return gettext('N/A');
972 let fmt
= v
=> Proxmox
.Utils
.format_size(v
, useSI
);
973 let ratio
= (val
* 100 / max
).toFixed(2);
974 return ratio
+ '% (' + Ext
.String
.format(gettext('{0} of {1}'), fmt(val
), fmt(max
)) + ')';
977 render_cpu: function(value
, metaData
, record
, rowIndex
, colIndex
, store
) {
978 if (!(record
.data
.uptime
&& Ext
.isNumeric(value
))) {
982 let maxcpu
= record
.data
.maxcpu
|| 1;
983 if (!Ext
.isNumeric(maxcpu
) || maxcpu
< 1) {
986 let cpuText
= maxcpu
> 1 ? 'CPUs' : 'CPU';
987 let ratio
= (value
* 100).toFixed(1);
988 return `${ratio}% of ${maxcpu.toString()} ${cpuText}`;
991 render_size: function(value
, metaData
, record
, rowIndex
, colIndex
, store
) {
992 if (!Ext
.isNumeric(value
)) {
995 return Proxmox
.Utils
.format_size(value
);
998 render_cpu_model: function(cpu
) {
999 let socketText
= cpu
.sockets
> 1 ? gettext('Sockets') : gettext('Socket');
1000 return `${cpu.cpus} x ${cpu.model} (${cpu.sockets.toString()} ${socketText})`;
1003 /* this is different for nodes */
1004 render_node_cpu_usage: function(value
, record
) {
1005 return Proxmox
.Utils
.render_cpu_usage(value
, record
.cpus
);
1008 render_node_size_usage: function(record
) {
1009 return Proxmox
.Utils
.render_size_usage(record
.used
, record
.total
);
1012 loadTextFromFile: function(file
, callback
, maxBytes
) {
1013 let maxSize
= maxBytes
|| 8192;
1014 if (file
.size
> maxSize
) {
1015 Ext
.Msg
.alert(gettext('Error'), gettext("Invalid file size: ") + file
.size
);
1018 let reader
= new FileReader();
1019 reader
.onload
= evt
=> callback(evt
.target
.result
);
1020 reader
.readAsText(file
);
1023 parsePropertyString: function(value
, defaultKey
) {
1027 if (typeof value
!== 'string' || value
=== '') {
1031 Ext
.Array
.each(value
.split(','), function(p
) {
1032 var kv
= p
.split('=', 2);
1033 if (Ext
.isDefined(kv
[1])) {
1035 } else if (Ext
.isDefined(defaultKey
)) {
1036 if (Ext
.isDefined(res
[defaultKey
])) {
1037 error
= 'defaultKey may be only defined once in propertyString';
1038 return false; // break
1040 res
[defaultKey
] = kv
[0];
1042 error
= 'invalid propertyString, not a key=value pair and no defaultKey defined';
1043 return false; // break
1048 if (error
!== undefined) {
1049 console
.error(error
);
1056 printPropertyString: function(data
, defaultKey
) {
1057 var stringparts
= [],
1058 gotDefaultKeyVal
= false,
1061 Ext
.Object
.each(data
, function(key
, value
) {
1062 if (defaultKey
!== undefined && key
=== defaultKey
) {
1063 gotDefaultKeyVal
= true;
1064 defaultKeyVal
= value
;
1065 } else if (Ext
.isArray(value
)) {
1066 stringparts
.push(key
+ '=' + value
.join(';'));
1067 } else if (value
!== '') {
1068 stringparts
.push(key
+ '=' + value
);
1072 stringparts
= stringparts
.sort();
1073 if (gotDefaultKeyVal
) {
1074 stringparts
.unshift(defaultKeyVal
);
1077 return stringparts
.join(',');
1080 acmedomain_count
: 5,
1082 parseACMEPluginData: function(data
) {
1085 data
.split('\n').forEach((line
) => {
1086 // capture everything after the first = as value
1087 let [key
, value
] = line
.split('=');
1088 if (value
!== undefined) {
1091 extradata
.push(line
);
1094 return [res
, extradata
];
1097 delete_if_default: function(values
, fieldname
, default_val
, create
) {
1098 if (values
[fieldname
] === '' || values
[fieldname
] === default_val
) {
1100 if (values
.delete) {
1101 if (Ext
.isArray(values
.delete)) {
1102 values
.delete.push(fieldname
);
1104 values
.delete += ',' + fieldname
;
1107 values
.delete = fieldname
;
1111 delete values
[fieldname
];
1115 printACME: function(value
) {
1116 if (Ext
.isArray(value
.domains
)) {
1117 value
.domains
= value
.domains
.join(';');
1119 return Proxmox
.Utils
.printPropertyString(value
);
1122 parseACME: function(value
) {
1130 Ext
.Array
.each(value
.split(','), function(p
) {
1131 var kv
= p
.split('=', 2);
1132 if (Ext
.isDefined(kv
[1])) {
1135 error
= 'Failed to parse key-value pair: '+p
;
1141 if (error
!== undefined) {
1142 console
.error(error
);
1146 if (res
.domains
!== undefined) {
1147 res
.domains
= res
.domains
.split(/;/);
1153 add_domain_to_acme: function(acme
, domain
) {
1154 if (acme
.domains
=== undefined) {
1155 acme
.domains
= [domain
];
1157 acme
.domains
.push(domain
);
1158 acme
.domains
= acme
.domains
.filter((value
, index
, self
) => self
.indexOf(value
) === index
);
1163 remove_domain_from_acme: function(acme
, domain
) {
1164 if (acme
.domains
!== undefined) {
1165 acme
.domains
= acme
.domains
.filter(
1166 (value
, index
, self
) => self
.indexOf(value
) === index
&& value
!== domain
,
1172 get_health_icon: function(state
, circle
) {
1173 if (circle
=== undefined) {
1177 if (state
=== undefined) {
1181 var icon
= 'faded fa-question';
1184 icon
= 'good fa-check';
1187 icon
= 'warning fa-upload';
1190 icon
= 'warning fa-refresh';
1193 icon
= 'warning fa-exclamation';
1196 icon
= 'critical fa-times';
1208 formatNodeRepoStatus: function(status
, product
) {
1209 let fmt
= (txt
, cls
) => `<i class="fa fa-fw fa-lg fa-${cls}"></i>${txt}`;
1211 let getUpdates
= Ext
.String
.format(gettext('{0} updates'), product
);
1212 let noRepo
= Ext
.String
.format(gettext('No {0} repository enabled!'), product
);
1214 if (status
=== 'ok') {
1215 return fmt(getUpdates
, 'check-circle good') + ' ' +
1216 fmt(gettext('Production-ready Enterprise repository enabled'), 'check-circle good');
1217 } else if (status
=== 'no-sub') {
1218 return fmt(gettext('Production-ready Enterprise repository enabled'), 'check-circle good') + ' ' +
1219 fmt(gettext('Enterprise repository needs valid subscription'), 'exclamation-circle warning');
1220 } else if (status
=== 'non-production') {
1221 return fmt(getUpdates
, 'check-circle good') + ' ' +
1222 fmt(gettext('Non production-ready repository enabled!'), 'exclamation-circle warning');
1223 } else if (status
=== 'no-repo') {
1224 return fmt(noRepo
, 'exclamation-circle critical');
1227 return Proxmox
.Utils
.unknownText
;
1230 render_u2f_error: function(error
) {
1232 '1': gettext('Other Error'),
1233 '2': gettext('Bad Request'),
1234 '3': gettext('Configuration Unsupported'),
1235 '4': gettext('Device Ineligible'),
1236 '5': gettext('Timeout'),
1238 return "U2F Error: " + ErrorNames
[error
] || Proxmox
.Utils
.unknownText
;
1241 // Convert an ArrayBuffer to a base64url encoded string.
1242 // A `null` value will be preserved for convenience.
1243 bytes_to_base64url: function(bytes
) {
1244 if (bytes
=== null) {
1249 .from(new Uint8Array(bytes
))
1250 .map(val
=> String
.fromCharCode(val
))
1253 .replace(/\+/g, '-')
1254 .replace(/\//g, '_')
1255 .replace(/[=]/g, '');
1258 // Convert an a base64url string to an ArrayBuffer.
1259 // A `null` value will be preserved for convenience.
1260 base64url_to_bytes: function(b64u
) {
1261 if (b64u
=== null) {
1265 return new Uint8Array(
1268 .replace(/_/g, '/'),
1271 .map(val => val.charCodeAt(0)),
1277 constructor: function() {
1279 Ext.apply(me, me.utilities);
1281 let IPV4_OCTET = "(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])";
1282 let IPV4_REGEXP = "(?:(?:" + IPV4_OCTET + "\\.){3}" + IPV4_OCTET + ")";
1283 let IPV6_H16 = "(?:[0-9a-fA-F]{1,4})";
1284 let IPV6_LS32 = "(?:(?:" + IPV6_H16 + ":" + IPV6_H16 + ")|" + IPV4_REGEXP + ")";
1285 let IPV4_CIDR_MASK = "([0-9]{1,2})";
1286 let IPV6_CIDR_MASK = "([0-9]{1,3})";
1289 me.IP4_match = new RegExp("^(?:" + IPV4_REGEXP + ")$");
1290 me.IP4_cidr_match = new RegExp("^(?:" + IPV4_REGEXP + ")/" + IPV4_CIDR_MASK + "$");
1292 /* eslint-disable no-useless-concat,no-multi-spaces */
1293 let IPV6_REGEXP = "(?:" +
1294 "(?:(?:" + "(?:" + IPV6_H16 + ":){6})" + IPV6_LS32 + ")|" +
1295 "(?:(?:" + "::" + "(?:" + IPV6_H16 + ":){5})" + IPV6_LS32 + ")|" +
1296 "(?:(?:(?:" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){4})" + IPV6_LS32 + ")|" +
1297 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,1}" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){3})" + IPV6_LS32 + ")|" +
1298 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,2}" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){2})" + IPV6_LS32 + ")|" +
1299 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,3}" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){1})" + IPV6_LS32 + ")|" +
1300 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,4}" + IPV6_H16 + ")?::" + ")" + IPV6_LS32 + ")|" +
1301 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,5}" + IPV6_H16 + ")?::" + ")" + IPV6_H16 + ")|" +
1302 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,7}" + IPV6_H16 + ")?::" + ")" + ")" +
1304 /* eslint-enable no-useless-concat,no-multi-spaces */
1306 me.IP6_match = new RegExp("^(?:" + IPV6_REGEXP + ")$");
1307 me.IP6_cidr_match = new RegExp("^(?:" + IPV6_REGEXP + ")/" + IPV6_CIDR_MASK + "$");
1308 me.IP6_bracket_match = new RegExp("^\\[(" + IPV6_REGEXP + ")\\]");
1310 me.IP64_match = new RegExp("^(?:" + IPV6_REGEXP + "|" + IPV4_REGEXP + ")$");
1311 me.IP64_cidr_match = new RegExp("^(?:" + IPV6_REGEXP + "/" + IPV6_CIDR_MASK + ")|(?:" + IPV4_REGEXP + "/" + IPV4_CIDR_MASK + ")$");
1313 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])?))";
1314 me.DnsName_match = new RegExp("^" + DnsName_REGEXP + "$");
1315 me.DnsName_or_Wildcard_match = new RegExp("^(?:\\*\\.)?" + DnsName_REGEXP + "$");
1317 me.HostPort_match = new RegExp("^(" + IPV4_REGEXP + "|" + DnsName_REGEXP + ")(?::(\\d+))?$");
1318 me.HostPortBrackets_match = new RegExp("^\\[(" + IPV6_REGEXP + "|" + IPV4_REGEXP + "|" + DnsName_REGEXP + ")\\](?::(\\d+))?$");
1319 me.IP6_dotnotation_match = new RegExp("^(" + IPV6_REGEXP + ")(?:\\.(\\d+))?$");
1320 me.Vlan_match = /^vlan(\d+)/;
1321 me.VlanInterface_match = /(\w+)\.(\d+)/;
1325 Ext.define('Proxmox
.Async
', {
1328 // Returns a Promise resolving to the result of an `API2Request` or rejecting to the error
1329 // response on failure
1330 api2: function(reqOpts) {
1331 return new Promise((resolve, reject) => {
1332 delete reqOpts.callback; // not allowed in this api
1333 reqOpts.success = response => resolve(response);
1334 reqOpts.failure = response => reject(response);
1335 Proxmox.Utils.API2Request(reqOpts);
1339 // Delay for a number of milliseconds.
1340 sleep: function(millis) {
1341 return new Promise((resolve, _reject) => setTimeout(resolve, millis));