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