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
= result
.message
;
401 msg
+= ' (' + result
.status
+ ')';
404 if (verbose
&& Ext
.isObject(result
.errors
)) {
406 Ext
.Object
.each(result
.errors
, function(prop
, desc
) {
407 msg
+= "<br><b>" + Ext
.htmlEncode(prop
) + "</b>: " +
408 Ext
.htmlEncode(desc
);
417 API2Request: function(reqOpts
) {
418 let newopts
= Ext
.apply({
419 waitMsg
: gettext('Please wait...'),
422 if (!newopts
.url
.match(/^\/api2/)) {
423 newopts
.url
= '/api2/extjs' + newopts
.url
;
425 delete newopts
.callback
;
427 let createWrapper = function(successFn
, callbackFn
, failureFn
) {
429 success: function(response
, options
) {
430 if (options
.waitMsgTarget
) {
431 if (Proxmox
.Utils
.toolkit
=== 'touch') {
432 options
.waitMsgTarget
.setMasked(false);
434 options
.waitMsgTarget
.setLoading(false);
437 let result
= Ext
.decode(response
.responseText
);
438 response
.result
= result
;
439 if (!result
.success
) {
440 response
.htmlStatus
= Proxmox
.Utils
.extractRequestError(result
, true);
441 Ext
.callback(callbackFn
, options
.scope
, [options
, false, response
]);
442 Ext
.callback(failureFn
, options
.scope
, [response
, options
]);
445 Ext
.callback(callbackFn
, options
.scope
, [options
, true, response
]);
446 Ext
.callback(successFn
, options
.scope
, [response
, options
]);
448 failure: function(response
, options
) {
449 if (options
.waitMsgTarget
) {
450 if (Proxmox
.Utils
.toolkit
=== 'touch') {
451 options
.waitMsgTarget
.setMasked(false);
453 options
.waitMsgTarget
.setLoading(false);
456 response
.result
= {};
458 response
.result
= Ext
.decode(response
.responseText
);
462 let msg
= gettext('Connection error') + ' - server offline?';
463 if (response
.aborted
) {
464 msg
= gettext('Connection error') + ' - aborted.';
465 } else if (response
.timedout
) {
466 msg
= gettext('Connection error') + ' - Timeout.';
467 } else if (response
.status
&& response
.statusText
) {
468 msg
= gettext('Connection error') + ' ' + response
.status
+ ': ' + response
.statusText
;
470 response
.htmlStatus
= msg
;
471 Ext
.callback(callbackFn
, options
.scope
, [options
, false, response
]);
472 Ext
.callback(failureFn
, options
.scope
, [response
, options
]);
477 createWrapper(reqOpts
.success
, reqOpts
.callback
, reqOpts
.failure
);
479 let target
= newopts
.waitMsgTarget
;
481 if (Proxmox
.Utils
.toolkit
=== 'touch') {
482 target
.setMasked({ xtype
: 'loadmask', message
: newopts
.waitMsg
});
484 // Note: ExtJS bug - this does not work when component is not rendered
485 target
.setLoading(newopts
.waitMsg
);
488 Ext
.Ajax
.request(newopts
);
491 // can be useful for catching displaying errors from the API, e.g.:
492 // Proxmox.Async.api2({
494 // }).catch(Proxmox.Utils.alertResponseFailure);
495 alertResponseFailure
: (response
) => {
498 response
.htmlStatus
|| response
.result
.message
,
502 checked_command: function(orig_cmd
) {
503 Proxmox
.Utils
.API2Request(
505 url
: '/nodes/localhost/subscription',
507 failure: function(response
, opts
) {
508 Ext
.Msg
.alert(gettext('Error'), response
.htmlStatus
);
510 success: function(response
, opts
) {
511 let res
= response
.result
;
512 if (res
=== null || res
=== undefined || !res
|| res
513 .data
.status
.toLowerCase() !== 'active') {
515 title
: gettext('No valid subscription'),
516 icon
: Ext
.Msg
.WARNING
,
517 message
: Proxmox
.Utils
.getNoSubKeyHtml(res
.data
.url
),
519 callback: function(btn
) {
534 assemble_field_data: function(values
, data
) {
535 if (!Ext
.isObject(data
)) {
538 Ext
.Object
.each(data
, function(name
, val
) {
539 if (Object
.prototype.hasOwnProperty
.call(values
, name
)) {
540 let bucket
= values
[name
];
541 if (!Ext
.isArray(bucket
)) {
542 bucket
= values
[name
] = [bucket
];
544 if (Ext
.isArray(val
)) {
545 values
[name
] = bucket
.concat(val
);
555 updateColumnWidth: function(container
, thresholdWidth
) {
556 let mode
= Ext
.state
.Manager
.get('summarycolumns') || 'auto';
558 if (mode
!== 'auto') {
559 factor
= parseInt(mode
, 10);
560 if (Number
.isNaN(factor
)) {
564 thresholdWidth
= (thresholdWidth
|| 1400) + 1;
565 factor
= Math
.ceil(container
.getSize().width
/ thresholdWidth
);
568 if (container
.oldFactor
=== factor
) {
572 let items
= container
.query('>'); // direct children
573 factor
= Math
.min(factor
, items
.length
);
574 container
.oldFactor
= factor
;
576 items
.forEach((item
) => {
577 item
.columnWidth
= 1 / factor
;
580 // we have to update the layout twice, since the first layout change
581 // can trigger the scrollbar which reduces the amount of space left
582 container
.updateLayout();
583 container
.updateLayout();
586 // NOTE: depreacated, use updateColumnWidth
587 updateColumns
: container
=> Proxmox
.Utils
.updateColumnWidth(container
),
589 dialog_title: function(subject
, create
, isAdd
) {
592 return gettext('Add') + ': ' + subject
;
594 return gettext('Create') + ': ' + subject
;
597 return gettext('Edit') + ': ' + subject
;
601 network_iface_types
: {
602 eth
: gettext("Network Device"),
603 bridge
: 'Linux Bridge',
606 OVSBridge
: 'OVS Bridge',
609 OVSIntPort
: 'OVS IntPort',
612 render_network_iface_type: function(value
) {
613 return Proxmox
.Utils
.network_iface_types
[value
] ||
614 Proxmox
.Utils
.unknownText
;
617 // NOTE: only add general, product agnostic, ones here! Else use override helper in product repos
619 aptupdate
: ['', gettext('Update package database')],
620 diskinit
: ['Disk', gettext('Initialize Disk with GPT')],
621 spiceshell
: ['', gettext('Shell') + ' (Spice)'],
622 srvreload
: ['SRV', gettext('Reload')],
623 srvrestart
: ['SRV', gettext('Restart')],
624 srvstart
: ['SRV', gettext('Start')],
625 srvstop
: ['SRV', gettext('Stop')],
626 termproxy
: ['', gettext('Console') + ' (xterm.js)'],
627 vncshell
: ['', gettext('Shell')],
630 // to add or change existing for product specific ones
631 override_task_descriptions: function(extra
) {
632 for (const [key
, value
] of Object
.entries(extra
)) {
633 Proxmox
.Utils
.task_desc_table
[key
] = value
;
637 format_task_description: function(type
, id
) {
638 let farray
= Proxmox
.Utils
.task_desc_table
[type
];
646 } else if (Ext
.isFunction(farray
)) {
647 return farray(type
, id
);
649 let prefix
= farray
[0];
651 if (prefix
&& id
!== undefined) {
652 return prefix
+ ' ' + id
+ ' - ' + text
;
657 format_size: function(size
, useSI
) {
658 let units
= ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'];
660 const baseValue
= useSI
? 1000 : 1024;
661 while (size
>= baseValue
&& order
< units
.length
) {
662 size
= size
/ baseValue
;
666 let unit
= units
[order
], commaDigits
= 2;
672 return `${size.toFixed(commaDigits)} ${unit}B`;
680 'GiB': 1024*1024*1024,
681 'TiB': 1024*1024*1024*1024,
682 'PiB': 1024*1024*1024*1024*1024,
686 'GB': 1000*1000*1000,
687 'TB': 1000*1000*1000*1000,
688 'PB': 1000*1000*1000*1000*1000,
691 parse_size_unit: function(val
) {
692 //let m = val.match(/([.\d])+\s?([KMGTP]?)(i?)B?\s*$/i);
693 let m
= val
.match(/(\d+(?:\.\d+)?)\s?([KMGTP]?)(i?)B?\s*$/i);
694 let size
= parseFloat(m
[1]);
695 let scale
= m
[2].toUpperCase();
696 let binary
= m
[3].toLowerCase();
698 let unit
= `${scale}${binary}B`;
699 let factor
= Proxmox
.Utils
.SizeUnits
[unit
];
701 return { size
, factor
, unit
, binary
}; // for convenience return all we got
704 size_unit_to_bytes: function(val
) {
705 let { size
, factor
} = Proxmox
.Utils
.parse_size_unit(val
);
706 return size
* factor
;
709 autoscale_size_unit: function(val
) {
710 let { size
, factor
, binary
} = Proxmox
.Utils
.parse_size_unit(val
);
711 return Proxmox
.Utils
.format_size(size
* factor
, binary
!== "i");
714 size_unit_ratios: function(a
, b
) {
715 a
= typeof a
!== "undefined" ? a
: 0;
716 b
= typeof b
!== "undefined" ? b
: Infinity
;
717 let aBytes
= typeof a
=== "number" ? a
: Proxmox
.Utils
.size_unit_to_bytes(a
);
718 let bBytes
= typeof b
=== "number" ? b
: Proxmox
.Utils
.size_unit_to_bytes(b
);
719 return aBytes
/ (bBytes
|| Infinity
); // avoid division by zero
722 render_upid: function(value
, metaData
, record
) {
723 let task
= record
.data
;
724 let type
= task
.type
|| task
.worker_type
;
725 let id
= task
.id
|| task
.worker_id
;
727 return Proxmox
.Utils
.format_task_description(type
, id
);
730 render_uptime: function(value
) {
733 if (uptime
=== undefined) {
741 return Proxmox
.Utils
.format_duration_long(uptime
);
744 systemd_unescape: function(string_value
) {
745 const charcode_0
= '0'.charCodeAt(0);
746 const charcode_9
= '9'.charCodeAt(0);
747 const charcode_A
= 'A'.charCodeAt(0);
748 const charcode_F
= 'F'.charCodeAt(0);
749 const charcode_a
= 'a'.charCodeAt(0);
750 const charcode_f
= 'f'.charCodeAt(0);
751 const charcode_x
= 'x'.charCodeAt(0);
752 const charcode_minus
= '-'.charCodeAt(0);
753 const charcode_slash
= '/'.charCodeAt(0);
754 const charcode_backslash
= '\\'.charCodeAt(0);
756 let parse_hex_digit = function(d
) {
757 if (d
>= charcode_0
&& d
<= charcode_9
) {
758 return d
- charcode_0
;
760 if (d
>= charcode_A
&& d
<= charcode_F
) {
761 return d
- charcode_A
+ 10;
763 if (d
>= charcode_a
&& d
<= charcode_f
) {
764 return d
- charcode_a
+ 10;
766 throw "got invalid hex digit";
769 let value
= new TextEncoder().encode(string_value
);
770 let result
= new Uint8Array(value
.length
);
775 while (i
< value
.length
) {
777 if (c0
=== charcode_minus
) {
778 result
.set([charcode_slash
], result_len
);
783 if ((i
+ 4) < value
.length
) {
785 if (c0
=== charcode_backslash
&& c1
=== charcode_x
) {
786 let h1
= parse_hex_digit(value
[i
+2]);
787 let h0
= parse_hex_digit(value
[i
+3]);
789 result
.set([ord
], result_len
);
795 result
.set([c0
], result_len
);
800 return new TextDecoder().decode(result
.slice(0, result
.len
));
803 parse_task_upid: function(upid
) {
806 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]+):$/);
808 throw "unable to parse upid '" + upid
+ "'";
811 task
.pid
= parseInt(res
[2], 16);
812 task
.pstart
= parseInt(res
[3], 16);
813 if (res
[5] !== undefined) {
814 task
.task_id
= parseInt(res
[5], 16);
816 task
.starttime
= parseInt(res
[6], 16);
818 task
.id
= Proxmox
.Utils
.systemd_unescape(res
[8]);
821 task
.desc
= Proxmox
.Utils
.format_task_description(task
.type
, task
.id
);
826 parse_task_status: function(status
) {
827 if (status
=== 'OK') {
831 if (status
=== 'unknown') {
835 let match
= status
.match(/^WARNINGS: (.*)$/);
843 format_task_status: function(status
) {
844 let parsed
= Proxmox
.Utils
.parse_task_status(status
);
846 case 'unknown': return Proxmox
.Utils
.unknownText
;
847 case 'error': return Proxmox
.Utils
.errorText
+ ': ' + status
;
848 case 'warning': return status
.replace('WARNINGS', Proxmox
.Utils
.warningsText
);
849 case 'ok': // fall-through
850 default: return status
;
854 render_duration: function(value
) {
855 if (value
=== undefined) {
858 return Proxmox
.Utils
.format_duration_human(value
);
861 render_timestamp: function(value
, metaData
, record
, rowIndex
, colIndex
, store
) {
862 let servertime
= new Date(value
* 1000);
863 return Ext
.Date
.format(servertime
, 'Y-m-d H:i:s');
866 render_zfs_health: function(value
) {
867 if (typeof value
=== 'undefined') {
870 var iconCls
= 'question-circle';
874 iconCls
= 'check-circle good';
878 iconCls
= 'exclamation-circle warning';
883 iconCls
= 'times-circle critical';
888 return '<i class="fa fa-' + iconCls
+ '"></i> ' + value
;
891 get_help_info: function(section
) {
893 if (typeof proxmoxOnlineHelpInfo
!== 'undefined') {
894 helpMap
= proxmoxOnlineHelpInfo
; // eslint-disable-line no-undef
895 } else if (typeof pveOnlineHelpInfo
!== 'undefined') {
896 // be backward compatible with older pve-doc-generators
897 helpMap
= pveOnlineHelpInfo
; // eslint-disable-line no-undef
899 throw "no global OnlineHelpInfo map declared";
902 if (helpMap
[section
]) {
903 return helpMap
[section
];
905 // try to normalize - and _ separators, to support asciidoc and sphinx
906 // references at the same time.
907 let section_minus_normalized
= section
.replace(/_
/g
, '-');
908 if (helpMap
[section_minus_normalized
]) {
909 return helpMap
[section_minus_normalized
];
911 let section_underscore_normalized
= section
.replace(/-/g
, '_');
912 return helpMap
[section_underscore_normalized
];
915 get_help_link: function(section
) {
916 let info
= Proxmox
.Utils
.get_help_info(section
);
920 return window
.location
.origin
+ info
.link
;
923 openXtermJsViewer: function(vmtype
, vmid
, nodename
, vmname
, cmd
) {
924 let url
= Ext
.Object
.toQueryString({
925 console
: vmtype
, // kvm, lxc, upgrade or shell
933 let nw
= window
.open("?" + url
, '_blank', 'toolbar=no,location=no,status=no,menubar=no,resizable=yes,width=800,height=420');
939 render_optional_url: function(value
) {
940 if (value
&& value
.match(/^https?:\/\//) !== null) {
941 return '<a target="_blank" href="' + value
+ '">' + value
+ '</a>';
946 render_san: function(value
) {
948 if (Ext
.isArray(value
)) {
949 value
.forEach(function(val
) {
950 if (!Ext
.isNumber(val
)) {
954 return names
.join('<br>');
959 render_usage
: val
=> (val
* 100).toFixed(2) + '%',
961 render_cpu_usage: function(val
, max
) {
962 return Ext
.String
.format(
963 `${gettext('{0}% of {1}')} ${gettext('CPU(s)')}`,
964 (val
*100).toFixed(2),
969 render_size_usage: function(val
, max
, useSI
) {
971 return gettext('N/A');
973 let fmt
= v
=> Proxmox
.Utils
.format_size(v
, useSI
);
974 let ratio
= (val
* 100 / max
).toFixed(2);
975 return ratio
+ '% (' + Ext
.String
.format(gettext('{0} of {1}'), fmt(val
), fmt(max
)) + ')';
978 render_cpu: function(value
, metaData
, record
, rowIndex
, colIndex
, store
) {
979 if (!(record
.data
.uptime
&& Ext
.isNumeric(value
))) {
983 let maxcpu
= record
.data
.maxcpu
|| 1;
984 if (!Ext
.isNumeric(maxcpu
) || maxcpu
< 1) {
987 let cpuText
= maxcpu
> 1 ? 'CPUs' : 'CPU';
988 let ratio
= (value
* 100).toFixed(1);
989 return `${ratio}% of ${maxcpu.toString()} ${cpuText}`;
992 render_size: function(value
, metaData
, record
, rowIndex
, colIndex
, store
) {
993 if (!Ext
.isNumeric(value
)) {
996 return Proxmox
.Utils
.format_size(value
);
999 render_cpu_model: function(cpu
) {
1000 let socketText
= cpu
.sockets
> 1 ? gettext('Sockets') : gettext('Socket');
1001 return `${cpu.cpus} x ${cpu.model} (${cpu.sockets.toString()} ${socketText})`;
1004 /* this is different for nodes */
1005 render_node_cpu_usage: function(value
, record
) {
1006 return Proxmox
.Utils
.render_cpu_usage(value
, record
.cpus
);
1009 render_node_size_usage: function(record
) {
1010 return Proxmox
.Utils
.render_size_usage(record
.used
, record
.total
);
1013 loadTextFromFile: function(file
, callback
, maxBytes
) {
1014 let maxSize
= maxBytes
|| 8192;
1015 if (file
.size
> maxSize
) {
1016 Ext
.Msg
.alert(gettext('Error'), gettext("Invalid file size: ") + file
.size
);
1019 let reader
= new FileReader();
1020 reader
.onload
= evt
=> callback(evt
.target
.result
);
1021 reader
.readAsText(file
);
1024 parsePropertyString: function(value
, defaultKey
) {
1028 if (typeof value
!== 'string' || value
=== '') {
1032 Ext
.Array
.each(value
.split(','), function(p
) {
1033 var kv
= p
.split('=', 2);
1034 if (Ext
.isDefined(kv
[1])) {
1036 } else if (Ext
.isDefined(defaultKey
)) {
1037 if (Ext
.isDefined(res
[defaultKey
])) {
1038 error
= 'defaultKey may be only defined once in propertyString';
1039 return false; // break
1041 res
[defaultKey
] = kv
[0];
1043 error
= 'invalid propertyString, not a key=value pair and no defaultKey defined';
1044 return false; // break
1049 if (error
!== undefined) {
1050 console
.error(error
);
1057 printPropertyString: function(data
, defaultKey
) {
1058 var stringparts
= [],
1059 gotDefaultKeyVal
= false,
1062 Ext
.Object
.each(data
, function(key
, value
) {
1063 if (defaultKey
!== undefined && key
=== defaultKey
) {
1064 gotDefaultKeyVal
= true;
1065 defaultKeyVal
= value
;
1066 } else if (Ext
.isArray(value
)) {
1067 stringparts
.push(key
+ '=' + value
.join(';'));
1068 } else if (value
!== '') {
1069 stringparts
.push(key
+ '=' + value
);
1073 stringparts
= stringparts
.sort();
1074 if (gotDefaultKeyVal
) {
1075 stringparts
.unshift(defaultKeyVal
);
1078 return stringparts
.join(',');
1081 acmedomain_count
: 5,
1083 parseACMEPluginData: function(data
) {
1086 data
.split('\n').forEach((line
) => {
1087 // capture everything after the first = as value
1088 let [key
, value
] = line
.split('=');
1089 if (value
!== undefined) {
1092 extradata
.push(line
);
1095 return [res
, extradata
];
1098 delete_if_default: function(values
, fieldname
, default_val
, create
) {
1099 if (values
[fieldname
] === '' || values
[fieldname
] === default_val
) {
1101 if (values
.delete) {
1102 if (Ext
.isArray(values
.delete)) {
1103 values
.delete.push(fieldname
);
1105 values
.delete += ',' + fieldname
;
1108 values
.delete = fieldname
;
1112 delete values
[fieldname
];
1116 printACME: function(value
) {
1117 if (Ext
.isArray(value
.domains
)) {
1118 value
.domains
= value
.domains
.join(';');
1120 return Proxmox
.Utils
.printPropertyString(value
);
1123 parseACME: function(value
) {
1131 Ext
.Array
.each(value
.split(','), function(p
) {
1132 var kv
= p
.split('=', 2);
1133 if (Ext
.isDefined(kv
[1])) {
1136 error
= 'Failed to parse key-value pair: '+p
;
1142 if (error
!== undefined) {
1143 console
.error(error
);
1147 if (res
.domains
!== undefined) {
1148 res
.domains
= res
.domains
.split(/;/);
1154 add_domain_to_acme: function(acme
, domain
) {
1155 if (acme
.domains
=== undefined) {
1156 acme
.domains
= [domain
];
1158 acme
.domains
.push(domain
);
1159 acme
.domains
= acme
.domains
.filter((value
, index
, self
) => self
.indexOf(value
) === index
);
1164 remove_domain_from_acme: function(acme
, domain
) {
1165 if (acme
.domains
!== undefined) {
1166 acme
.domains
= acme
.domains
.filter(
1167 (value
, index
, self
) => self
.indexOf(value
) === index
&& value
!== domain
,
1173 get_health_icon: function(state
, circle
) {
1174 if (circle
=== undefined) {
1178 if (state
=== undefined) {
1182 var icon
= 'faded fa-question';
1185 icon
= 'good fa-check';
1188 icon
= 'warning fa-upload';
1191 icon
= 'warning fa-refresh';
1194 icon
= 'warning fa-exclamation';
1197 icon
= 'critical fa-times';
1209 formatNodeRepoStatus: function(status
, product
) {
1210 let fmt
= (txt
, cls
) => `<i class="fa fa-fw fa-lg fa-${cls}"></i>${txt}`;
1212 let getUpdates
= Ext
.String
.format(gettext('{0} updates'), product
);
1213 let noRepo
= Ext
.String
.format(gettext('No {0} repository enabled!'), product
);
1215 if (status
=== 'ok') {
1216 return fmt(getUpdates
, 'check-circle good') + ' ' +
1217 fmt(gettext('Production-ready Enterprise repository enabled'), 'check-circle good');
1218 } else if (status
=== 'no-sub') {
1219 return fmt(gettext('Production-ready Enterprise repository enabled'), 'check-circle good') + ' ' +
1220 fmt(gettext('Enterprise repository needs valid subscription'), 'exclamation-circle warning');
1221 } else if (status
=== 'non-production') {
1222 return fmt(getUpdates
, 'check-circle good') + ' ' +
1223 fmt(gettext('Non production-ready repository enabled!'), 'exclamation-circle warning');
1224 } else if (status
=== 'no-repo') {
1225 return fmt(noRepo
, 'exclamation-circle critical');
1228 return Proxmox
.Utils
.unknownText
;
1231 render_u2f_error: function(error
) {
1233 '1': gettext('Other Error'),
1234 '2': gettext('Bad Request'),
1235 '3': gettext('Configuration Unsupported'),
1236 '4': gettext('Device Ineligible'),
1237 '5': gettext('Timeout'),
1239 return "U2F Error: " + ErrorNames
[error
] || Proxmox
.Utils
.unknownText
;
1242 // Convert an ArrayBuffer to a base64url encoded string.
1243 // A `null` value will be preserved for convenience.
1244 bytes_to_base64url: function(bytes
) {
1245 if (bytes
=== null) {
1250 .from(new Uint8Array(bytes
))
1251 .map(val
=> String
.fromCharCode(val
))
1254 .replace(/\+/g, '-')
1255 .replace(/\//g, '_')
1256 .replace(/[=]/g, '');
1259 // Convert an a base64url string to an ArrayBuffer.
1260 // A `null` value will be preserved for convenience.
1261 base64url_to_bytes: function(b64u
) {
1262 if (b64u
=== null) {
1266 return new Uint8Array(
1269 .replace(/_/g, '/'),
1272 .map(val => val.charCodeAt(0)),
1278 constructor: function() {
1280 Ext.apply(me, me.utilities);
1282 let IPV4_OCTET = "(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])";
1283 let IPV4_REGEXP = "(?:(?:" + IPV4_OCTET + "\\.){3}" + IPV4_OCTET + ")";
1284 let IPV6_H16 = "(?:[0-9a-fA-F]{1,4})";
1285 let IPV6_LS32 = "(?:(?:" + IPV6_H16 + ":" + IPV6_H16 + ")|" + IPV4_REGEXP + ")";
1286 let IPV4_CIDR_MASK = "([0-9]{1,2})";
1287 let IPV6_CIDR_MASK = "([0-9]{1,3})";
1290 me.IP4_match = new RegExp("^(?:" + IPV4_REGEXP + ")$");
1291 me.IP4_cidr_match = new RegExp("^(?:" + IPV4_REGEXP + ")/" + IPV4_CIDR_MASK + "$");
1293 /* eslint-disable no-useless-concat,no-multi-spaces */
1294 let IPV6_REGEXP = "(?:" +
1295 "(?:(?:" + "(?:" + IPV6_H16 + ":){6})" + IPV6_LS32 + ")|" +
1296 "(?:(?:" + "::" + "(?:" + IPV6_H16 + ":){5})" + IPV6_LS32 + ")|" +
1297 "(?:(?:(?:" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){4})" + IPV6_LS32 + ")|" +
1298 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,1}" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){3})" + IPV6_LS32 + ")|" +
1299 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,2}" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){2})" + IPV6_LS32 + ")|" +
1300 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,3}" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){1})" + IPV6_LS32 + ")|" +
1301 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,4}" + IPV6_H16 + ")?::" + ")" + IPV6_LS32 + ")|" +
1302 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,5}" + IPV6_H16 + ")?::" + ")" + IPV6_H16 + ")|" +
1303 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,7}" + IPV6_H16 + ")?::" + ")" + ")" +
1305 /* eslint-enable no-useless-concat,no-multi-spaces */
1307 me.IP6_match = new RegExp("^(?:" + IPV6_REGEXP + ")$");
1308 me.IP6_cidr_match = new RegExp("^(?:" + IPV6_REGEXP + ")/" + IPV6_CIDR_MASK + "$");
1309 me.IP6_bracket_match = new RegExp("^\\[(" + IPV6_REGEXP + ")\\]");
1311 me.IP64_match = new RegExp("^(?:" + IPV6_REGEXP + "|" + IPV4_REGEXP + ")$");
1312 me.IP64_cidr_match = new RegExp("^(?:" + IPV6_REGEXP + "/" + IPV6_CIDR_MASK + ")|(?:" + IPV4_REGEXP + "/" + IPV4_CIDR_MASK + ")$");
1314 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])?))";
1315 me.DnsName_match = new RegExp("^" + DnsName_REGEXP + "$");
1316 me.DnsName_or_Wildcard_match = new RegExp("^(?:\\*\\.)?" + DnsName_REGEXP + "$");
1318 me.CpuSet_match = /^[0-9]+(?:-[0-9]+)?(?:,[0-9]+(?:-[0-9]+)?)*$/;
1320 me.HostPort_match = new RegExp("^(" + IPV4_REGEXP + "|" + DnsName_REGEXP + ")(?::(\\d+))?$");
1321 me.HostPortBrackets_match = new RegExp("^\\[(" + IPV6_REGEXP + "|" + IPV4_REGEXP + "|" + DnsName_REGEXP + ")\\](?::(\\d+))?$");
1322 me.IP6_dotnotation_match = new RegExp("^(" + IPV6_REGEXP + ")(?:\\.(\\d+))?$");
1323 me.Vlan_match = /^vlan(\d+)/;
1324 me.VlanInterface_match = /(\w+)\.(\d+)/;
1328 Ext.define('Proxmox
.Async
', {
1331 // Returns a Promise resolving to the result of an `API2Request` or rejecting to the error
1332 // response on failure
1333 api2: function(reqOpts) {
1334 return new Promise((resolve, reject) => {
1335 delete reqOpts.callback; // not allowed in this api
1336 reqOpts.success = response => resolve(response);
1337 reqOpts.failure = response => reject(response);
1338 Proxmox.Utils.API2Request(reqOpts);
1342 // Delay for a number of milliseconds.
1343 sleep: function(millis) {
1344 return new Promise((resolve, _reject) => setTimeout(resolve, millis));