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