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