]> git.proxmox.com Git - pve-manager.git/blame - www/manager6/Utils.js
remove redundant model definition
[pve-manager.git] / www / manager6 / Utils.js
CommitLineData
b0a6d326
EK
1Ext.ns('PVE');
2
3// avoid errors when running without development tools
4if (!Ext.isDefined(Ext.global.console)) {
5 var console = {
6 dir: function() {},
7 log: function() {}
8 };
9}
10console.log("Starting PVE Manager");
11
12Ext.Ajax.defaultHeaders = {
13 'Accept': 'application/json'
14};
15
16Ext.Ajax.on('beforerequest', function(conn, options) {
17 if (PVE.CSRFPreventionToken) {
18 if (!options.headers) {
19 options.headers = {};
20 }
21 options.headers.CSRFPreventionToken = PVE.CSRFPreventionToken;
22 }
23});
24
25var IPV4_OCTET = "(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])";
26var IPV4_REGEXP = "(?:(?:" + IPV4_OCTET + "\\.){3}" + IPV4_OCTET + ")";
27var IPV6_H16 = "(?:[0-9a-fA-F]{1,4})";
28var IPV6_LS32 = "(?:(?:" + IPV6_H16 + ":" + IPV6_H16 + ")|" + IPV4_REGEXP + ")";
29
30
31var IP4_match = new RegExp("^(?:" + IPV4_REGEXP + ")$");
8a52defd 32var IP4_cidr_match = new RegExp("^(?:" + IPV4_REGEXP + ")\/[1-3][0-9]?$");
b0a6d326
EK
33
34var IPV6_REGEXP = "(?:" +
35 "(?:(?:" + "(?:" + IPV6_H16 + ":){6})" + IPV6_LS32 + ")|" +
36 "(?:(?:" + "::" + "(?:" + IPV6_H16 + ":){5})" + IPV6_LS32 + ")|" +
37 "(?:(?:(?:" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){4})" + IPV6_LS32 + ")|" +
38 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,1}" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){3})" + IPV6_LS32 + ")|" +
39 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,2}" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){2})" + IPV6_LS32 + ")|" +
40 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,3}" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){1})" + IPV6_LS32 + ")|" +
41 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,4}" + IPV6_H16 + ")?::" + ")" + IPV6_LS32 + ")|" +
42 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,5}" + IPV6_H16 + ")?::" + ")" + IPV6_H16 + ")|" +
43 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,7}" + IPV6_H16 + ")?::" + ")" + ")" +
44 ")";
45
8a52defd
DM
46var IP6_match = new RegExp("^(?:" + IPV6_REGEXP + ")$");
47var IP6_cidr_match = new RegExp("^(?:" + IPV6_REGEXP + ")\/[0-9]{1,3}?$");
aa0819a8 48var IP6_bracket_match = new RegExp("^\\[(" + IPV6_REGEXP + ")\\]");
8a52defd 49
b0a6d326
EK
50var IP64_match = new RegExp("^(?:" + IPV6_REGEXP + "|" + IPV4_REGEXP + ")$");
51
52Ext.define('PVE.Utils', { statics: {
53
54 // this class only contains static functions
55
56 toolkit: undefined, // (extjs|touch), set inside Toolkit.js
57
58 log_severity_hash: {
59 0: "panic",
60 1: "alert",
61 2: "critical",
62 3: "error",
63 4: "warning",
64 5: "notice",
65 6: "info",
66 7: "debug"
67 },
68
69 support_level_hash: {
70 'c': gettext('Community'),
71 'b': gettext('Basic'),
72 's': gettext('Standard'),
73 'p': gettext('Premium')
74 },
75
76 noSubKeyHtml: 'You do not have a valid subscription for this server. Please visit <a target="_blank" href="http://www.proxmox.com/products/proxmox-ve/subscription-service-plans">www.proxmox.com</a> to get a list of available options.',
77
78 kvm_ostypes: {
79 other: gettext('Other OS types'),
80 wxp: 'Microsoft Windows XP/2003',
81 w2k: 'Microsoft Windows 2000',
82 w2k8: 'Microsoft Windows Vista/2008',
83 win7: 'Microsoft Windows 7/2008r2',
84 win8: 'Microsoft Windows 8/2012',
85 l24: 'Linux 2.4 Kernel',
86 l26: 'Linux 3.X/2.6 Kernel',
87 solaris: 'Solaris Kernel'
88 },
89
90 render_kvm_ostype: function (value) {
91 if (!value) {
92 return gettext('Other OS types');
93 }
94 var text = PVE.Utils.kvm_ostypes[value];
95 if (text) {
96 return text + ' (' + value + ')';
97 }
98 return value;
99 },
100
101 render_hotplug_features: function (value) {
102 var fa = [];
103
104 if (!value || (value === '0')) {
105 return gettext('disabled');
106 }
107
108 Ext.each(value.split(','), function(el) {
109 if (el === 'disk') {
110 fa.push(gettext('Disk'));
111 } else if (el === 'network') {
112 fa.push(gettext('Network'));
113 } else if (el === 'usb') {
114 fa.push(gettext('USB'));
115 } else if (el === 'memory') {
116 fa.push(gettext('Memory'));
117 } else if (el === 'cpu') {
118 fa.push(gettext('CPU'));
119 } else {
120 fa.push(el);
121 }
122 });
123
124 return fa.join(', ');
125 },
126
127 network_iface_types: {
128 eth: gettext("Network Device"),
129 bridge: 'Linux Bridge',
130 bond: 'Linux Bond',
131 OVSBridge: 'OVS Bridge',
132 OVSBond: 'OVS Bond',
133 OVSPort: 'OVS Port',
134 OVSIntPort: 'OVS IntPort'
135 },
136
137 render_network_iface_type: function(value) {
138 return PVE.Utils.network_iface_types[value] ||
139 PVE.Utils.unknownText;
140 },
141
142 render_scsihw: function(value) {
143 if (!value) {
144 return PVE.Utils.defaultText + ' (LSI 53C895A)';
145 } else if (value === 'lsi') {
146 return 'LSI 53C895A';
147 } else if (value === 'lsi53c810') {
148 return 'LSI 53C810';
149 } else if (value === 'megasas') {
150 return 'MegaRAID SAS 8708EM2';
151 } else if (value === 'virtio-scsi-pci') {
152 return 'VIRTIO';
153 } else if (value === 'pvscsi') {
154 return 'VMware PVSCSI';
155 } else {
156 return value;
157 }
158 },
159
160 // fixme: auto-generate this
161 // for now, please keep in sync with PVE::Tools::kvmkeymaps
162 kvm_keymaps: {
163 //ar: 'Arabic',
164 da: 'Danish',
165 de: 'German',
166 'de-ch': 'German (Swiss)',
167 'en-gb': 'English (UK)',
0a5b8747 168 'en-us': 'English (USA)',
b0a6d326
EK
169 es: 'Spanish',
170 //et: 'Estonia',
171 fi: 'Finnish',
172 //fo: 'Faroe Islands',
173 fr: 'French',
174 'fr-be': 'French (Belgium)',
175 'fr-ca': 'French (Canada)',
176 'fr-ch': 'French (Swiss)',
177 //hr: 'Croatia',
178 hu: 'Hungarian',
179 is: 'Icelandic',
180 it: 'Italian',
181 ja: 'Japanese',
182 lt: 'Lithuanian',
183 //lv: 'Latvian',
184 mk: 'Macedonian',
185 nl: 'Dutch',
186 //'nl-be': 'Dutch (Belgium)',
187 no: 'Norwegian',
188 pl: 'Polish',
189 pt: 'Portuguese',
190 'pt-br': 'Portuguese (Brazil)',
191 //ru: 'Russian',
192 sl: 'Slovenian',
193 sv: 'Swedish',
194 //th: 'Thai',
195 tr: 'Turkish'
196 },
197
198 kvm_vga_drivers: {
199 std: gettext('Standard VGA'),
200 vmware: gettext('VMWare compatible'),
201 cirrus: 'Cirrus Logic GD5446',
202 qxl: 'SPICE',
203 qxl2: 'SPICE dual monitor',
204 qxl3: 'SPICE three monitors',
205 qxl4: 'SPICE four monitors',
206 serial0: gettext('Serial terminal') + ' 0',
207 serial1: gettext('Serial terminal') + ' 1',
208 serial2: gettext('Serial terminal') + ' 2',
209 serial3: gettext('Serial terminal') + ' 3'
210 },
211
212 render_kvm_language: function (value) {
213 if (!value) {
214 return PVE.Utils.defaultText;
215 }
216 var text = PVE.Utils.kvm_keymaps[value];
217 if (text) {
218 return text + ' (' + value + ')';
219 }
220 return value;
221 },
222
223 kvm_keymap_array: function() {
224 var data = [['', PVE.Utils.render_kvm_language('')]];
225 Ext.Object.each(PVE.Utils.kvm_keymaps, function(key, value) {
226 data.push([key, PVE.Utils.render_kvm_language(value)]);
227 });
228
229 return data;
230 },
231
232 render_console_viewer: function(value) {
233 if (!value) {
234 return PVE.Utils.defaultText + ' (HTML5)';
235 } else if (value === 'applet') {
236 return 'Java VNC Applet';
237 } else if (value === 'vv') {
238 return 'SPICE (remote-viewer)';
239 } else if (value === 'html5') {
240 return 'HTML5 (noVNC)';
241 } else {
242 return value;
243 }
244 },
245
246 language_map: {
247 zh_CN: 'Chinese',
248 ca: 'Catalan',
249 da: 'Danish',
250 en: 'English',
251 eu: 'Euskera (Basque)',
252 fr: 'French',
253 de: 'German',
254 it: 'Italian',
255 ja: 'Japanese',
256 nb: 'Norwegian (Bokmal)',
257 nn: 'Norwegian (Nynorsk)',
258 fa: 'Persian (Farsi)',
259 pl: 'Polish',
260 pt_BR: 'Portuguese (Brazil)',
261 ru: 'Russian',
262 sl: 'Slovenian',
263 es: 'Spanish',
264 sv: 'Swedish',
265 tr: 'Turkish'
266 },
267
268 render_language: function (value) {
269 if (!value) {
270 return PVE.Utils.defaultText + ' (English)';
271 }
272 var text = PVE.Utils.language_map[value];
273 if (text) {
274 return text + ' (' + value + ')';
275 }
276 return value;
277 },
278
279 language_array: function() {
280 var data = [['', PVE.Utils.render_language('')]];
281 Ext.Object.each(PVE.Utils.language_map, function(key, value) {
282 data.push([key, PVE.Utils.render_language(value)]);
283 });
284
285 return data;
286 },
287
288 render_kvm_vga_driver: function (value) {
289 if (!value) {
290 return PVE.Utils.defaultText;
291 }
292 var text = PVE.Utils.kvm_vga_drivers[value];
293 if (text) {
294 return text + ' (' + value + ')';
295 }
296 return value;
297 },
298
299 kvm_vga_driver_array: function() {
300 var data = [['', PVE.Utils.render_kvm_vga_driver('')]];
301 Ext.Object.each(PVE.Utils.kvm_vga_drivers, function(key, value) {
302 data.push([key, PVE.Utils.render_kvm_vga_driver(value)]);
303 });
304
305 return data;
306 },
307
308 render_kvm_startup: function(value) {
309 var startup = PVE.Parser.parseStartup(value);
310
311 var res = 'order=';
312 if (startup.order === undefined) {
313 res += 'any';
314 } else {
315 res += startup.order;
316 }
317 if (startup.up !== undefined) {
318 res += ',up=' + startup.up;
319 }
320 if (startup.down !== undefined) {
321 res += ',down=' + startup.down;
322 }
323
324 return res;
325 },
326
327 authOK: function() {
328 return Ext.util.Cookies.get('PVEAuthCookie');
329 },
330
331 authClear: function() {
332 Ext.util.Cookies.clear("PVEAuthCookie");
333 },
334
335 // fixme: remove - not needed?
336 gridLineHeigh: function() {
337 return 21;
338
339 //if (Ext.isGecko)
340 //return 23;
341 //return 21;
342 },
343
344 extractRequestError: function(result, verbose) {
345 var msg = gettext('Successful');
346
347 if (!result.success) {
348 msg = gettext("Unknown error");
349 if (result.message) {
350 msg = result.message;
351 if (result.status) {
352 msg += ' (' + result.status + ')';
353 }
354 }
355 if (verbose && Ext.isObject(result.errors)) {
356 msg += "<br>";
357 Ext.Object.each(result.errors, function(prop, desc) {
358 msg += "<br><b>" + Ext.htmlEncode(prop) + "</b>: " +
359 Ext.htmlEncode(desc);
360 });
361 }
362 }
363
364 return msg;
365 },
366
367 extractFormActionError: function(action) {
368 var msg;
369 switch (action.failureType) {
370 case Ext.form.action.Action.CLIENT_INVALID:
371 msg = gettext('Form fields may not be submitted with invalid values');
372 break;
373 case Ext.form.action.Action.CONNECT_FAILURE:
374 msg = gettext('Connection error');
375 var resp = action.response;
376 if (resp.status && resp.statusText) {
377 msg += " " + resp.status + ": " + resp.statusText;
378 }
379 break;
380 case Ext.form.action.Action.LOAD_FAILURE:
381 case Ext.form.action.Action.SERVER_INVALID:
382 msg = PVE.Utils.extractRequestError(action.result, true);
383 break;
384 }
385 return msg;
386 },
387
388 // Ext.Ajax.request
389 API2Request: function(reqOpts) {
390
391 var newopts = Ext.apply({
392 waitMsg: gettext('Please wait...')
393 }, reqOpts);
394
395 if (!newopts.url.match(/^\/api2/)) {
396 newopts.url = '/api2/extjs' + newopts.url;
397 }
398 delete newopts.callback;
399
400 var createWrapper = function(successFn, callbackFn, failureFn) {
401 Ext.apply(newopts, {
402 success: function(response, options) {
403 if (options.waitMsgTarget) {
404 if (PVE.Utils.toolkit === 'touch') {
405 options.waitMsgTarget.setMasked(false);
406 } else {
407 options.waitMsgTarget.setLoading(false);
408 }
409 }
410 var result = Ext.decode(response.responseText);
411 response.result = result;
412 if (!result.success) {
413 response.htmlStatus = PVE.Utils.extractRequestError(result, true);
414 Ext.callback(callbackFn, options.scope, [options, false, response]);
415 Ext.callback(failureFn, options.scope, [response, options]);
416 return;
417 }
418 Ext.callback(callbackFn, options.scope, [options, true, response]);
419 Ext.callback(successFn, options.scope, [response, options]);
420 },
421 failure: function(response, options) {
422 if (options.waitMsgTarget) {
423 if (PVE.Utils.toolkit === 'touch') {
424 options.waitMsgTarget.setMasked(false);
425 } else {
426 options.waitMsgTarget.setLoading(false);
427 }
428 }
429 response.result = {};
430 try {
431 response.result = Ext.decode(response.responseText);
432 } catch(e) {}
433 var msg = gettext('Connection error') + ' - server offline?';
434 if (response.aborted) {
435 msg = gettext('Connection error') + ' - aborted.';
436 } else if (response.timedout) {
437 msg = gettext('Connection error') + ' - Timeout.';
438 } else if (response.status && response.statusText) {
439 msg = gettext('Connection error') + ' ' + response.status + ': ' + response.statusText;
440 }
441 response.htmlStatus = msg;
442 Ext.callback(callbackFn, options.scope, [options, false, response]);
443 Ext.callback(failureFn, options.scope, [response, options]);
444 }
445 });
446 };
447
448 createWrapper(reqOpts.success, reqOpts.callback, reqOpts.failure);
449
450 var target = newopts.waitMsgTarget;
451 if (target) {
452 if (PVE.Utils.toolkit === 'touch') {
453 target.setMasked({ xtype: 'loadmask', message: newopts.waitMsg} );
454 } else {
455 // Note: ExtJS bug - this does not work when component is not rendered
456 target.setLoading(newopts.waitMsg);
457 }
458 }
459 Ext.Ajax.request(newopts);
460 },
461
462 assemble_field_data: function(values, data) {
463 if (Ext.isObject(data)) {
464 Ext.Object.each(data, function(name, val) {
465 if (values.hasOwnProperty(name)) {
466 var bucket = values[name];
467 if (!Ext.isArray(bucket)) {
468 bucket = values[name] = [bucket];
469 }
470 if (Ext.isArray(val)) {
471 values[name] = bucket.concat(val);
472 } else {
473 bucket.push(val);
474 }
475 } else {
476 values[name] = val;
477 }
478 });
479 }
480 },
481
482 checked_command: function(orig_cmd) {
483 PVE.Utils.API2Request({
484 url: '/nodes/localhost/subscription',
485 method: 'GET',
486 //waitMsgTarget: me,
487 failure: function(response, opts) {
488 Ext.Msg.alert(gettext('Error'), response.htmlStatus);
489 },
490 success: function(response, opts) {
491 var data = response.result.data;
492
493 if (data.status !== 'Active') {
494 Ext.Msg.show({
495 title: gettext('No valid subscription'),
496 icon: Ext.Msg.WARNING,
497 msg: PVE.Utils.noSubKeyHtml,
498 buttons: Ext.Msg.OK,
499 callback: function(btn) {
500 if (btn !== 'ok') {
501 return;
502 }
503 orig_cmd();
504 }
505 });
506 } else {
507 orig_cmd();
508 }
509 }
510 });
511 },
512
513 task_desc_table: {
514 vncproxy: [ 'VM/CT', gettext('Console') ],
515 spiceproxy: [ 'VM/CT', gettext('Console') + ' (Spice)' ],
516 vncshell: [ '', gettext('Shell') ],
517 spiceshell: [ '', gettext('Shell') + ' (Spice)' ],
518 qmsnapshot: [ 'VM', gettext('Snapshot') ],
519 qmrollback: [ 'VM', gettext('Rollback') ],
520 qmdelsnapshot: [ 'VM', gettext('Delete Snapshot') ],
521 qmcreate: [ 'VM', gettext('Create') ],
522 qmrestore: [ 'VM', gettext('Restore') ],
523 qmdestroy: [ 'VM', gettext('Destroy') ],
524 qmigrate: [ 'VM', gettext('Migrate') ],
525 qmclone: [ 'VM', gettext('Clone') ],
526 qmmove: [ 'VM', gettext('Move disk') ],
527 qmtemplate: [ 'VM', gettext('Convert to template') ],
528 qmstart: [ 'VM', gettext('Start') ],
529 qmstop: [ 'VM', gettext('Stop') ],
530 qmreset: [ 'VM', gettext('Reset') ],
531 qmshutdown: [ 'VM', gettext('Shutdown') ],
532 qmsuspend: [ 'VM', gettext('Suspend') ],
533 qmresume: [ 'VM', gettext('Resume') ],
534 qmconfig: [ 'VM', gettext('Configure') ],
535 vzcreate: ['CT', gettext('Create') ],
536 vzrestore: ['CT', gettext('Restore') ],
537 vzdestroy: ['CT', gettext('Destroy') ],
538 vzmigrate: [ 'CT', gettext('Migrate') ],
539 vzstart: ['CT', gettext('Start') ],
540 vzstop: ['CT', gettext('Stop') ],
541 vzmount: ['CT', gettext('Mount') ],
542 vzumount: ['CT', gettext('Unmount') ],
543 vzshutdown: ['CT', gettext('Shutdown') ],
544 vzsuspend: [ 'CT', gettext('Suspend') ],
545 vzresume: [ 'CT', gettext('Resume') ],
546 hamigrate: [ 'HA', gettext('Migrate') ],
547 hastart: [ 'HA', gettext('Start') ],
548 hastop: [ 'HA', gettext('Stop') ],
549 srvstart: ['SRV', gettext('Start') ],
550 srvstop: ['SRV', gettext('Stop') ],
551 srvrestart: ['SRV', gettext('Restart') ],
552 srvreload: ['SRV', gettext('Reload') ],
553 cephcreatemon: ['Ceph Monitor', gettext('Create') ],
554 cephdestroymon: ['Ceph Monitor', gettext('Destroy') ],
555 cephcreateosd: ['Ceph OSD', gettext('Create') ],
556 cephdestroyosd: ['Ceph OSD', gettext('Destroy') ],
557 imgcopy: ['', gettext('Copy data') ],
558 imgdel: ['', gettext('Erase data') ],
559 download: ['', gettext('Download') ],
560 vzdump: ['', gettext('Backup') ],
561 aptupdate: ['', gettext('Update package database') ],
562 startall: [ '', gettext('Start all VMs and Containers') ],
563 stopall: [ '', gettext('Stop all VMs and Containers') ],
564 migrateall: [ '', gettext('Migrate all VMs and Containers') ]
565 },
566
567 format_task_description: function(type, id) {
568 var farray = PVE.Utils.task_desc_table[type];
569 if (!farray) {
570 return type;
571 }
572 var prefix = farray[0];
573 var text = farray[1];
574 if (prefix) {
575 return prefix + ' ' + id + ' - ' + text;
576 }
577 return text;
578 },
579
580 parse_task_upid: function(upid) {
581 var task = {};
582
583 var res = upid.match(/^UPID:(\S+):([0-9A-Fa-f]{8}):([0-9A-Fa-f]{8,9}):([0-9A-Fa-f]{8}):([^:\s]+):([^:\s]*):([^:\s]+):$/);
584 if (!res) {
585 throw "unable to parse upid '" + upid + "'";
586 }
587 task.node = res[1];
588 task.pid = parseInt(res[2], 16);
589 task.pstart = parseInt(res[3], 16);
590 task.starttime = parseInt(res[4], 16);
591 task.type = res[5];
592 task.id = res[6];
593 task.user = res[7];
594
595 task.desc = PVE.Utils.format_task_description(task.type, task.id);
596
597 return task;
598 },
599
600 format_size: function(size) {
601 /*jslint confusion: true */
602
603 if (size < 1024) {
604 return size;
605 }
606
607 var kb = size / 1024;
608
609 if (kb < 1024) {
610 return kb.toFixed(0) + "KB";
611 }
612
613 var mb = size / (1024*1024);
614
615 if (mb < 1024) {
616 return mb.toFixed(0) + "MB";
617 }
618
619 var gb = mb / 1024;
620
621 if (gb < 1024) {
622 return gb.toFixed(2) + "GB";
623 }
624
625 var tb = gb / 1024;
626
627 return tb.toFixed(2) + "TB";
628
629 },
630
631 format_html_bar: function(per, text) {
632
633 return "<div class='pve-bar-wrap'>" + text + "<div class='pve-bar-border'>" +
634 "<div class='pve-bar-inner' style='width:" + per + "%;'></div>" +
635 "</div></div>";
636
637 },
638
639 format_cpu_bar: function(per1, per2, text) {
640
641 return "<div class='pve-bar-border'>" +
642 "<div class='pve-bar-inner' style='width:" + per1 + "%;'></div>" +
643 "<div class='pve-bar-inner2' style='width:" + per2 + "%;'></div>" +
644 "<div class='pve-bar-text'>" + text + "</div>" +
645 "</div>";
646 },
647
648 format_large_bar: function(per, text) {
649
650 if (!text) {
651 text = per.toFixed(1) + "%";
652 }
653
654 return "<div class='pve-largebar-border'>" +
655 "<div class='pve-largebar-inner' style='width:" + per + "%;'></div>" +
656 "<div class='pve-largebar-text'>" + text + "</div>" +
657 "</div>";
658 },
659
660 format_duration_long: function(ut) {
661
662 var days = Math.floor(ut / 86400);
663 ut -= days*86400;
664 var hours = Math.floor(ut / 3600);
665 ut -= hours*3600;
666 var mins = Math.floor(ut / 60);
667 ut -= mins*60;
668
669 var hours_str = '00' + hours.toString();
670 hours_str = hours_str.substr(hours_str.length - 2);
671 var mins_str = "00" + mins.toString();
672 mins_str = mins_str.substr(mins_str.length - 2);
673 var ut_str = "00" + ut.toString();
674 ut_str = ut_str.substr(ut_str.length - 2);
675
676 if (days) {
677 var ds = days > 1 ? PVE.Utils.daysText : PVE.Utils.dayText;
678 return days.toString() + ' ' + ds + ' ' +
679 hours_str + ':' + mins_str + ':' + ut_str;
680 } else {
681 return hours_str + ':' + mins_str + ':' + ut_str;
682 }
683 },
684
685 format_duration_short: function(ut) {
686
687 if (ut < 60) {
688 return ut.toString() + 's';
689 }
690
691 if (ut < 3600) {
692 var mins = ut / 60;
693 return mins.toFixed(0) + 'm';
694 }
695
696 if (ut < 86400) {
697 var hours = ut / 3600;
698 return hours.toFixed(0) + 'h';
699 }
700
701 var days = ut / 86400;
702 return days.toFixed(0) + 'd';
703 },
704
705 yesText: gettext('Yes'),
706 noText: gettext('No'),
707 noneText: gettext('none'),
708 errorText: gettext('Error'),
709 unknownText: gettext('Unknown'),
710 defaultText: gettext('Default'),
711 daysText: gettext('days'),
712 dayText: gettext('day'),
713 runningText: gettext('running'),
714 stoppedText: gettext('stopped'),
715 neverText: gettext('never'),
716 totalText: gettext('Total'),
717 usedText: gettext('Used'),
718 directoryText: gettext('Directory'),
719 imagesText: gettext('Disk image'),
720 backupFileText: gettext('VZDump backup file'),
2c554952 721 vztmplText: gettext('Container template'),
b0a6d326 722 isoImageText: gettext('ISO image'),
2c554952 723 containersText: gettext('Container'),
b0a6d326
EK
724
725 format_expire: function(date) {
726 if (!date) {
727 return PVE.Utils.neverText;
728 }
729 return Ext.Date.format(date, "Y-m-d");
730 },
731
732 format_storage_type: function(value) {
733 if (value === 'dir') {
734 return PVE.Utils.directoryText;
735 } else if (value === 'nfs') {
736 return 'NFS';
737 } else if (value === 'glusterfs') {
738 return 'GlusterFS';
739 } else if (value === 'lvm') {
740 return 'LVM';
ffd96a3b
DM
741 } else if (value === 'lvmthin') {
742 return 'LVM-Thin';
b0a6d326
EK
743 } else if (value === 'iscsi') {
744 return 'iSCSI';
745 } else if (value === 'rbd') {
746 return 'RBD';
747 } else if (value === 'sheepdog') {
748 return 'Sheepdog';
749 } else if (value === 'zfs') {
750 return 'ZFS over iSCSI';
751 } else if (value === 'zfspool') {
752 return 'ZFS';
753 } else if (value === 'iscsidirect') {
754 return 'iSCSIDirect';
ffd96a3b
DM
755 } else if (value === 'drbd') {
756 return 'DRBD';
b0a6d326
EK
757 } else {
758 return PVE.Utils.unknownText;
759 }
760 },
761
762 format_boolean_with_default: function(value) {
763 if (Ext.isDefined(value) && value !== '') {
764 return value ? PVE.Utils.yesText : PVE.Utils.noText;
765 }
766 return PVE.Utils.defaultText;
767 },
768
769 format_boolean: function(value) {
770 return value ? PVE.Utils.yesText : PVE.Utils.noText;
771 },
772
773 format_neg_boolean: function(value) {
774 return !value ? PVE.Utils.yesText : PVE.Utils.noText;
775 },
776
777 format_content_types: function(value) {
778 var cta = [];
779
780 Ext.each(value.split(',').sort(), function(ct) {
781 if (ct === 'images') {
782 cta.push(PVE.Utils.imagesText);
783 } else if (ct === 'backup') {
784 cta.push(PVE.Utils.backupFileText);
785 } else if (ct === 'vztmpl') {
786 cta.push(PVE.Utils.vztmplText);
787 } else if (ct === 'iso') {
788 cta.push(PVE.Utils.isoImageText);
789 } else if (ct === 'rootdir') {
790 cta.push(PVE.Utils.containersText);
791 }
792 });
793
794 return cta.join(', ');
795 },
796
797 render_storage_content: function(value, metaData, record) {
798 var data = record.data;
799 if (Ext.isNumber(data.channel) &&
800 Ext.isNumber(data.id) &&
801 Ext.isNumber(data.lun)) {
802 return "CH " +
803 Ext.String.leftPad(data.channel,2, '0') +
804 " ID " + data.id + " LUN " + data.lun;
805 }
806 return data.volid.replace(/^.*:(.*\/)?/,'');
807 },
808
809 render_serverity: function (value) {
810 return PVE.Utils.log_severity_hash[value] || value;
811 },
812
813 render_cpu: function(value, metaData, record, rowIndex, colIndex, store) {
814
815 if (!(record.data.uptime && Ext.isNumeric(value))) {
816 return '';
817 }
818
819 var maxcpu = record.data.maxcpu || 1;
820
821 if (!Ext.isNumeric(maxcpu) && (maxcpu >= 1)) {
822 return '';
823 }
824
825 var per = value * 100;
826
827 return per.toFixed(1) + '% of ' + maxcpu.toString() + (maxcpu > 1 ? 'CPUs' : 'CPU');
828 },
829
830 render_size: function(value, metaData, record, rowIndex, colIndex, store) {
831 /*jslint confusion: true */
832
833 if (!Ext.isNumeric(value)) {
834 return '';
835 }
836
837 return PVE.Utils.format_size(value);
838 },
839
840 render_timestamp: function(value, metaData, record, rowIndex, colIndex, store) {
841 var servertime = new Date(value * 1000);
842 return Ext.Date.format(servertime, 'Y-m-d H:i:s');
843 },
844
845 render_mem_usage: function(value, metaData, record, rowIndex, colIndex, store) {
846
847 var mem = value;
848 var maxmem = record.data.maxmem;
849
850 if (!record.data.uptime) {
851 return '';
852 }
853
854 if (!(Ext.isNumeric(mem) && maxmem)) {
855 return '';
856 }
857
858 var per = (mem * 100) / maxmem;
859
860 return per.toFixed(1) + '%';
861 },
862
863 render_disk_usage: function(value, metaData, record, rowIndex, colIndex, store) {
864
865 var disk = value;
866 var maxdisk = record.data.maxdisk;
867
868 if (!(Ext.isNumeric(disk) && maxdisk)) {
869 return '';
870 }
871
872 var per = (disk * 100) / maxdisk;
873
874 return per.toFixed(1) + '%';
875 },
876
877 render_resource_type: function(value, metaData, record, rowIndex, colIndex, store) {
878
879 var cls = 'pve-itype-icon-' + value;
880
881 if (record.data.running) {
882 metaData.tdCls = cls + "-running";
883 } else if (record.data.template) {
884 metaData.tdCls = cls + "-template";
885 } else {
886 metaData.tdCls = cls;
887 }
888
889 return value;
890 },
891
892 render_uptime: function(value, metaData, record, rowIndex, colIndex, store) {
893
894 var uptime = value;
895
896 if (uptime === undefined) {
897 return '';
898 }
899
900 if (uptime <= 0) {
901 return '-';
902 }
903
904 return PVE.Utils.format_duration_long(uptime);
905 },
906
907 render_support_level: function(value, metaData, record) {
908 return PVE.Utils.support_level_hash[value] || '-';
909 },
910
911 render_upid: function(value, metaData, record) {
912 var type = record.data.type;
913 var id = record.data.id;
914
915 return PVE.Utils.format_task_description(type, id);
916 },
917
918 dialog_title: function(subject, create, isAdd) {
919 if (create) {
920 if (isAdd) {
921 return gettext('Add') + ': ' + subject;
922 } else {
923 return gettext('Create') + ': ' + subject;
924 }
925 } else {
926 return gettext('Edit') + ': ' + subject;
927 }
928 },
aa0819a8
WB
929
930 windowHostname: function() {
931 return window.location.hostname.replace(IP6_bracket_match,
932 function(m, addr, offset, original) { return addr; });
933 },
b0a6d326
EK
934
935 openDefaultConsoleWindow: function(allowSpice, vmtype, vmid, nodename, vmname) {
936 var dv = PVE.Utils.defaultViewer(allowSpice);
937 PVE.Utils.openConsoleWindow(dv, vmtype, vmid, nodename, vmname);
938 },
939
940 openConsoleWindow: function(viewer, vmtype, vmid, nodename, vmname) {
9e361643 941 // kvm, lxc, shell, upgrade
b0a6d326 942
9e361643 943 if (vmid == undefined && (vmtype === 'kvm' || vmtype === 'lxc')) {
b0a6d326
EK
944 throw "missing vmid";
945 }
946
947 if (!nodename) {
948 throw "no nodename specified";
949 }
950
951 if (viewer === 'applet' || viewer === 'html5') {
952 PVE.Utils.openVNCViewer(vmtype, vmid, nodename, vmname, viewer === 'html5');
953 } else if (viewer === 'vv') {
954 var url;
aa0819a8 955 var params = { proxy: PVE.Utils.windowHostname() };
b0a6d326
EK
956 if (vmtype === 'kvm') {
957 url = '/nodes/' + nodename + '/qemu/' + vmid.toString() + '/spiceproxy';
958 PVE.Utils.openSpiceViewer(url, params);
9e361643
DM
959 } else if (vmtype === 'lxc') {
960 url = '/nodes/' + nodename + '/lxc/' + vmid.toString() + '/spiceproxy';
b0a6d326
EK
961 PVE.Utils.openSpiceViewer(url, params);
962 } else if (vmtype === 'shell') {
963 url = '/nodes/' + nodename + '/spiceshell';
964 PVE.Utils.openSpiceViewer(url, params);
965 } else if (vmtype === 'upgrade') {
966 url = '/nodes/' + nodename + '/spiceshell';
967 params.upgrade = 1;
968 PVE.Utils.openSpiceViewer(url, params);
969 }
970 } else {
971 throw "unknown viewer type";
972 }
973 },
974
975 defaultViewer: function(allowSpice) {
976 var vncdefault = 'html5';
977 var dv = PVE.VersionInfo.console || vncdefault;
978 if (dv === 'vv' && !allowSpice) {
979 dv = vncdefault;
980 }
981
982 return dv;
983 },
984
985 openVNCViewer: function(vmtype, vmid, nodename, vmname, novnc) {
986 var url = Ext.urlEncode({
9e361643 987 console: vmtype, // kvm, lxc, upgrade or shell
b0a6d326
EK
988 novnc: novnc ? 1 : 0,
989 vmid: vmid,
990 vmname: vmname,
991 node: nodename
992 });
993 var nw = window.open("?" + url, '_blank', "innerWidth=745,innerheight=427");
994 nw.focus();
995 },
996
997 openSpiceViewer: function(url, params){
998
999 var downloadWithName = function(uri, name) {
1000 var link = Ext.DomHelper.append(document.body, {
1001 tag: 'a',
1002 href: uri,
1003 css : 'display:none;visibility:hidden;height:0px;'
1004 });
1005
1006 // Note: we need to tell android the correct file name extension
1007 // but we do not set 'download' tag for other environments, because
1008 // It can have strange side effects (additional user prompt on firefox)
1009 var andriod = navigator.userAgent.match(/Android/i) ? true : false;
1010 if (andriod) {
1011 link.download = name;
1012 }
1013
1014 if (link.fireEvent) {
1015 link.fireEvent('onclick');
1016 } else {
1017 var evt = document.createEvent("MouseEvents");
1018 evt.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
1019 link.dispatchEvent(evt);
1020 }
1021 };
1022
1023 PVE.Utils.API2Request({
1024 url: url,
1025 params: params,
1026 method: 'POST',
1027 failure: function(response, opts){
1028 Ext.Msg.alert('Error', response.htmlStatus);
1029 },
1030 success: function(response, opts){
1031 var raw = "[virt-viewer]\n";
1032 Ext.Object.each(response.result.data, function(k, v) {
1033 raw += k + "=" + v + "\n";
1034 });
1035 var url = 'data:application/x-virt-viewer;charset=UTF-8,' +
1036 encodeURIComponent(raw);
1037
1038 downloadWithName(url, "pve-spice.vv");
1039 }
1040 });
1041 },
1042
1043 // comp.setLoading() is buggy in ExtJS 4.0.7, so we
1044 // use el.mask() instead
1045 setErrorMask: function(comp, msg) {
1046 var el = comp.el;
1047 if (!el) {
1048 return;
1049 }
1050 if (!msg) {
1051 el.unmask();
1052 } else {
1053 if (msg === true) {
1054 el.mask(gettext("Loading..."));
1055 } else {
1056 el.mask(msg);
1057 }
1058 }
1059 },
1060
1061 monStoreErrors: function(me, store) {
1062 me.mon(store, 'beforeload', function(s, operation, eOpts) {
1063 if (!me.loadCount) {
1064 me.loadCount = 0; // make sure it is numeric
1065 PVE.Utils.setErrorMask(me, true);
1066 }
1067 });
1068
1069 // only works with 'pve' proxy
1070 me.mon(store.proxy, 'afterload', function(proxy, request, success) {
1071 me.loadCount++;
1072
1073 if (success) {
1074 PVE.Utils.setErrorMask(me, false);
1075 return;
1076 }
1077
1078 var msg;
1079 var operation = request.operation;
1080 var error = operation.getError();
1081 if (error.statusText) {
1082 msg = error.statusText + ' (' + error.status + ')';
1083 } else {
1084 msg = gettext('Connection error');
1085 }
1086 PVE.Utils.setErrorMask(me, msg);
1087 });
1088 }
1089
1090}});
1091