]> git.proxmox.com Git - pve-manager.git/blame - www/manager/Utils.js
fix bug 48: proxy initlop to correct node
[pve-manager.git] / www / manager / Utils.js
CommitLineData
aff192e6
DM
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
16// do not send '_dc' parameter
17Ext.Ajax.disableCaching = false;
18
19Ext.Ajax.on('beforerequest', function(conn, options) {
20 if (PVE.CSRFPreventionToken) {
21 if (!options.headers) {
22 options.headers = {};
23 }
24 options.headers.CSRFPreventionToken = PVE.CSRFPreventionToken;
25 }
26});
27
10b4a988 28// custom Vtypes
aff192e6
DM
29Ext.apply(Ext.form.field.VTypes, {
30 IPAddress: function(v) {
31 return (/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/).test(v);
32 },
33 IPAddressText: 'Must be a numeric IP address',
34 IPAddressMask: /[\d\.]/i,
35
36 MacAddress: function(v) {
37 return (/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/).test(v);
38 },
39 MacAddressMask: /[a-fA-F0-9:]/,
40 MacAddressText: 'Must be a valid MAC address (example: "01:23:45:67:89:ab")',
41
42 BridgeName: function(v) {
43 return (/^vmbr\d{1,4}$/).test(v);
44 },
45 BridgeNameText: 'Allowable bridge names: vmbr<b>N</b>, where 0 <= <b>N</b> <= 9999',
46
47 BondName: function(v) {
48 return (/^bond\d{1,4}$/).test(v);
49 },
50 BondNameText: 'Allowable bond names: bond<b>N</b>, where 0 <= <b>N</b> <= 9999',
51
52 QemuStartDate: function(v) {
53 return (/^(now|\d{4}-\d{1,2}-\d{1,2}(T\d{1,2}:\d{1,2}:\d{1,2})?)$/).test(v);
54 },
55 QemuStartDateText: 'Valid format for date are: "now" or "2006-06-17T16:01:21" or "2006-06-17"',
56
57 StorageId: function(v) {
58 return (/^[a-z][a-z0-9\-\_\.]*[a-z0-9]$/i).test(v);
59 },
10b4a988
DM
60 StorageIdText: "ID contains illegal characters (allowed characters: 'a-z', '0-9', '-', '_' and '.')",
61
62 HttpProxy: function(v) {
63 return (/^http:\/\/.*$/).test(v);
64 },
e7b95416 65 HttpProxyText: "Must confirm to schema 'http://.*' (example: 'http://username:password@host:port/')"
aff192e6
DM
66});
67
68// we dont want that a displayfield set the form dirty flag!
69Ext.override(Ext.form.field.Display, {
70 isDirty: function() { return false; }
71});
72
73// hack: ExtJS does not display the correct value if we
74// call setValue while the store is loading, so we need
75// to call it again after loading
76Ext.override(Ext.form.field.ComboBox, {
77 onLoad: function() {
78 this.setValue(this.value, false);
79 this.callOverridden(arguments);
80 }
81});
82
83Ext.define('PVE.Utils', { statics: {
84
85 // this class only contains static functions
86
87 log_severity_hash: {
88 0: "panic",
89 1: "alert",
90 2: "critical",
91 3: "error",
92 4: "warning",
93 5: "notice",
94 6: "info",
95 7: "debug"
96 },
97
98 kvm_ostypes: {
99 other: 'Other',
100 wxp: 'Microsoft Windows XP/2003',
101 w2k: 'Microsoft Windows 2000',
102 w2k8: 'Microsoft Windows Vista/2008',
103 win7: 'Microsoft Windows 7/2008r2',
104 l24: 'Linux 2.4 Kernel',
1ea7a234 105 l26: 'Linux 3.X/2.6 Kernel'
aff192e6
DM
106 },
107
108 render_kvm_ostype: function (value) {
109 if (!value) {
110 return 'Other';
111 }
112 var text = PVE.Utils.kvm_ostypes[value];
113 if (text) {
114 return text + ' (' + value + ')';
115 }
116 return value;
117 },
118
119 // fixme: auto-generate this
120 // for now, please keep in sync with PVE::Tools::kvmkeymaps
121 kvm_keymaps: {
122 //ar: 'Arabic',
123 dk: 'Danish',
124 de: 'German',
125 'de-ch': 'German (Swiss)',
126 'en-gb': 'English (UK)',
127 'en-us': 'English (USA',
128 es: 'Spanish',
129 //et: 'Estonia',
130 fi: 'Finnish',
131 //fo: 'Faroe Islands',
132 fr: 'French',
133 'fr-be': 'French (Belgium)',
134 'fr-ca': 'French (Canada)',
135 'fr-ch': 'French (Swiss)',
136 //hr: 'Croatia',
137 hu: 'Hungarian',
138 is: 'Icelandic',
139 it: 'Italian',
140 ja: 'Japanese',
141 lt: 'Lithuanian',
142 //lv: 'Latvian',
143 mk: 'Macedonian',
144 nl: 'Dutch',
145 //'nl-be': 'Dutch (Belgium)',
146 no: 'Norwegian',
147 pl: 'Polish',
148 pt: 'Portuguese',
149 'pt-br': 'Portuguese (Brazil)',
150 //ru: 'Russian',
151 si: 'Slovenian'
152 //sv: 'Swedish',
153 //th: 'Thai',
154 //tr: 'Turkish'
155 },
156
157 kvm_vga_drivers: {
158 std: 'Standard VGA',
159 vmware: 'VMWare compatible',
160 cirrus: 'Cirrus Logic GD5446'
161 },
162
163 render_kvm_language: function (value) {
164 if (!value) {
165 return 'Default';
166 }
167 var text = PVE.Utils.kvm_keymaps[value];
168 if (text) {
169 return text + ' (' + value + ')';
170 }
171 return value;
172 },
173
174 kvm_keymap_array: function() {
175 var data = [['', PVE.Utils.render_kvm_language('')]];
176 Ext.Object.each(PVE.Utils.kvm_keymaps, function(key, value) {
177 data.push([key, PVE.Utils.render_kvm_language(value)]);
178 });
179
180 return data;
181 },
182
19fa0647
DM
183 language_map: {
184 en: 'English',
185 de: 'German'
186 },
187
188 render_language: function (value) {
189 if (!value) {
190 return 'Default (English)';
191 }
192 var text = PVE.Utils.language_map[value];
193 if (text) {
194 return text + ' (' + value + ')';
195 }
196 return value;
197 },
198
199 language_array: function() {
200 var data = [['', PVE.Utils.render_language('')]];
201 Ext.Object.each(PVE.Utils.language_map, function(key, value) {
202 data.push([key, PVE.Utils.render_language(value)]);
203 });
204
205 return data;
206 },
207
aff192e6
DM
208 render_kvm_vga_driver: function (value) {
209 if (!value) {
133362ca 210 return 'OS default';
aff192e6
DM
211 }
212 var text = PVE.Utils.kvm_vga_drivers[value];
213 if (text) {
214 return text + ' (' + value + ')';
215 }
216 return value;
217 },
218
219 kvm_vga_driver_array: function() {
220 var data = [['', PVE.Utils.render_kvm_vga_driver('')]];
221 Ext.Object.each(PVE.Utils.kvm_vga_drivers, function(key, value) {
222 data.push([key, PVE.Utils.render_kvm_vga_driver(value)]);
223 });
224
225 return data;
226 },
227
228 authOK: function() {
229 return Ext.util.Cookies.get('PVEAuthCookie');
230 },
231
232 authClear: function() {
233 Ext.util.Cookies.clear("PVEAuthCookie");
234 },
235
236 // fixme: remove - not needed?
237 gridLineHeigh: function() {
238 return 21;
239
240 //if (Ext.isGecko)
241 //return 23;
242 //return 21;
243 },
244
245 extractRequestError: function(result, verbose) {
246 var msg = 'Successful';
247
248 if (!result.success) {
249 msg = "Unknown error";
250 if (result.message) {
251 msg = result.message;
252 if (result.status) {
253 msg += ' (' + result.status + ')';
254 }
255 }
256 if (verbose && Ext.isObject(result.errors)) {
257 msg += "<br>";
258 Ext.Object.each(result.errors, function(prop, desc) {
259 msg += "<br><b>" + Ext.htmlEncode(prop) + "</b>: " +
260 Ext.htmlEncode(desc);
261 });
262 }
263 }
264
265 return msg;
266 },
267
268 extractFormActionError: function(action) {
269 var msg;
270 switch (action.failureType) {
271 case Ext.form.action.Action.CLIENT_INVALID:
272 msg = 'Form fields may not be submitted with invalid values';
273 break;
274 case Ext.form.action.Action.CONNECT_FAILURE:
275 msg = 'Connect failure';
276 var resp = action.response;
277 if (resp.status && resp.statusText) {
278 msg += " " + resp.status + ": " + resp.statusText;
279 }
280 break;
281 case Ext.form.action.Action.LOAD_FAILURE:
282 case Ext.form.action.Action.SERVER_INVALID:
283 msg = PVE.Utils.extractRequestError(action.result, true);
284 break;
285 }
286 return msg;
287 },
288
289 // Ext.Ajax.request
290 API2Request: function(reqOpts) {
291
292 var newopts = Ext.apply({
293 waitMsg: 'Please wait...'
294 }, reqOpts);
295
296 if (!newopts.url.match(/^\/api2/)) {
297 newopts.url = '/api2/extjs' + newopts.url;
298 }
299 delete newopts.callback;
300
301 var createWrapper = function(successFn, callbackFn, failureFn) {
302 Ext.apply(newopts, {
303 success: function(response, options) {
304 if (options.waitMsgTarget) {
305 options.waitMsgTarget.setLoading(false);
306 }
307 var result = Ext.decode(response.responseText);
308 response.result = result;
309 if (!result.success) {
310 response.htmlStatus = PVE.Utils.extractRequestError(result, true);
311 Ext.callback(callbackFn, options.scope, [options, false, response]);
312 Ext.callback(failureFn, options.scope, [response, options]);
313 return;
314 }
315 Ext.callback(callbackFn, options.scope, [options, true, response]);
316 Ext.callback(successFn, options.scope, [response, options]);
317 },
318 failure: function(response, options) {
319 if (options.waitMsgTarget) {
320 options.waitMsgTarget.setLoading(false);
321 }
52406c42
DM
322 response.result = {};
323 try {
324 response.result = Ext.decode(response.responseText);
db16032c 325 } catch(e) {}
aff192e6
DM
326 var msg = "Connection error - server offline?";
327 if (response.aborted) {
328 msg = 'Transaction aborted.';
329 } else if (response.timedout) {
330 msg = 'Communication failure: Timeout.';
331 } else if (response.status && response.statusText) {
332 msg = 'Connection error ' + response.status + ': ' + response.statusText;
333 }
334 response.htmlStatus = msg;
335 Ext.callback(callbackFn, options.scope, [options, false, response]);
336 Ext.callback(failureFn, options.scope, [response, options]);
337 }
338 });
339 };
340
341 createWrapper(reqOpts.success, reqOpts.callback, reqOpts.failure);
342
343 var target = newopts.waitMsgTarget;
344 if (target) {
345 // Note: ExtJS bug - this does not work when component is not rendered
346 target.setLoading(newopts.waitMsg, true);
347 }
348 Ext.Ajax.request(newopts);
349 },
350
351 assemble_field_data: function(values, data) {
352 if (Ext.isObject(data)) {
353 Ext.Object.each(data, function(name, val) {
354 if (values.hasOwnProperty(name)) {
355 var bucket = values[name];
356 if (!Ext.isArray(bucket)) {
357 bucket = values[name] = [bucket];
358 }
359 if (Ext.isArray(val)) {
360 values[name] = bucket.concat(val);
361 } else {
362 bucket.push(val);
363 }
364 } else {
365 values[name] = val;
366 }
367 });
368 }
369 },
370
acc0c13a
DM
371 task_desc_table: {
372 vncproxy: 'VNC connection to VM/CT {0}',
373 vncshell: 'VNC shell',
997b5dd6
DM
374 qmcreate: 'Create VM {0}',
375 qmrestore: 'Restore VM {0}',
376 qmdestroy: 'Destroy VM {0}',
acc0c13a
DM
377 qmigrate: 'Migrate VM {0}',
378 qmstart: 'Start VM {0}',
379 qmstop: 'Stop VM {0}',
380 qmreset: 'Reset VM {0}',
381 qmshutdown: 'Shutdown VM {0}',
382 qmsuspend: 'Suspend VM {0}',
383 qmresume: 'Resume VM {0}',
384 vzcreate: 'Create CT {0}',
aabf3add 385 vzrestore: 'Restore CT {0}',
acc0c13a
DM
386 vzdestroy: 'Destroy CT {0}',
387 vzstart: 'Start CT {0}',
388 vzstop: 'Stop CT {0}',
389 srvstart: 'Start service {0}',
390 srvstop: 'Stop service {0}',
391 srvrestart: 'Restart service {0}',
4a4051d8
DM
392 srvreload: 'Reload service {0}',
393 vzdump: 'Backup'
acc0c13a 394 },
d1233856 395
acc0c13a
DM
396 format_task_description: function(type, id) {
397 var format = PVE.Utils.task_desc_table[type];
398 if (format) {
399 return Ext.String.format(format, id);
d1233856 400 }
aff192e6
DM
401 return type;
402 },
403
aff192e6
DM
404 parse_task_upid: function(upid) {
405 var task = {};
406
55d19d9b 407 var res = upid.match(/^UPID:(\S+):([0-9A-Fa-f]{8}):([0-9A-Fa-f]{8}):([0-9A-Fa-f]{8}):([^:\s]+):([^:\s]*):([^:\s]+):$/);
aff192e6
DM
408 if (!res) {
409 throw "unable to parse upid '" + upid + "'";
410 }
411 task.node = res[1];
412 task.pid = parseInt(res[2], 16);
413 task.pstart = parseInt(res[3], 16);
414 task.starttime = parseInt(res[4], 16);
415 task.type = res[5];
416 task.id = res[6];
417 task.user = res[7];
418
419 task.desc = PVE.Utils.format_task_description(task.type, task.id);
420
421 return task;
422 },
423
424 format_size: function(size) {
a2f57991 425 /*jslint confusion: true */
aff192e6 426
a1d849df
DM
427 if (size < 1024) {
428 return size;
429 }
430
aff192e6
DM
431 var kb = size / 1024;
432
433 if (kb < 1024) {
434 return kb.toFixed(0) + "KB";
435 }
436
437 var mb = size / (1024*1024);
438
439 if (mb < 1024) {
440 return mb.toFixed(0) + "MB";
441 }
442
443 var gb = mb / 1024;
444
445 if (gb < 1024) {
446 return gb.toFixed(2) + "GB";
447 }
448
449 var tb = gb / 1024;
450
451 return tb.toFixed(2) + "TB";
452
453 },
454
455 format_html_bar: function(per, text) {
456
457 return "<div class='pve-bar-wrap'>" + text + "<div class='pve-bar-border'>" +
458 "<div class='pve-bar-inner' style='width:" + per + "%;'></div>" +
459 "</div></div>";
460
461 },
462
463 format_cpu_bar: function(per1, per2, text) {
464
465 return "<div class='pve-bar-border'>" +
466 "<div class='pve-bar-inner' style='width:" + per1 + "%;'></div>" +
467 "<div class='pve-bar-inner2' style='width:" + per2 + "%;'></div>" +
468 "<div class='pve-bar-text'>" + text + "</div>" +
469 "</div>";
470 },
471
472 format_large_bar: function(per, text) {
473
474 if (!text) {
475 text = per.toFixed(1) + "%";
476 }
477
478 return "<div class='pve-largebar-border'>" +
479 "<div class='pve-largebar-inner' style='width:" + per + "%;'></div>" +
480 "<div class='pve-largebar-text'>" + text + "</div>" +
481 "</div>";
482 },
483
484 format_duration_long: function(ut) {
485
486 var days = Math.floor(ut / 86400);
487 ut -= days*86400;
488 var hours = Math.floor(ut / 3600);
489 ut -= hours*3600;
490 var mins = Math.floor(ut / 60);
491 ut -= mins*60;
492
493 var hours_str = '00' + hours.toString();
494 hours_str = hours_str.substr(hours_str.length - 2);
495 var mins_str = "00" + mins.toString();
496 mins_str = mins_str.substr(mins_str.length - 2);
497 var ut_str = "00" + ut.toString();
498 ut_str = ut_str.substr(ut_str.length - 2);
499
500 if (days) {
501 var ds = days > 1 ? 'days' : 'day';
502 return days.toString() + ' ' + ds + ' ' +
503 hours_str + ':' + mins_str + ':' + ut_str;
504 } else {
505 return hours_str + ':' + mins_str + ':' + ut_str;
506 }
507 },
508
509 format_duration_short: function(ut) {
510
511 if (ut < 60) {
512 return ut.toString() + 's';
513 }
514
515 if (ut < 3600) {
516 var mins = ut / 60;
517 return mins.toFixed(0) + 'm';
518 }
519
520 if (ut < 86400) {
521 var hours = ut / 3600;
522 return hours.toFixed(0) + 'h';
523 }
524
525 var days = ut / 86400;
526 return days.toFixed(0) + 'd';
527 },
528
529 format_storage_type: function(value) {
530 if (value === 'dir') {
531 return 'Directory';
532 } else if (value === 'nfs') {
533 return 'NFS';
534 } else if (value === 'lvm') {
535 return 'LVM';
536 } else if (value === 'iscsi') {
537 return 'iSCSI';
538 } else {
539 return 'unknown';
540 }
541 },
542
543 format_boolean_with_default: function(value) {
544 if (Ext.isDefined(value) && value !== '') {
545 return value ? 'Yes' : 'No';
546 }
547 return 'Default';
548 },
549
550 format_boolean: function(value) {
551 return value ? 'Yes' : 'No';
552 },
553
554 format_neg_boolean: function(value) {
555 return !value ? 'Yes' : 'No';
556 },
557
558 format_content_types: function(value) {
559 var cta = [];
560
f29297db 561 Ext.each(value.split(',').sort(), function(ct) {
aff192e6
DM
562 if (ct === 'images') {
563 cta.push('Images');
564 } else if (ct === 'backup') {
565 cta.push('Backups');
566 } else if (ct === 'vztmpl') {
567 cta.push('Templates');
568 } else if (ct === 'iso') {
569 cta.push('ISO');
9f767883
DM
570 } else if (ct === 'rootdir') {
571 cta.push('Containers');
aff192e6
DM
572 }
573 });
574
575 return cta.join(', ');
576 },
577
578 render_storage_content: function(value, metaData, record) {
579 var data = record.data;
580 if (Ext.isNumber(data.channel) &&
581 Ext.isNumber(data.id) &&
582 Ext.isNumber(data.lun)) {
583 return "CH " +
584 Ext.String.leftPad(data.channel,2, '0') +
585 " ID " + data.id + " LUN " + data.lun;
586 }
587 return data.volid.replace(/^.*:(.*\/)?/,'');
588 },
589
590 render_serverity: function (value) {
591 return PVE.Utils.log_severity_hash[value] || value;
592 },
593
594 render_cpu: function(value, metaData, record, rowIndex, colIndex, store) {
595
596 var maxcpu = record.data.maxcpu;
597
598 if (!record.data.uptime) {
599 return '';
600 }
601
602 if (!(Ext.isNumeric(value) && Ext.isNumeric(maxcpu) && (maxcpu >= 1))) {
603 return '';
604 }
605
606 var per = (value * 100) / maxcpu;
607
608 return per.toFixed(1) + '% of ' + maxcpu.toString() + (maxcpu > 1 ? 'CPUs' : 'CPU');
609 },
610
611 render_size: function(value, metaData, record, rowIndex, colIndex, store) {
a2f57991 612 /*jslint confusion: true */
aff192e6
DM
613
614 if (!Ext.isNumeric(value)) {
615 return '';
616 }
617
618 return PVE.Utils.format_size(value);
619 },
620
621 render_timestamp: function(value, metaData, record, rowIndex, colIndex, store) {
622 var servertime = new Date(value * 1000);
623 return Ext.Date.format(servertime, 'Y-m-d H:i:s');
624 },
625
626 render_mem_usage: function(value, metaData, record, rowIndex, colIndex, store) {
627
628 var mem = value;
629 var maxmem = record.data.maxmem;
630
631 if (!record.data.uptime) {
632 return '';
633 }
634
635 if (!(Ext.isNumeric(mem) && maxmem)) {
636 return '';
637 }
638
639 var per = (mem * 100) / maxmem;
640
641 return per.toFixed(1) + '%';
642 },
643
644 render_disk_usage: function(value, metaData, record, rowIndex, colIndex, store) {
645
646 var disk = value;
647 var maxdisk = record.data.maxdisk;
648
649 if (!(Ext.isNumeric(disk) && maxdisk)) {
650 return '';
651 }
652
653 var per = (disk * 100) / maxdisk;
654
655 return per.toFixed(1) + '%';
656 },
657
658 render_resource_type: function(value, metaData, record, rowIndex, colIndex, store) {
659
660 var cls = 'pve-itype-icon-' + value;
661
662 if (record.data.running) {
663 metaData.tdCls = cls + "-running";
664 } else {
665 metaData.tdCls = cls;
666 }
667
668 return value;
669 },
670
671 render_uptime: function(value, metaData, record, rowIndex, colIndex, store) {
672
673 var uptime = value;
674
675 if (uptime === undefined) {
676 return '';
677 }
678
679 if (uptime <= 0) {
680 return '-';
681 }
682
683 return PVE.Utils.format_duration_long(uptime);
684 },
685
686 render_upid: function(value, metaData, record) {
687 var type = record.data.type;
688 var id = record.data.id;
689
690 return PVE.Utils.format_task_description(type, id);
176eee4f
DM
691 },
692
693 openConoleWindow: function(vmtype, vmid, nodename) {
694 var url = Ext.urlEncode({
695 console: vmtype, // kvm or openvz
696 vmid: vmid,
697 node: nodename
698 });
699 var nw = window.open("?" + url, '_blank',
700 "innerWidth=745,innerheight=427");
701 nw.focus();
aff192e6 702 }
176eee4f 703
aff192e6
DM
704}});
705