]> git.proxmox.com Git - proxmox-widget-toolkit.git/blob - src/Utils.js
utils: improve indentation and better check API result
[proxmox-widget-toolkit.git] / src / Utils.js
1 Ext.ns('Proxmox');
2 Ext.ns('Proxmox.Setup');
3
4 if (!Ext.isDefined(Proxmox.Setup.auth_cookie_name)) {
5 throw "Proxmox library not initialized";
6 }
7
8 // avoid errors related to Accessible Rich Internet Applications
9 // (access for people with disabilities)
10 // TODO reenable after all components are upgraded
11 Ext.enableAria = false;
12 Ext.enableAriaButtons = false;
13 Ext.enableAriaPanels = false;
14
15 // avoid errors when running without development tools
16 if (!Ext.isDefined(Ext.global.console)) {
17 let console = {
18 dir: function() {
19 // do nothing
20 },
21 log: function() {
22 // do nothing
23 },
24 warn: function() {
25 // do nothing
26 },
27 };
28 Ext.global.console = console;
29 }
30
31 Ext.Ajax.defaultHeaders = {
32 'Accept': 'application/json',
33 };
34
35 Ext.Ajax.on('beforerequest', function(conn, options) {
36 if (Proxmox.CSRFPreventionToken) {
37 if (!options.headers) {
38 options.headers = {};
39 }
40 options.headers.CSRFPreventionToken = Proxmox.CSRFPreventionToken;
41 }
42 let storedAuth = Proxmox.Utils.getStoredAuth();
43 if (storedAuth.token) {
44 options.headers.Authorization = storedAuth.token;
45 }
46 });
47
48 Ext.define('Proxmox.Utils', { // a singleton
49 utilities: {
50
51 yesText: gettext('Yes'),
52 noText: gettext('No'),
53 enabledText: gettext('Enabled'),
54 disabledText: gettext('Disabled'),
55 noneText: gettext('none'),
56 NoneText: gettext('None'),
57 errorText: gettext('Error'),
58 unknownText: gettext('Unknown'),
59 defaultText: gettext('Default'),
60 daysText: gettext('days'),
61 dayText: gettext('day'),
62 runningText: gettext('running'),
63 stoppedText: gettext('stopped'),
64 neverText: gettext('never'),
65 totalText: gettext('Total'),
66 usedText: gettext('Used'),
67 directoryText: gettext('Directory'),
68 stateText: gettext('State'),
69 groupText: gettext('Group'),
70
71 language_map: {
72 ar: 'Arabic',
73 ca: 'Catalan',
74 da: 'Danish',
75 de: 'German',
76 en: 'English',
77 es: 'Spanish',
78 eu: 'Euskera (Basque)',
79 fa: 'Persian (Farsi)',
80 fr: 'French',
81 he: 'Hebrew',
82 it: 'Italian',
83 ja: 'Japanese',
84 nb: 'Norwegian (Bokmal)',
85 nn: 'Norwegian (Nynorsk)',
86 pl: 'Polish',
87 pt_BR: 'Portuguese (Brazil)',
88 ru: 'Russian',
89 sl: 'Slovenian',
90 sv: 'Swedish',
91 tr: 'Turkish',
92 zh_CN: 'Chinese (Simplified)',
93 zh_TW: 'Chinese (Traditional)',
94 },
95
96 render_language: function(value) {
97 if (!value) {
98 return Proxmox.Utils.defaultText + ' (English)';
99 }
100 let text = Proxmox.Utils.language_map[value];
101 if (text) {
102 return text + ' (' + value + ')';
103 }
104 return value;
105 },
106
107 language_array: function() {
108 let data = [['__default__', Proxmox.Utils.render_language('')]];
109 Ext.Object.each(Proxmox.Utils.language_map, function(key, value) {
110 data.push([key, Proxmox.Utils.render_language(value)]);
111 });
112
113 return data;
114 },
115
116 bond_mode_gettext_map: {
117 '802.3ad': 'LACP (802.3ad)',
118 'lacp-balance-slb': 'LACP (balance-slb)',
119 'lacp-balance-tcp': 'LACP (balance-tcp)',
120 },
121
122 render_bond_mode: value => Proxmox.Utils.bond_mode_gettext_map[value] || value || '',
123
124 bond_mode_array: function(modes) {
125 return modes.map(mode => [mode, Proxmox.Utils.render_bond_mode(mode)]);
126 },
127
128 getNoSubKeyHtml: function(url) {
129 // url http://www.proxmox.com/products/proxmox-ve/subscription-service-plans
130 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');
131 },
132
133 format_boolean_with_default: function(value) {
134 if (Ext.isDefined(value) && value !== '__default__') {
135 return value ? Proxmox.Utils.yesText : Proxmox.Utils.noText;
136 }
137 return Proxmox.Utils.defaultText;
138 },
139
140 format_boolean: function(value) {
141 return value ? Proxmox.Utils.yesText : Proxmox.Utils.noText;
142 },
143
144 format_neg_boolean: function(value) {
145 return !value ? Proxmox.Utils.yesText : Proxmox.Utils.noText;
146 },
147
148 format_enabled_toggle: function(value) {
149 return value ? Proxmox.Utils.enabledText : Proxmox.Utils.disabledText;
150 },
151
152 format_expire: function(date) {
153 if (!date) {
154 return Proxmox.Utils.neverText;
155 }
156 return Ext.Date.format(date, "Y-m-d");
157 },
158
159 // somewhat like a human would tell durations, omit zero values and do not
160 // give seconds precision if we talk days already
161 format_duration_human: function(ut) {
162 let seconds = 0, minutes = 0, hours = 0, days = 0;
163
164 if (ut <= 0.1) {
165 return '<0.1s';
166 }
167
168 let remaining = ut;
169 seconds = Number((remaining % 60).toFixed(1));
170 remaining = Math.trunc(remaining / 60);
171 if (remaining > 0) {
172 minutes = remaining % 60;
173 remaining = Math.trunc(remaining / 60);
174 if (remaining > 0) {
175 hours = remaining % 24;
176 remaining = Math.trunc(remaining / 24);
177 if (remaining > 0) {
178 days = remaining;
179 }
180 }
181 }
182
183 let res = [];
184 let add = (t, unit) => {
185 if (t > 0) res.push(t + unit);
186 return t > 0;
187 };
188
189 let addSeconds = !add(days, 'd');
190 add(hours, 'h');
191 add(minutes, 'm');
192 if (addSeconds) {
193 add(seconds, 's');
194 }
195 return res.join(' ');
196 },
197
198 format_duration_long: function(ut) {
199 let days = Math.floor(ut / 86400);
200 ut -= days*86400;
201 let hours = Math.floor(ut / 3600);
202 ut -= hours*3600;
203 let mins = Math.floor(ut / 60);
204 ut -= mins*60;
205
206 let hours_str = '00' + hours.toString();
207 hours_str = hours_str.substr(hours_str.length - 2);
208 let mins_str = "00" + mins.toString();
209 mins_str = mins_str.substr(mins_str.length - 2);
210 let ut_str = "00" + ut.toString();
211 ut_str = ut_str.substr(ut_str.length - 2);
212
213 if (days) {
214 let ds = days > 1 ? Proxmox.Utils.daysText : Proxmox.Utils.dayText;
215 return days.toString() + ' ' + ds + ' ' +
216 hours_str + ':' + mins_str + ':' + ut_str;
217 } else {
218 return hours_str + ':' + mins_str + ':' + ut_str;
219 }
220 },
221
222 format_subscription_level: function(level) {
223 if (level === 'c') {
224 return 'Community';
225 } else if (level === 'b') {
226 return 'Basic';
227 } else if (level === 's') {
228 return 'Standard';
229 } else if (level === 'p') {
230 return 'Premium';
231 } else {
232 return Proxmox.Utils.noneText;
233 }
234 },
235
236 compute_min_label_width: function(text, width) {
237 if (width === undefined) { width = 100; }
238
239 let tm = new Ext.util.TextMetrics();
240 let min = tm.getWidth(text + ':');
241
242 return min < width ? width : min;
243 },
244
245 getStoredAuth: function() {
246 let storedAuth = JSON.parse(window.localStorage.getItem('ProxmoxUser'));
247 return storedAuth || {};
248 },
249
250 setAuthData: function(data) {
251 Proxmox.UserName = data.username;
252 Proxmox.LoggedOut = data.LoggedOut;
253 // creates a session cookie (expire = null)
254 // that way the cookie gets deleted after the browser window is closed
255 if (data.ticket) {
256 Proxmox.CSRFPreventionToken = data.CSRFPreventionToken;
257 Ext.util.Cookies.set(Proxmox.Setup.auth_cookie_name, data.ticket, null, '/', null, true);
258 }
259
260 if (data.token) {
261 window.localStorage.setItem('ProxmoxUser', JSON.stringify(data));
262 }
263 },
264
265 authOK: function() {
266 if (Proxmox.LoggedOut) {
267 return undefined;
268 }
269 let storedAuth = Proxmox.Utils.getStoredAuth();
270 let cookie = Ext.util.Cookies.get(Proxmox.Setup.auth_cookie_name);
271 if ((Proxmox.UserName !== '' && cookie && !cookie.startsWith("PVE:tfa!")) || storedAuth.token) {
272 return cookie || storedAuth.token;
273 } else {
274 return false;
275 }
276 },
277
278 authClear: function() {
279 if (Proxmox.LoggedOut) {
280 return;
281 }
282 Ext.util.Cookies.clear(Proxmox.Setup.auth_cookie_name);
283 window.localStorage.removeItem("ProxmoxUser");
284 },
285
286 // comp.setLoading() is buggy in ExtJS 4.0.7, so we
287 // use el.mask() instead
288 setErrorMask: function(comp, msg) {
289 let el = comp.el;
290 if (!el) {
291 return;
292 }
293 if (!msg) {
294 el.unmask();
295 } else if (msg === true) {
296 el.mask(gettext("Loading..."));
297 } else {
298 el.mask(msg);
299 }
300 },
301
302 getResponseErrorMessage: (err) => {
303 if (!err.statusText) {
304 return gettext('Connection error');
305 }
306 let msg = [`${err.statusText} (${err.status})`];
307 if (err.response && err.response.responseText) {
308 let txt = err.response.responseText;
309 try {
310 let res = JSON.parse(txt);
311 if (res.errors && typeof res.errors === 'object') {
312 for (let [key, value] of Object.entries(res.errors)) {
313 msg.push(Ext.String.htmlEncode(`${key}: ${value}`));
314 }
315 }
316 } catch (e) {
317 // fallback to string
318 msg.push(Ext.String.htmlEncode(txt));
319 }
320 }
321 return msg.join('<br>');
322 },
323
324 monStoreErrors: function(component, store, clearMaskBeforeLoad) {
325 if (clearMaskBeforeLoad) {
326 component.mon(store, 'beforeload', function(s, operation, eOpts) {
327 Proxmox.Utils.setErrorMask(component, false);
328 });
329 } else {
330 component.mon(store, 'beforeload', function(s, operation, eOpts) {
331 if (!component.loadCount) {
332 component.loadCount = 0; // make sure it is nucomponent.ic
333 Proxmox.Utils.setErrorMask(component, true);
334 }
335 });
336 }
337
338 // only works with 'proxmox' proxy
339 component.mon(store.proxy, 'afterload', function(proxy, request, success) {
340 component.loadCount++;
341
342 if (success) {
343 Proxmox.Utils.setErrorMask(component, false);
344 return;
345 }
346
347 let error = request._operation.getError();
348 let msg = Proxmox.Utils.getResponseErrorMessage(error);
349 Proxmox.Utils.setErrorMask(component, msg);
350 });
351 },
352
353 extractRequestError: function(result, verbose) {
354 let msg = gettext('Successful');
355
356 if (!result.success) {
357 msg = gettext("Unknown error");
358 if (result.message) {
359 msg = result.message;
360 if (result.status) {
361 msg += ' (' + result.status + ')';
362 }
363 }
364 if (verbose && Ext.isObject(result.errors)) {
365 msg += "<br>";
366 Ext.Object.each(result.errors, function(prop, desc) {
367 msg += "<br><b>" + Ext.htmlEncode(prop) + "</b>: " +
368 Ext.htmlEncode(desc);
369 });
370 }
371 }
372
373 return msg;
374 },
375
376 // Ext.Ajax.request
377 API2Request: function(reqOpts) {
378 let newopts = Ext.apply({
379 waitMsg: gettext('Please wait...'),
380 }, reqOpts);
381
382 if (!newopts.url.match(/^\/api2/)) {
383 newopts.url = '/api2/extjs' + newopts.url;
384 }
385 delete newopts.callback;
386
387 let createWrapper = function(successFn, callbackFn, failureFn) {
388 Ext.apply(newopts, {
389 success: function(response, options) {
390 if (options.waitMsgTarget) {
391 if (Proxmox.Utils.toolkit === 'touch') {
392 options.waitMsgTarget.setMasked(false);
393 } else {
394 options.waitMsgTarget.setLoading(false);
395 }
396 }
397 let result = Ext.decode(response.responseText);
398 response.result = result;
399 if (!result.success) {
400 response.htmlStatus = Proxmox.Utils.extractRequestError(result, true);
401 Ext.callback(callbackFn, options.scope, [options, false, response]);
402 Ext.callback(failureFn, options.scope, [response, options]);
403 return;
404 }
405 Ext.callback(callbackFn, options.scope, [options, true, response]);
406 Ext.callback(successFn, options.scope, [response, options]);
407 },
408 failure: function(response, options) {
409 if (options.waitMsgTarget) {
410 if (Proxmox.Utils.toolkit === 'touch') {
411 options.waitMsgTarget.setMasked(false);
412 } else {
413 options.waitMsgTarget.setLoading(false);
414 }
415 }
416 response.result = {};
417 try {
418 response.result = Ext.decode(response.responseText);
419 } catch (e) {
420 // ignore
421 }
422 let msg = gettext('Connection error') + ' - server offline?';
423 if (response.aborted) {
424 msg = gettext('Connection error') + ' - aborted.';
425 } else if (response.timedout) {
426 msg = gettext('Connection error') + ' - Timeout.';
427 } else if (response.status && response.statusText) {
428 msg = gettext('Connection error') + ' ' + response.status + ': ' + response.statusText;
429 }
430 response.htmlStatus = msg;
431 Ext.callback(callbackFn, options.scope, [options, false, response]);
432 Ext.callback(failureFn, options.scope, [response, options]);
433 },
434 });
435 };
436
437 createWrapper(reqOpts.success, reqOpts.callback, reqOpts.failure);
438
439 let target = newopts.waitMsgTarget;
440 if (target) {
441 if (Proxmox.Utils.toolkit === 'touch') {
442 target.setMasked({ xtype: 'loadmask', message: newopts.waitMsg });
443 } else {
444 // Note: ExtJS bug - this does not work when component is not rendered
445 target.setLoading(newopts.waitMsg);
446 }
447 }
448 Ext.Ajax.request(newopts);
449 },
450
451 checked_command: function(orig_cmd) {
452 Proxmox.Utils.API2Request(
453 {
454 url: '/nodes/localhost/subscription',
455 method: 'GET',
456 failure: function(response, opts) {
457 Ext.Msg.alert(gettext('Error'), response.htmlStatus);
458 },
459 success: function(response, opts) {
460 let res = response.result;
461 if (res === null || res === undefined || !res || res
462 .data.status !== 'Active') {
463 Ext.Msg.show({
464 title: gettext('No valid subscription'),
465 icon: Ext.Msg.WARNING,
466 message: Proxmox.Utils.getNoSubKeyHtml(res.data.url),
467 buttons: Ext.Msg.OK,
468 callback: function(btn) {
469 if (btn !== 'ok') {
470 return;
471 }
472 orig_cmd();
473 },
474 });
475 } else {
476 orig_cmd();
477 }
478 },
479 },
480 );
481 },
482
483 assemble_field_data: function(values, data) {
484 if (!Ext.isObject(data)) {
485 return;
486 }
487 Ext.Object.each(data, function(name, val) {
488 if (Object.prototype.hasOwnProperty.call(values, name)) {
489 let bucket = values[name];
490 if (!Ext.isArray(bucket)) {
491 bucket = values[name] = [bucket];
492 }
493 if (Ext.isArray(val)) {
494 values[name] = bucket.concat(val);
495 } else {
496 bucket.push(val);
497 }
498 } else {
499 values[name] = val;
500 }
501 });
502 },
503
504 updateColumnWidth: function(container) {
505 let mode = Ext.state.Manager.get('summarycolumns') || 'auto';
506 let factor;
507 if (mode !== 'auto') {
508 factor = parseInt(mode, 10);
509 if (Number.isNaN(factor)) {
510 factor = 1;
511 }
512 } else {
513 factor = container.getSize().width < 1600 ? 1 : 2;
514 }
515
516 if (container.oldFactor === factor) {
517 return;
518 }
519
520 let items = container.query('>'); // direct childs
521 factor = Math.min(factor, items.length);
522 container.oldFactor = factor;
523
524 items.forEach((item) => {
525 item.columnWidth = 1 / factor;
526 });
527
528 // we have to update the layout twice, since the first layout change
529 // can trigger the scrollbar which reduces the amount of space left
530 container.updateLayout();
531 container.updateLayout();
532 },
533
534 dialog_title: function(subject, create, isAdd) {
535 if (create) {
536 if (isAdd) {
537 return gettext('Add') + ': ' + subject;
538 } else {
539 return gettext('Create') + ': ' + subject;
540 }
541 } else {
542 return gettext('Edit') + ': ' + subject;
543 }
544 },
545
546 network_iface_types: {
547 eth: gettext("Network Device"),
548 bridge: 'Linux Bridge',
549 bond: 'Linux Bond',
550 vlan: 'Linux VLAN',
551 OVSBridge: 'OVS Bridge',
552 OVSBond: 'OVS Bond',
553 OVSPort: 'OVS Port',
554 OVSIntPort: 'OVS IntPort',
555 },
556
557 render_network_iface_type: function(value) {
558 return Proxmox.Utils.network_iface_types[value] ||
559 Proxmox.Utils.unknownText;
560 },
561
562 task_desc_table: {
563 acmenewcert: ['SRV', gettext('Order Certificate')],
564 acmeregister: ['ACME Account', gettext('Register')],
565 acmedeactivate: ['ACME Account', gettext('Deactivate')],
566 acmeupdate: ['ACME Account', gettext('Update')],
567 acmerefresh: ['ACME Account', gettext('Refresh')],
568 acmerenew: ['SRV', gettext('Renew Certificate')],
569 acmerevoke: ['SRV', gettext('Revoke Certificate')],
570 'auth-realm-sync': [gettext('Realm'), gettext('Sync')],
571 'auth-realm-sync-test': [gettext('Realm'), gettext('Sync Preview')],
572 'move_volume': ['CT', gettext('Move Volume')],
573 clustercreate: ['', gettext('Create Cluster')],
574 clusterjoin: ['', gettext('Join Cluster')],
575 diskinit: ['Disk', gettext('Initialize Disk with GPT')],
576 vncproxy: ['VM/CT', gettext('Console')],
577 spiceproxy: ['VM/CT', gettext('Console') + ' (Spice)'],
578 vncshell: ['', gettext('Shell')],
579 spiceshell: ['', gettext('Shell') + ' (Spice)'],
580 qmsnapshot: ['VM', gettext('Snapshot')],
581 qmrollback: ['VM', gettext('Rollback')],
582 qmdelsnapshot: ['VM', gettext('Delete Snapshot')],
583 qmcreate: ['VM', gettext('Create')],
584 qmrestore: ['VM', gettext('Restore')],
585 qmdestroy: ['VM', gettext('Destroy')],
586 qmigrate: ['VM', gettext('Migrate')],
587 qmclone: ['VM', gettext('Clone')],
588 qmmove: ['VM', gettext('Move disk')],
589 qmtemplate: ['VM', gettext('Convert to template')],
590 qmstart: ['VM', gettext('Start')],
591 qmstop: ['VM', gettext('Stop')],
592 qmreset: ['VM', gettext('Reset')],
593 qmshutdown: ['VM', gettext('Shutdown')],
594 qmreboot: ['VM', gettext('Reboot')],
595 qmsuspend: ['VM', gettext('Hibernate')],
596 qmpause: ['VM', gettext('Pause')],
597 qmresume: ['VM', gettext('Resume')],
598 qmconfig: ['VM', gettext('Configure')],
599 vzsnapshot: ['CT', gettext('Snapshot')],
600 vzrollback: ['CT', gettext('Rollback')],
601 vzdelsnapshot: ['CT', gettext('Delete Snapshot')],
602 vzcreate: ['CT', gettext('Create')],
603 vzrestore: ['CT', gettext('Restore')],
604 vzdestroy: ['CT', gettext('Destroy')],
605 vzmigrate: ['CT', gettext('Migrate')],
606 vzclone: ['CT', gettext('Clone')],
607 vztemplate: ['CT', gettext('Convert to template')],
608 vzstart: ['CT', gettext('Start')],
609 vzstop: ['CT', gettext('Stop')],
610 vzmount: ['CT', gettext('Mount')],
611 vzumount: ['CT', gettext('Unmount')],
612 vzshutdown: ['CT', gettext('Shutdown')],
613 vzreboot: ['CT', gettext('Reboot')],
614 vzsuspend: ['CT', gettext('Suspend')],
615 vzresume: ['CT', gettext('Resume')],
616 push_file: ['CT', gettext('Push file')],
617 pull_file: ['CT', gettext('Pull file')],
618 hamigrate: ['HA', gettext('Migrate')],
619 hastart: ['HA', gettext('Start')],
620 hastop: ['HA', gettext('Stop')],
621 hashutdown: ['HA', gettext('Shutdown')],
622 srvstart: ['SRV', gettext('Start')],
623 srvstop: ['SRV', gettext('Stop')],
624 srvrestart: ['SRV', gettext('Restart')],
625 srvreload: ['SRV', gettext('Reload')],
626 cephcreatemgr: ['Ceph Manager', gettext('Create')],
627 cephdestroymgr: ['Ceph Manager', gettext('Destroy')],
628 cephcreatemon: ['Ceph Monitor', gettext('Create')],
629 cephdestroymon: ['Ceph Monitor', gettext('Destroy')],
630 cephcreateosd: ['Ceph OSD', gettext('Create')],
631 cephdestroyosd: ['Ceph OSD', gettext('Destroy')],
632 cephcreatepool: ['Ceph Pool', gettext('Create')],
633 cephdestroypool: ['Ceph Pool', gettext('Destroy')],
634 cephfscreate: ['CephFS', gettext('Create')],
635 cephcreatemds: ['Ceph Metadata Server', gettext('Create')],
636 cephdestroymds: ['Ceph Metadata Server', gettext('Destroy')],
637 imgcopy: ['', gettext('Copy data')],
638 imgdel: ['', gettext('Erase data')],
639 unknownimgdel: ['', gettext('Destroy image from unknown guest')],
640 download: ['', gettext('Download')],
641 vzdump: (type, id) => id ? `VM/CT ${id} - ${gettext('Backup')}` : gettext('Backup Job'),
642 aptupdate: ['', gettext('Update package database')],
643 startall: ['', gettext('Start all VMs and Containers')],
644 stopall: ['', gettext('Stop all VMs and Containers')],
645 migrateall: ['', gettext('Migrate all VMs and Containers')],
646 dircreate: [gettext('Directory Storage'), gettext('Create')],
647 lvmcreate: [gettext('LVM Storage'), gettext('Create')],
648 lvmthincreate: [gettext('LVM-Thin Storage'), gettext('Create')],
649 zfscreate: [gettext('ZFS Storage'), gettext('Create')],
650 },
651
652 // to add or change existing for product specific ones
653 override_task_descriptions: function(extra) {
654 for (const [key, value] of Object.entries(extra)) {
655 Proxmox.Utils.task_desc_table[key] = value;
656 }
657 },
658
659 format_task_description: function(type, id) {
660 let farray = Proxmox.Utils.task_desc_table[type];
661 let text;
662 if (!farray) {
663 text = type;
664 if (id) {
665 type += ' ' + id;
666 }
667 return text;
668 } else if (Ext.isFunction(farray)) {
669 return farray(type, id);
670 }
671 let prefix = farray[0];
672 text = farray[1];
673 if (prefix && id !== undefined) {
674 return prefix + ' ' + id + ' - ' + text;
675 }
676 return text;
677 },
678
679 format_size: function(size) {
680 let units = ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi', 'Yi'];
681 let num = 0;
682 while (size >= 1024 && num++ <= units.length) {
683 size = size / 1024;
684 }
685
686 return size.toFixed(num > 0?2:0) + " " + units[num] + "B";
687 },
688
689 render_upid: function(value, metaData, record) {
690 let task = record.data;
691 let type = task.type || task.worker_type;
692 let id = task.id || task.worker_id;
693
694 return Proxmox.Utils.format_task_description(type, id);
695 },
696
697 render_uptime: function(value) {
698 let uptime = value;
699
700 if (uptime === undefined) {
701 return '';
702 }
703
704 if (uptime <= 0) {
705 return '-';
706 }
707
708 return Proxmox.Utils.format_duration_long(uptime);
709 },
710
711 parse_task_upid: function(upid) {
712 let task = {};
713
714 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]+):$/);
715 if (!res) {
716 throw "unable to parse upid '" + upid + "'";
717 }
718 task.node = res[1];
719 task.pid = parseInt(res[2], 16);
720 task.pstart = parseInt(res[3], 16);
721 if (res[5] !== undefined) {
722 task.task_id = parseInt(res[5], 16);
723 }
724 task.starttime = parseInt(res[6], 16);
725 task.type = res[7];
726 task.id = res[8];
727 task.user = res[9];
728
729 task.desc = Proxmox.Utils.format_task_description(task.type, task.id);
730
731 return task;
732 },
733
734 parse_task_status: function(status) {
735 if (status === 'OK') {
736 return 'ok';
737 }
738
739 if (status === 'unknown') {
740 return 'unknown';
741 }
742
743 let match = status.match(/^WARNINGS: (.*)$/);
744 if (match) {
745 return 'warning';
746 }
747
748 return 'error';
749 },
750
751 render_duration: function(value) {
752 if (value === undefined) {
753 return '-';
754 }
755 return Proxmox.Utils.format_duration_human(value);
756 },
757
758 render_timestamp: function(value, metaData, record, rowIndex, colIndex, store) {
759 let servertime = new Date(value * 1000);
760 return Ext.Date.format(servertime, 'Y-m-d H:i:s');
761 },
762
763 render_zfs_health: function(value) {
764 if (typeof value === 'undefined') {
765 return "";
766 }
767 var iconCls = 'question-circle';
768 switch (value) {
769 case 'AVAIL':
770 case 'ONLINE':
771 iconCls = 'check-circle good';
772 break;
773 case 'REMOVED':
774 case 'DEGRADED':
775 iconCls = 'exclamation-circle warning';
776 break;
777 case 'UNAVAIL':
778 case 'FAULTED':
779 case 'OFFLINE':
780 iconCls = 'times-circle critical';
781 break;
782 default: //unknown
783 }
784
785 return '<i class="fa fa-' + iconCls + '"></i> ' + value;
786 },
787
788 get_help_info: function(section) {
789 let helpMap;
790 if (typeof proxmoxOnlineHelpInfo !== 'undefined') {
791 helpMap = proxmoxOnlineHelpInfo; // eslint-disable-line no-undef
792 } else if (typeof pveOnlineHelpInfo !== 'undefined') {
793 // be backward compatible with older pve-doc-generators
794 helpMap = pveOnlineHelpInfo; // eslint-disable-line no-undef
795 } else {
796 throw "no global OnlineHelpInfo map declared";
797 }
798
799 if (helpMap[section]) {
800 return helpMap[section];
801 }
802 // try to normalize - and _ separators, to support asciidoc and sphinx
803 // references at the same time.
804 let section_minus_normalized = section.replace(/_/, '-');
805 if (helpMap[section_minus_normalized]) {
806 return helpMap[section_minus_normalized];
807 }
808 let section_underscore_normalized = section.replace(/-/, '_');
809 return helpMap[section_underscore_normalized];
810 },
811
812 get_help_link: function(section) {
813 let info = Proxmox.Utils.get_help_info(section);
814 if (!info) {
815 return undefined;
816 }
817 return window.location.origin + info.link;
818 },
819
820 openXtermJsViewer: function(vmtype, vmid, nodename, vmname, cmd) {
821 let url = Ext.Object.toQueryString({
822 console: vmtype, // kvm, lxc, upgrade or shell
823 xtermjs: 1,
824 vmid: vmid,
825 vmname: vmname,
826 node: nodename,
827 cmd: cmd,
828
829 });
830 let nw = window.open("?" + url, '_blank', 'toolbar=no,location=no,status=no,menubar=no,resizable=yes,width=800,height=420');
831 if (nw) {
832 nw.focus();
833 }
834 },
835
836 },
837
838 singleton: true,
839 constructor: function() {
840 let me = this;
841 Ext.apply(me, me.utilities);
842
843 let IPV4_OCTET = "(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])";
844 let IPV4_REGEXP = "(?:(?:" + IPV4_OCTET + "\\.){3}" + IPV4_OCTET + ")";
845 let IPV6_H16 = "(?:[0-9a-fA-F]{1,4})";
846 let IPV6_LS32 = "(?:(?:" + IPV6_H16 + ":" + IPV6_H16 + ")|" + IPV4_REGEXP + ")";
847 let IPV4_CIDR_MASK = "([0-9]{1,2})";
848 let IPV6_CIDR_MASK = "([0-9]{1,3})";
849
850
851 me.IP4_match = new RegExp("^(?:" + IPV4_REGEXP + ")$");
852 me.IP4_cidr_match = new RegExp("^(?:" + IPV4_REGEXP + ")/" + IPV4_CIDR_MASK + "$");
853
854 /* eslint-disable no-useless-concat,no-multi-spaces */
855 let IPV6_REGEXP = "(?:" +
856 "(?:(?:" + "(?:" + IPV6_H16 + ":){6})" + IPV6_LS32 + ")|" +
857 "(?:(?:" + "::" + "(?:" + IPV6_H16 + ":){5})" + IPV6_LS32 + ")|" +
858 "(?:(?:(?:" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){4})" + IPV6_LS32 + ")|" +
859 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,1}" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){3})" + IPV6_LS32 + ")|" +
860 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,2}" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){2})" + IPV6_LS32 + ")|" +
861 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,3}" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){1})" + IPV6_LS32 + ")|" +
862 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,4}" + IPV6_H16 + ")?::" + ")" + IPV6_LS32 + ")|" +
863 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,5}" + IPV6_H16 + ")?::" + ")" + IPV6_H16 + ")|" +
864 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,7}" + IPV6_H16 + ")?::" + ")" + ")" +
865 ")";
866 /* eslint-enable no-useless-concat,no-multi-spaces */
867
868 me.IP6_match = new RegExp("^(?:" + IPV6_REGEXP + ")$");
869 me.IP6_cidr_match = new RegExp("^(?:" + IPV6_REGEXP + ")/" + IPV6_CIDR_MASK + "$");
870 me.IP6_bracket_match = new RegExp("^\\[(" + IPV6_REGEXP + ")\\]");
871
872 me.IP64_match = new RegExp("^(?:" + IPV6_REGEXP + "|" + IPV4_REGEXP + ")$");
873 me.IP64_cidr_match = new RegExp("^(?:" + IPV6_REGEXP + "/" + IPV6_CIDR_MASK + ")|(?:" + IPV4_REGEXP + "/" + IPV4_CIDR_MASK + ")$");
874
875 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])?))";
876 me.DnsName_match = new RegExp("^" + DnsName_REGEXP + "$");
877
878 me.HostPort_match = new RegExp("^(" + IPV4_REGEXP + "|" + DnsName_REGEXP + ")(:\\d+)?$");
879 me.HostPortBrackets_match = new RegExp("^\\[(?:" + IPV6_REGEXP + "|" + IPV4_REGEXP + "|" + DnsName_REGEXP + ")\\](:\\d+)?$");
880 me.IP6_dotnotation_match = new RegExp("^" + IPV6_REGEXP + "(\\.\\d+)?$");
881 me.Vlan_match = /^vlan(\\d+)/;
882 me.VlanInterface_match = /(\\w+)\\.(\\d+)/;
883 },
884 });