]> git.proxmox.com Git - pve-manager.git/blob - www/manager/Utils.js
use better task descriptions
[pve-manager.git] / www / manager / Utils.js
1 Ext.ns('PVE');
2
3 // avoid errors when running without development tools
4 if (!Ext.isDefined(Ext.global.console)) {
5 var console = {
6 dir: function() {},
7 log: function() {}
8 };
9 }
10 console.log("Starting PVE Manager");
11
12 Ext.Ajax.defaultHeaders = {
13 'Accept': 'application/json'
14 };
15
16 // do not send '_dc' parameter
17 Ext.Ajax.disableCaching = false;
18
19 Ext.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
28 // custom Vtypes
29 Ext.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 },
60 StorageIdText: "ID contains illegal characters (allowed characters: 'a-z', '0-9', '-', '_' and '.')",
61
62 HttpProxy: function(v) {
63 return (/^http:\/\/.*$/).test(v);
64 },
65 HttpProxyText: "Must confirm to schema 'http://.*' (example: 'http://username:password@host:port/')"
66 });
67
68 // we dont want that a displayfield set the form dirty flag!
69 Ext.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
76 Ext.override(Ext.form.field.ComboBox, {
77 onLoad: function() {
78 this.setValue(this.value, false);
79 this.callOverridden(arguments);
80 }
81 });
82
83 Ext.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',
105 l26: 'Linux 3.X/2.6 Kernel'
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
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
208 render_kvm_vga_driver: function (value) {
209 if (!value) {
210 return 'OS default';
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 }
322 var result = Ext.decode(response.responseText);
323 response.result = result || {};
324 var msg = "Connection error - server offline?";
325 if (response.aborted) {
326 msg = 'Transaction aborted.';
327 } else if (response.timedout) {
328 msg = 'Communication failure: Timeout.';
329 } else if (response.status && response.statusText) {
330 msg = 'Connection error ' + response.status + ': ' + response.statusText;
331 }
332 response.htmlStatus = msg;
333 Ext.callback(callbackFn, options.scope, [options, false, response]);
334 Ext.callback(failureFn, options.scope, [response, options]);
335 }
336 });
337 };
338
339 createWrapper(reqOpts.success, reqOpts.callback, reqOpts.failure);
340
341 var target = newopts.waitMsgTarget;
342 if (target) {
343 // Note: ExtJS bug - this does not work when component is not rendered
344 target.setLoading(newopts.waitMsg, true);
345 }
346 Ext.Ajax.request(newopts);
347 },
348
349 assemble_field_data: function(values, data) {
350 if (Ext.isObject(data)) {
351 Ext.Object.each(data, function(name, val) {
352 if (values.hasOwnProperty(name)) {
353 var bucket = values[name];
354 if (!Ext.isArray(bucket)) {
355 bucket = values[name] = [bucket];
356 }
357 if (Ext.isArray(val)) {
358 values[name] = bucket.concat(val);
359 } else {
360 bucket.push(val);
361 }
362 } else {
363 values[name] = val;
364 }
365 });
366 }
367 },
368
369 format_task_description: function(type, id) {
370
371 if (type == 'vncproxy') {
372 return "VNC connection to VM/CT " + id;
373 }
374
375 if (type == 'vncshell') {
376 return "VNC shell";
377 }
378
379 if (type == 'qmigrate') {
380 return "Migrate VM " + id;
381 }
382
383 if (type == 'vzcreate') {
384 return "Create CT " + id;
385 }
386
387 if (type == 'vzdestroy') {
388 return "Destroy CT " + id;
389 }
390
391 if (type == 'vzstart') {
392 return "Start CT " + id;
393 }
394
395 if (type == 'vzstop') {
396 return "Stop CT " + id;
397 }
398
399 return type;
400 },
401
402
403 parse_task_upid: function(upid) {
404 var task = {};
405
406 var res = upid.match(/^UPID:(\S+):([0-9A-Fa-f]{8}):([0-9A-Fa-f]{8}):([0-9A-Fa-f]{8}):([^:\s]+):([^:\s]*):([^:\s]+):$/);
407 if (!res) {
408 throw "unable to parse upid '" + upid + "'";
409 }
410 task.node = res[1];
411 task.pid = parseInt(res[2], 16);
412 task.pstart = parseInt(res[3], 16);
413 task.starttime = parseInt(res[4], 16);
414 task.type = res[5];
415 task.id = res[6];
416 task.user = res[7];
417
418 task.desc = PVE.Utils.format_task_description(task.type, task.id);
419
420 return task;
421 },
422
423 format_size: function(size) {
424
425 var kb = size / 1024;
426
427 if (kb < 1024) {
428 return kb.toFixed(0) + "KB";
429 }
430
431 var mb = size / (1024*1024);
432
433 if (mb < 1024) {
434 return mb.toFixed(0) + "MB";
435 }
436
437 var gb = mb / 1024;
438
439 if (gb < 1024) {
440 return gb.toFixed(2) + "GB";
441 }
442
443 var tb = gb / 1024;
444
445 return tb.toFixed(2) + "TB";
446
447 },
448
449 format_html_bar: function(per, text) {
450
451 return "<div class='pve-bar-wrap'>" + text + "<div class='pve-bar-border'>" +
452 "<div class='pve-bar-inner' style='width:" + per + "%;'></div>" +
453 "</div></div>";
454
455 },
456
457 format_cpu_bar: function(per1, per2, text) {
458
459 return "<div class='pve-bar-border'>" +
460 "<div class='pve-bar-inner' style='width:" + per1 + "%;'></div>" +
461 "<div class='pve-bar-inner2' style='width:" + per2 + "%;'></div>" +
462 "<div class='pve-bar-text'>" + text + "</div>" +
463 "</div>";
464 },
465
466 format_large_bar: function(per, text) {
467
468 if (!text) {
469 text = per.toFixed(1) + "%";
470 }
471
472 return "<div class='pve-largebar-border'>" +
473 "<div class='pve-largebar-inner' style='width:" + per + "%;'></div>" +
474 "<div class='pve-largebar-text'>" + text + "</div>" +
475 "</div>";
476 },
477
478 format_duration_long: function(ut) {
479
480 var days = Math.floor(ut / 86400);
481 ut -= days*86400;
482 var hours = Math.floor(ut / 3600);
483 ut -= hours*3600;
484 var mins = Math.floor(ut / 60);
485 ut -= mins*60;
486
487 var hours_str = '00' + hours.toString();
488 hours_str = hours_str.substr(hours_str.length - 2);
489 var mins_str = "00" + mins.toString();
490 mins_str = mins_str.substr(mins_str.length - 2);
491 var ut_str = "00" + ut.toString();
492 ut_str = ut_str.substr(ut_str.length - 2);
493
494 if (days) {
495 var ds = days > 1 ? 'days' : 'day';
496 return days.toString() + ' ' + ds + ' ' +
497 hours_str + ':' + mins_str + ':' + ut_str;
498 } else {
499 return hours_str + ':' + mins_str + ':' + ut_str;
500 }
501 },
502
503 format_duration_short: function(ut) {
504
505 if (ut < 60) {
506 return ut.toString() + 's';
507 }
508
509 if (ut < 3600) {
510 var mins = ut / 60;
511 return mins.toFixed(0) + 'm';
512 }
513
514 if (ut < 86400) {
515 var hours = ut / 3600;
516 return hours.toFixed(0) + 'h';
517 }
518
519 var days = ut / 86400;
520 return days.toFixed(0) + 'd';
521 },
522
523 format_storage_type: function(value) {
524 if (value === 'dir') {
525 return 'Directory';
526 } else if (value === 'nfs') {
527 return 'NFS';
528 } else if (value === 'lvm') {
529 return 'LVM';
530 } else if (value === 'iscsi') {
531 return 'iSCSI';
532 } else {
533 return 'unknown';
534 }
535 },
536
537 format_boolean_with_default: function(value) {
538 if (Ext.isDefined(value) && value !== '') {
539 return value ? 'Yes' : 'No';
540 }
541 return 'Default';
542 },
543
544 format_boolean: function(value) {
545 return value ? 'Yes' : 'No';
546 },
547
548 format_neg_boolean: function(value) {
549 return !value ? 'Yes' : 'No';
550 },
551
552 format_content_types: function(value) {
553 var cta = [];
554
555 Ext.each(value.split(','), function(ct) {
556 if (ct === 'images') {
557 cta.push('Images');
558 } else if (ct === 'backup') {
559 cta.push('Backups');
560 } else if (ct === 'vztmpl') {
561 cta.push('Templates');
562 } else if (ct === 'iso') {
563 cta.push('ISO');
564 }
565 });
566
567 return cta.join(', ');
568 },
569
570 render_storage_content: function(value, metaData, record) {
571 var data = record.data;
572 if (Ext.isNumber(data.channel) &&
573 Ext.isNumber(data.id) &&
574 Ext.isNumber(data.lun)) {
575 return "CH " +
576 Ext.String.leftPad(data.channel,2, '0') +
577 " ID " + data.id + " LUN " + data.lun;
578 }
579 return data.volid.replace(/^.*:(.*\/)?/,'');
580 },
581
582 render_serverity: function (value) {
583 return PVE.Utils.log_severity_hash[value] || value;
584 },
585
586 render_cpu: function(value, metaData, record, rowIndex, colIndex, store) {
587
588 var maxcpu = record.data.maxcpu;
589
590 if (!record.data.uptime) {
591 return '';
592 }
593
594 if (!(Ext.isNumeric(value) && Ext.isNumeric(maxcpu) && (maxcpu >= 1))) {
595 return '';
596 }
597
598 var per = (value * 100) / maxcpu;
599
600 return per.toFixed(1) + '% of ' + maxcpu.toString() + (maxcpu > 1 ? 'CPUs' : 'CPU');
601 },
602
603 render_size: function(value, metaData, record, rowIndex, colIndex, store) {
604
605 if (!Ext.isNumeric(value)) {
606 return '';
607 }
608
609 return PVE.Utils.format_size(value);
610 },
611
612 render_timestamp: function(value, metaData, record, rowIndex, colIndex, store) {
613 var servertime = new Date(value * 1000);
614 return Ext.Date.format(servertime, 'Y-m-d H:i:s');
615 },
616
617 render_mem_usage: function(value, metaData, record, rowIndex, colIndex, store) {
618
619 var mem = value;
620 var maxmem = record.data.maxmem;
621
622 if (!record.data.uptime) {
623 return '';
624 }
625
626 if (!(Ext.isNumeric(mem) && maxmem)) {
627 return '';
628 }
629
630 var per = (mem * 100) / maxmem;
631
632 return per.toFixed(1) + '%';
633 },
634
635 render_disk_usage: function(value, metaData, record, rowIndex, colIndex, store) {
636
637 var disk = value;
638 var maxdisk = record.data.maxdisk;
639
640 if (!(Ext.isNumeric(disk) && maxdisk)) {
641 return '';
642 }
643
644 var per = (disk * 100) / maxdisk;
645
646 return per.toFixed(1) + '%';
647 },
648
649 render_resource_type: function(value, metaData, record, rowIndex, colIndex, store) {
650
651 var cls = 'pve-itype-icon-' + value;
652
653 if (record.data.running) {
654 metaData.tdCls = cls + "-running";
655 } else {
656 metaData.tdCls = cls;
657 }
658
659 return value;
660 },
661
662 render_uptime: function(value, metaData, record, rowIndex, colIndex, store) {
663
664 var uptime = value;
665
666 if (uptime === undefined) {
667 return '';
668 }
669
670 if (uptime <= 0) {
671 return '-';
672 }
673
674 return PVE.Utils.format_duration_long(uptime);
675 },
676
677 render_upid: function(value, metaData, record) {
678 var type = record.data.type;
679 var id = record.data.id;
680
681 return PVE.Utils.format_task_description(type, id);
682 }
683 }});
684