]> git.proxmox.com Git - pve-manager.git/blame - www/manager/Utils.js
use anchor with download tag to open spice console
[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
035cde2b
DM
28var IPV4_OCTET = "(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])";
29var IPV4_REGEXP = "(?:(?:" + IPV4_OCTET + "\\.){3}" + IPV4_OCTET + ")";
30var IPV6_H16 = "(?:[0-9a-fA-F]{1,4})";
31var IPV6_LS32 = "(?:(?:" + IPV6_H16 + ":" + IPV6_H16 + ")|" + IPV4_REGEXP + ")";
32
33
c9160a27 34var IP4_match = new RegExp("^(?:" + IPV4_REGEXP + ")$");
035cde2b
DM
35
36var IPV6_REGEXP = "(?:" +
37 "(?:(?:" + "(?:" + IPV6_H16 + ":){6})" + IPV6_LS32 + ")|" +
38 "(?:(?:" + "::" + "(?:" + IPV6_H16 + ":){5})" + IPV6_LS32 + ")|" +
39 "(?:(?:(?:" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){4})" + IPV6_LS32 + ")|" +
40 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,1}" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){3})" + IPV6_LS32 + ")|" +
41 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,2}" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){2})" + IPV6_LS32 + ")|" +
42 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,3}" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){1})" + IPV6_LS32 + ")|" +
43 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,4}" + IPV6_H16 + ")?::" + ")" + IPV6_LS32 + ")|" +
44 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,5}" + IPV6_H16 + ")?::" + ")" + IPV6_H16 + ")|" +
45 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,7}" + IPV6_H16 + ")?::" + ")" + ")" +
46 ")";
47
c9160a27 48var IP64_match = new RegExp("^(?:" + IPV6_REGEXP + "|" + IPV4_REGEXP + ")$");
035cde2b 49
10b4a988 50// custom Vtypes
aff192e6
DM
51Ext.apply(Ext.form.field.VTypes, {
52 IPAddress: function(v) {
c9160a27 53 return IP4_match.test(v);
aff192e6 54 },
a2dca26b 55 IPAddressText: gettext('Example') + ': 192.168.1.1',
aff192e6
DM
56 IPAddressMask: /[\d\.]/i,
57
035cde2b
DM
58 IP64Address: function(v) {
59 return IP64_match.test(v);
60 },
61 IP64AddressText: gettext('Example') + ': 192.168.1.1 2001:DB8::42',
62 IP64AddressMask: /[A-Fa-f0-9\.:]/,
63
aff192e6
DM
64 MacAddress: function(v) {
65 return (/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/).test(v);
66 },
67 MacAddressMask: /[a-fA-F0-9:]/,
a2dca26b 68 MacAddressText: gettext('Example') + ': 01:23:45:67:89:ab',
aff192e6
DM
69
70 BridgeName: function(v) {
71 return (/^vmbr\d{1,4}$/).test(v);
72 },
a2dca26b 73 BridgeNameText: gettext('Format') + ': vmbr<b>N</b>, where 0 <= <b>N</b> <= 9999',
aff192e6
DM
74
75 BondName: function(v) {
76 return (/^bond\d{1,4}$/).test(v);
77 },
a2dca26b 78 BondNameText: gettext('Format') + ': bond<b>N</b>, where 0 <= <b>N</b> <= 9999',
aff192e6
DM
79
80 QemuStartDate: function(v) {
81 return (/^(now|\d{4}-\d{1,2}-\d{1,2}(T\d{1,2}:\d{1,2}:\d{1,2})?)$/).test(v);
82 },
a2dca26b 83 QemuStartDateText: gettext('Format') + ': "now" or "2006-06-17T16:01:21" or "2006-06-17"',
aff192e6
DM
84
85 StorageId: function(v) {
86 return (/^[a-z][a-z0-9\-\_\.]*[a-z0-9]$/i).test(v);
87 },
a2dca26b 88 StorageIdText: gettext("Allowed characters") + ": 'a-z', '0-9', '-', '_', '.'",
10b4a988
DM
89
90 HttpProxy: function(v) {
91 return (/^http:\/\/.*$/).test(v);
92 },
667b2be9
DM
93 HttpProxyText: gettext('Example') + ": http://username:password&#64;host:port/",
94
95 DnsName: function(v) {
0d201dfe 96 return (/^(([a-zA-Z0-9]([a-zA-Z0-9\-]*[a-zA-Z0-9])?)\.)*([A-Za-z0-9]([A-Za-z0-9\-]*[A-Za-z0-9])?)$/).test(v);
667b2be9
DM
97 },
98 DnsNameText: gettext('This is not a valid DNS name')
aff192e6
DM
99});
100
101// we dont want that a displayfield set the form dirty flag!
102Ext.override(Ext.form.field.Display, {
103 isDirty: function() { return false; }
104});
105
106// hack: ExtJS does not display the correct value if we
107// call setValue while the store is loading, so we need
108// to call it again after loading
109Ext.override(Ext.form.field.ComboBox, {
110 onLoad: function() {
111 this.setValue(this.value, false);
112 this.callOverridden(arguments);
113 }
114});
115
116Ext.define('PVE.Utils', { statics: {
117
118 // this class only contains static functions
119
120 log_severity_hash: {
121 0: "panic",
122 1: "alert",
123 2: "critical",
124 3: "error",
125 4: "warning",
126 5: "notice",
127 6: "info",
128 7: "debug"
129 },
130
16b69b6c
DM
131 support_level_hash: {
132 'c': gettext('Community'),
133 'b': gettext('Basic'),
134 's': gettext('Standard'),
135 'p': gettext('Premium')
136 },
137
9baa9680
DM
138 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.',
139
aff192e6 140 kvm_ostypes: {
2ed04b3c 141 other: gettext('Other OS types'),
aff192e6
DM
142 wxp: 'Microsoft Windows XP/2003',
143 w2k: 'Microsoft Windows 2000',
144 w2k8: 'Microsoft Windows Vista/2008',
145 win7: 'Microsoft Windows 7/2008r2',
1d7334d2 146 win8: 'Microsoft Windows 8/2012',
aff192e6 147 l24: 'Linux 2.4 Kernel',
51770186
AD
148 l26: 'Linux 3.X/2.6 Kernel',
149 solaris: 'Solaris Kernel'
aff192e6
DM
150 },
151
152 render_kvm_ostype: function (value) {
153 if (!value) {
2ed04b3c 154 return gettext('Other OS types');
aff192e6
DM
155 }
156 var text = PVE.Utils.kvm_ostypes[value];
157 if (text) {
158 return text + ' (' + value + ')';
159 }
160 return value;
161 },
162
74184048
DM
163 render_scsihw: function(value) {
164 if (!value) {
e824ec03 165 return PVE.Utils.defaultText + ' (LSI 53C895A)';
74184048
DM
166 } else if (value === 'lsi') {
167 return 'LSI 53C895A';
e824ec03
DM
168 } else if (value === 'lsi53c810') {
169 return 'LSI 53C810';
74184048
DM
170 } else if (value === 'megasas') {
171 return 'MegaRAID SAS 8708EM2';
172 } else if (value === 'virtio-scsi-pci') {
173 return 'VIRTIO';
ef9e9863
DM
174 } else if (value === 'pvscsi') {
175 return 'VMware PVSCSI';
74184048
DM
176 } else {
177 return value;
178 }
179 },
180
aff192e6
DM
181 // fixme: auto-generate this
182 // for now, please keep in sync with PVE::Tools::kvmkeymaps
183 kvm_keymaps: {
184 //ar: 'Arabic',
5fe5283f 185 da: 'Danish',
aff192e6
DM
186 de: 'German',
187 'de-ch': 'German (Swiss)',
188 'en-gb': 'English (UK)',
189 'en-us': 'English (USA',
190 es: 'Spanish',
191 //et: 'Estonia',
192 fi: 'Finnish',
193 //fo: 'Faroe Islands',
194 fr: 'French',
195 'fr-be': 'French (Belgium)',
196 'fr-ca': 'French (Canada)',
197 'fr-ch': 'French (Swiss)',
198 //hr: 'Croatia',
199 hu: 'Hungarian',
200 is: 'Icelandic',
201 it: 'Italian',
202 ja: 'Japanese',
203 lt: 'Lithuanian',
204 //lv: 'Latvian',
205 mk: 'Macedonian',
206 nl: 'Dutch',
207 //'nl-be': 'Dutch (Belgium)',
208 no: 'Norwegian',
209 pl: 'Polish',
210 pt: 'Portuguese',
211 'pt-br': 'Portuguese (Brazil)',
212 //ru: 'Russian',
b4e7aa2c 213 sl: 'Slovenian',
1133bd83 214 sv: 'Swedish',
aff192e6 215 //th: 'Thai',
1133bd83 216 tr: 'Turkish'
aff192e6
DM
217 },
218
219 kvm_vga_drivers: {
0070ee37
DP
220 std: gettext('Standard VGA'),
221 vmware: gettext('VMWare compatible'),
0c47a682 222 cirrus: 'Cirrus Logic GD5446',
76d0de20 223 qxl: 'SPICE',
caf64d77
DM
224 qxl2: 'SPICE dual monitor',
225 qxl3: 'SPICE three monitors',
226 qxl4: 'SPICE four monitors',
0070ee37
DP
227 serial0: gettext('Serial terminal') + ' 0',
228 serial1: gettext('Serial terminal') + ' 1',
229 serial2: gettext('Serial terminal') + ' 2',
230 serial3: gettext('Serial terminal') + ' 3'
aff192e6
DM
231 },
232
233 render_kvm_language: function (value) {
234 if (!value) {
2ed04b3c 235 return PVE.Utils.defaultText;
aff192e6
DM
236 }
237 var text = PVE.Utils.kvm_keymaps[value];
238 if (text) {
239 return text + ' (' + value + ')';
240 }
241 return value;
242 },
243
244 kvm_keymap_array: function() {
245 var data = [['', PVE.Utils.render_kvm_language('')]];
246 Ext.Object.each(PVE.Utils.kvm_keymaps, function(key, value) {
247 data.push([key, PVE.Utils.render_kvm_language(value)]);
248 });
249
250 return data;
251 },
252
2d802f8c
DM
253 render_console_viewer: function(value) {
254 if (!value) {
255 return PVE.Utils.defaultText + ' (Java VNC Applet)';
256 } else if (value === 'applet') {
257 return 'Java VNC Applet';
258 } else if (value === 'vv') {
259 return 'SPICE (remote-viewer)';
260 } else {
261 return value;
262 }
263 },
264
19fa0647 265 language_map: {
d0525640 266 zh_CN: 'Chinese',
226edf6d 267 ca: 'Catalan',
22217294 268 ja: 'Japanese',
19fa0647 269 en: 'English',
18fb1962 270 da: 'Danish',
2198a479 271 de: 'German',
8009570d 272 es: 'Spanish',
4a3a5520 273 fr: 'French',
72da7de7 274 it: 'Italian',
2d32003f
DM
275 nb: 'Norwegian (Bokmal)',
276 nn: 'Norwegian (Nynorsk)',
a4326a6c 277 ru: 'Russian',
b4e7aa2c 278 sl: 'Slovenian',
05e3e996 279 sv: 'Swedish',
fb1cf1bf 280 pl: 'Polish',
d97c5983 281 pt_BR: 'Portuguese (Brazil)',
05e3e996 282 tr: 'Turkish'
19fa0647
DM
283 },
284
285 render_language: function (value) {
286 if (!value) {
7e6b14a8 287 return PVE.Utils.defaultText + ' (English)';
19fa0647
DM
288 }
289 var text = PVE.Utils.language_map[value];
290 if (text) {
291 return text + ' (' + value + ')';
292 }
293 return value;
294 },
295
296 language_array: function() {
297 var data = [['', PVE.Utils.render_language('')]];
298 Ext.Object.each(PVE.Utils.language_map, function(key, value) {
299 data.push([key, PVE.Utils.render_language(value)]);
300 });
301
302 return data;
303 },
304
aff192e6
DM
305 render_kvm_vga_driver: function (value) {
306 if (!value) {
2ed04b3c 307 return PVE.Utils.defaultText;
aff192e6
DM
308 }
309 var text = PVE.Utils.kvm_vga_drivers[value];
310 if (text) {
311 return text + ' (' + value + ')';
312 }
313 return value;
314 },
315
316 kvm_vga_driver_array: function() {
317 var data = [['', PVE.Utils.render_kvm_vga_driver('')]];
318 Ext.Object.each(PVE.Utils.kvm_vga_drivers, function(key, value) {
319 data.push([key, PVE.Utils.render_kvm_vga_driver(value)]);
320 });
321
322 return data;
323 },
324
640f8f14
DM
325 render_kvm_startup: function(value) {
326 var startup = PVE.Parser.parseStartup(value);
327
328 var res = 'order=';
329 if (startup.order === undefined) {
330 res += 'any';
331 } else {
332 res += startup.order;
333 }
334 if (startup.up !== undefined) {
335 res += ',up=' + startup.up;
336 }
337 if (startup.down !== undefined) {
338 res += ',down=' + startup.down;
339 }
340
341 return res;
342 },
343
aff192e6
DM
344 authOK: function() {
345 return Ext.util.Cookies.get('PVEAuthCookie');
346 },
347
348 authClear: function() {
349 Ext.util.Cookies.clear("PVEAuthCookie");
350 },
351
352 // fixme: remove - not needed?
353 gridLineHeigh: function() {
354 return 21;
355
356 //if (Ext.isGecko)
357 //return 23;
358 //return 21;
359 },
360
361 extractRequestError: function(result, verbose) {
a2dca26b 362 var msg = gettext('Successful');
aff192e6
DM
363
364 if (!result.success) {
a2dca26b 365 msg = gettext("Unknown error");
aff192e6
DM
366 if (result.message) {
367 msg = result.message;
368 if (result.status) {
369 msg += ' (' + result.status + ')';
370 }
371 }
372 if (verbose && Ext.isObject(result.errors)) {
373 msg += "<br>";
374 Ext.Object.each(result.errors, function(prop, desc) {
375 msg += "<br><b>" + Ext.htmlEncode(prop) + "</b>: " +
376 Ext.htmlEncode(desc);
377 });
378 }
379 }
380
381 return msg;
382 },
383
384 extractFormActionError: function(action) {
385 var msg;
386 switch (action.failureType) {
387 case Ext.form.action.Action.CLIENT_INVALID:
a2dca26b 388 msg = gettext('Form fields may not be submitted with invalid values');
aff192e6
DM
389 break;
390 case Ext.form.action.Action.CONNECT_FAILURE:
a2dca26b 391 msg = gettext('Connection error');
aff192e6
DM
392 var resp = action.response;
393 if (resp.status && resp.statusText) {
394 msg += " " + resp.status + ": " + resp.statusText;
395 }
396 break;
397 case Ext.form.action.Action.LOAD_FAILURE:
398 case Ext.form.action.Action.SERVER_INVALID:
399 msg = PVE.Utils.extractRequestError(action.result, true);
400 break;
401 }
402 return msg;
403 },
404
405 // Ext.Ajax.request
406 API2Request: function(reqOpts) {
407
408 var newopts = Ext.apply({
a2dca26b 409 waitMsg: gettext('Please wait...')
aff192e6
DM
410 }, reqOpts);
411
412 if (!newopts.url.match(/^\/api2/)) {
413 newopts.url = '/api2/extjs' + newopts.url;
414 }
415 delete newopts.callback;
416
417 var createWrapper = function(successFn, callbackFn, failureFn) {
418 Ext.apply(newopts, {
419 success: function(response, options) {
420 if (options.waitMsgTarget) {
421 options.waitMsgTarget.setLoading(false);
422 }
423 var result = Ext.decode(response.responseText);
424 response.result = result;
425 if (!result.success) {
426 response.htmlStatus = PVE.Utils.extractRequestError(result, true);
427 Ext.callback(callbackFn, options.scope, [options, false, response]);
428 Ext.callback(failureFn, options.scope, [response, options]);
429 return;
430 }
431 Ext.callback(callbackFn, options.scope, [options, true, response]);
432 Ext.callback(successFn, options.scope, [response, options]);
433 },
434 failure: function(response, options) {
435 if (options.waitMsgTarget) {
436 options.waitMsgTarget.setLoading(false);
437 }
52406c42
DM
438 response.result = {};
439 try {
440 response.result = Ext.decode(response.responseText);
db16032c 441 } catch(e) {}
a2dca26b 442 var msg = gettext('Connection error') + ' - server offline?';
aff192e6 443 if (response.aborted) {
a2dca26b 444 msg = gettext('Connection error') + ' - aborted.';
aff192e6 445 } else if (response.timedout) {
a2dca26b 446 msg = gettext('Connection error') + ' - Timeout.';
aff192e6 447 } else if (response.status && response.statusText) {
a2dca26b 448 msg = gettext('Connection error') + ' ' + response.status + ': ' + response.statusText;
aff192e6
DM
449 }
450 response.htmlStatus = msg;
451 Ext.callback(callbackFn, options.scope, [options, false, response]);
452 Ext.callback(failureFn, options.scope, [response, options]);
453 }
454 });
455 };
456
457 createWrapper(reqOpts.success, reqOpts.callback, reqOpts.failure);
458
459 var target = newopts.waitMsgTarget;
460 if (target) {
461 // Note: ExtJS bug - this does not work when component is not rendered
2c535170 462 target.setLoading(newopts.waitMsg);
aff192e6
DM
463 }
464 Ext.Ajax.request(newopts);
465 },
466
467 assemble_field_data: function(values, data) {
468 if (Ext.isObject(data)) {
469 Ext.Object.each(data, function(name, val) {
470 if (values.hasOwnProperty(name)) {
471 var bucket = values[name];
472 if (!Ext.isArray(bucket)) {
473 bucket = values[name] = [bucket];
474 }
475 if (Ext.isArray(val)) {
476 values[name] = bucket.concat(val);
477 } else {
478 bucket.push(val);
479 }
480 } else {
481 values[name] = val;
482 }
483 });
484 }
485 },
486
9baa9680
DM
487 checked_command: function(orig_cmd) {
488 PVE.Utils.API2Request({
489 url: '/nodes/localhost/subscription',
490 method: 'GET',
491 //waitMsgTarget: me,
492 failure: function(response, opts) {
0070ee37 493 Ext.Msg.alert(gettext('Error'), response.htmlStatus);
9baa9680
DM
494 },
495 success: function(response, opts) {
496 var data = response.result.data;
497
498 if (data.status !== 'Active') {
499 Ext.Msg.show({
0070ee37 500 title: gettext('No valid subscription'),
9baa9680
DM
501 icon: Ext.Msg.WARNING,
502 msg: PVE.Utils.noSubKeyHtml,
503 buttons: Ext.Msg.OK,
504 callback: function(btn) {
505 if (btn !== 'ok') {
506 return;
507 }
508 orig_cmd();
509 }
510 });
511 } else {
512 orig_cmd();
513 }
514 }
515 });
516 },
517
acc0c13a 518 task_desc_table: {
c25f9d30 519 vncproxy: [ 'VM/CT', gettext('Console') ],
4af2c66c 520 spiceproxy: [ 'VM/CT', gettext('Console') + ' (Spice)' ],
2ed04b3c 521 vncshell: [ '', gettext('Shell') ],
2d802f8c 522 spiceshell: [ '', gettext('Shell') + ' (Spice)' ],
93d4a58a
DM
523 qmsnapshot: [ 'VM', gettext('Snapshot') ],
524 qmrollback: [ 'VM', gettext('Rollback') ],
525 qmdelsnapshot: [ 'VM', gettext('Delete Snapshot') ],
c25f9d30
DM
526 qmcreate: [ 'VM', gettext('Create') ],
527 qmrestore: [ 'VM', gettext('Restore') ],
528 qmdestroy: [ 'VM', gettext('Destroy') ],
529 qmigrate: [ 'VM', gettext('Migrate') ],
f16369ee 530 qmclone: [ 'VM', gettext('Clone') ],
772a8ffb 531 qmmove: [ 'VM', gettext('Move disk') ],
dd271a32 532 qmtemplate: [ 'VM', gettext('Convert to template') ],
c25f9d30
DM
533 qmstart: [ 'VM', gettext('Start') ],
534 qmstop: [ 'VM', gettext('Stop') ],
535 qmreset: [ 'VM', gettext('Reset') ],
536 qmshutdown: [ 'VM', gettext('Shutdown') ],
537 qmsuspend: [ 'VM', gettext('Suspend') ],
538 qmresume: [ 'VM', gettext('Resume') ],
9fb30485 539 qmconfig: [ 'VM', gettext('Configure') ],
c25f9d30
DM
540 vzcreate: ['CT', gettext('Create') ],
541 vzrestore: ['CT', gettext('Restore') ],
542 vzdestroy: ['CT', gettext('Destroy') ],
543 vzmigrate: [ 'CT', gettext('Migrate') ],
544 vzstart: ['CT', gettext('Start') ],
545 vzstop: ['CT', gettext('Stop') ],
8710f280
DM
546 vzmount: ['CT', gettext('Mount') ],
547 vzumount: ['CT', gettext('Unmount') ],
51ed1415 548 vzshutdown: ['CT', gettext('Shutdown') ],
3f76170f
DM
549 hamigrate: [ 'HA', gettext('Migrate') ],
550 hastart: [ 'HA', gettext('Start') ],
551 hastop: [ 'HA', gettext('Stop') ],
c25f9d30
DM
552 srvstart: ['SRV', gettext('Start') ],
553 srvstop: ['SRV', gettext('Stop') ],
554 srvrestart: ['SRV', gettext('Restart') ],
555 srvreload: ['SRV', gettext('Reload') ],
c9164975 556 imgcopy: ['', gettext('Copy data') ],
4a3a5520 557 imgdel: ['', gettext('Erase data') ],
c9164975 558 download: ['', gettext('Download') ],
640f8f14 559 vzdump: ['', gettext('Backup') ],
b9065f4d 560 aptupdate: ['', gettext('Update package database') ],
640f8f14
DM
561 startall: [ '', gettext('Start all VMs and Containers') ],
562 stopall: [ '', gettext('Stop 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'),
32314691 705 errorText: gettext('Error'),
7e6b14a8
DM
706 unknownText: gettext('Unknown'),
707 defaultText: gettext('Default'),
708 daysText: gettext('days'),
709 dayText: gettext('day'),
32314691
DM
710 runningText: gettext('running'),
711 stoppedText: gettext('stopped'),
b62861ce 712 neverText: gettext('never'),
bc3e73be
DM
713 totalText: gettext('Total'),
714 usedText: gettext('Used'),
b62861ce
DM
715
716 format_expire: function(date) {
717 if (!date) {
718 return PVE.Utils.neverText;
719 }
720 return Ext.Date.format(date, "Y-m-d");
721 },
7e6b14a8 722
aff192e6
DM
723 format_storage_type: function(value) {
724 if (value === 'dir') {
725 return 'Directory';
726 } else if (value === 'nfs') {
727 return 'NFS';
001b7f76
DM
728 } else if (value === 'glusterfs') {
729 return 'GlusterFS';
aff192e6
DM
730 } else if (value === 'lvm') {
731 return 'LVM';
732 } else if (value === 'iscsi') {
733 return 'iSCSI';
56fd4763
AD
734 } else if (value === 'rbd') {
735 return 'RBD';
736 } else if (value === 'sheepdog') {
737 return 'Sheepdog';
7995b6eb
MR
738 } else if (value === 'zfs') {
739 return 'ZFS';
56fd4763
AD
740 } else if (value === 'iscsidirect') {
741 return 'iSCSIDirect';
aff192e6 742 } else {
7e6b14a8 743 return PVE.Utils.unknownText;
aff192e6
DM
744 }
745 },
746
747 format_boolean_with_default: function(value) {
748 if (Ext.isDefined(value) && value !== '') {
a2dca26b 749 return value ? PVE.Utils.yesText : PVE.Utils.noText;
aff192e6 750 }
a2dca26b 751 return PVE.Utils.defaultText;
aff192e6
DM
752 },
753
754 format_boolean: function(value) {
a2dca26b 755 return value ? PVE.Utils.yesText : PVE.Utils.noText;
aff192e6
DM
756 },
757
758 format_neg_boolean: function(value) {
a2dca26b 759 return !value ? PVE.Utils.yesText : PVE.Utils.noText;
aff192e6
DM
760 },
761
762 format_content_types: function(value) {
763 var cta = [];
764
f29297db 765 Ext.each(value.split(',').sort(), function(ct) {
aff192e6
DM
766 if (ct === 'images') {
767 cta.push('Images');
768 } else if (ct === 'backup') {
769 cta.push('Backups');
770 } else if (ct === 'vztmpl') {
771 cta.push('Templates');
772 } else if (ct === 'iso') {
773 cta.push('ISO');
9f767883
DM
774 } else if (ct === 'rootdir') {
775 cta.push('Containers');
aff192e6
DM
776 }
777 });
778
779 return cta.join(', ');
780 },
781
782 render_storage_content: function(value, metaData, record) {
783 var data = record.data;
784 if (Ext.isNumber(data.channel) &&
785 Ext.isNumber(data.id) &&
786 Ext.isNumber(data.lun)) {
787 return "CH " +
788 Ext.String.leftPad(data.channel,2, '0') +
789 " ID " + data.id + " LUN " + data.lun;
790 }
791 return data.volid.replace(/^.*:(.*\/)?/,'');
792 },
793
794 render_serverity: function (value) {
795 return PVE.Utils.log_severity_hash[value] || value;
796 },
797
798 render_cpu: function(value, metaData, record, rowIndex, colIndex, store) {
799
105270d3 800 if (!(record.data.uptime && Ext.isNumeric(value))) {
aff192e6
DM
801 return '';
802 }
803
105270d3
DM
804 var maxcpu = record.data.maxcpu || 1;
805
806 if (!Ext.isNumeric(maxcpu) && (maxcpu >= 1)) {
aff192e6
DM
807 return '';
808 }
105270d3
DM
809
810 var per = value * 100;
aff192e6
DM
811
812 return per.toFixed(1) + '% of ' + maxcpu.toString() + (maxcpu > 1 ? 'CPUs' : 'CPU');
813 },
814
815 render_size: function(value, metaData, record, rowIndex, colIndex, store) {
a2f57991 816 /*jslint confusion: true */
aff192e6
DM
817
818 if (!Ext.isNumeric(value)) {
819 return '';
820 }
821
822 return PVE.Utils.format_size(value);
823 },
824
825 render_timestamp: function(value, metaData, record, rowIndex, colIndex, store) {
826 var servertime = new Date(value * 1000);
827 return Ext.Date.format(servertime, 'Y-m-d H:i:s');
828 },
829
830 render_mem_usage: function(value, metaData, record, rowIndex, colIndex, store) {
831
832 var mem = value;
833 var maxmem = record.data.maxmem;
834
835 if (!record.data.uptime) {
836 return '';
837 }
838
839 if (!(Ext.isNumeric(mem) && maxmem)) {
840 return '';
841 }
842
843 var per = (mem * 100) / maxmem;
844
845 return per.toFixed(1) + '%';
846 },
847
848 render_disk_usage: function(value, metaData, record, rowIndex, colIndex, store) {
849
850 var disk = value;
851 var maxdisk = record.data.maxdisk;
852
853 if (!(Ext.isNumeric(disk) && maxdisk)) {
854 return '';
855 }
856
857 var per = (disk * 100) / maxdisk;
858
859 return per.toFixed(1) + '%';
860 },
861
862 render_resource_type: function(value, metaData, record, rowIndex, colIndex, store) {
863
864 var cls = 'pve-itype-icon-' + value;
865
866 if (record.data.running) {
867 metaData.tdCls = cls + "-running";
5f28da0a
DM
868 } else if (record.data.template) {
869 metaData.tdCls = cls + "-template";
aff192e6
DM
870 } else {
871 metaData.tdCls = cls;
872 }
873
874 return value;
875 },
876
877 render_uptime: function(value, metaData, record, rowIndex, colIndex, store) {
878
879 var uptime = value;
880
881 if (uptime === undefined) {
882 return '';
883 }
884
885 if (uptime <= 0) {
886 return '-';
887 }
888
889 return PVE.Utils.format_duration_long(uptime);
890 },
891
16b69b6c
DM
892 render_support_level: function(value, metaData, record) {
893 return PVE.Utils.support_level_hash[value] || '-';
894 },
895
aff192e6
DM
896 render_upid: function(value, metaData, record) {
897 var type = record.data.type;
898 var id = record.data.id;
899
900 return PVE.Utils.format_task_description(type, id);
176eee4f
DM
901 },
902
58eb5905
DM
903 dialog_title: function(subject, create, isAdd) {
904 if (create) {
905 if (isAdd) {
906 return gettext('Add') + ': ' + subject;
907 } else {
908 return gettext('Create') + ': ' + subject;
909 }
910 } else {
911 return gettext('Edit') + ': ' + subject;
912 }
913 },
914
5431e16f 915 openConsoleWindow: function(vmtype, vmid, nodename, vmname) {
176eee4f 916 var url = Ext.urlEncode({
fb3feb55 917 console: vmtype, // kvm, openvz or shell
176eee4f 918 vmid: vmid,
fb3feb55 919 vmname: vmname,
176eee4f
DM
920 node: nodename
921 });
922 var nw = window.open("?" + url, '_blank',
923 "innerWidth=745,innerheight=427");
924 nw.focus();
5f663f5f
DM
925 },
926
2d802f8c
DM
927 defaultViewer: function(){
928 return PVE.VersionInfo.console || 'applet';
929 },
930
896090ee 931
2d802f8c 932 openSpiceViewer: function(url, params){
896090ee
DM
933
934 var downloadWithName = function(uri, name) {
935 var link = Ext.DomHelper.append(document.body, {
936 tag: 'a',
937 href: uri,
938 css : 'display:none;visibility:hidden;height:0px;',
939 });
940
941 // Note: we need to tell android the correct file name extension
942 // but we do not set 'download' tag for other environments, because
943 // It can have strange side effects (additional user prompt on firefox)
944 var andriod = navigator.userAgent.match(/Android/i) ? true : false;
945 if (andriod) {
946 link.download = name;
947 }
948
949 if (link.fireEvent) {
950 link.fireEvent('onclick');
951 } else {
952 var evt = document.createEvent("MouseEvents");
953 evt.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
954 link.dispatchEvent(evt);
955 }
956 };
957
2d802f8c
DM
958 PVE.Utils.API2Request({
959 url: url,
960 params: params,
961 method: 'POST',
962 failure: function(response, opts){
963 Ext.Msg.alert('Error', response.htmlStatus);
964 },
965 success: function(response, opts){
966 var raw = "[virt-viewer]\n";
967 Ext.Object.each(response.result.data, function(k, v) {
968 raw += k + "=" + v + "\n";
969 });
970 var url = 'data:application/x-virt-viewer;charset=UTF-8,' +
971 encodeURIComponent(raw);
972
896090ee 973 downloadWithName(url, "pve-spice.vv");
2d802f8c
DM
974 }
975 });
976 },
977
5f663f5f
DM
978 // comp.setLoading() is buggy in ExtJS 4.0.7, so we
979 // use el.mask() instead
980 setErrorMask: function(comp, msg) {
981 var el = comp.el;
982 if (!el) {
983 return;
984 }
985 if (!msg) {
986 el.unmask();
987 } else {
988 if (msg === true) {
989 el.mask(gettext("Loading..."));
990 } else {
991 el.mask(msg);
992 }
993 }
994 },
995
996 monStoreErrors: function(me, store) {
997 me.mon(store, 'beforeload', function(s, operation, eOpts) {
998 if (!me.loadCount) {
999 me.loadCount = 0; // make sure it is numeric
1000 PVE.Utils.setErrorMask(me, true);
1001 }
1002 });
1003
1004 // only works with 'pve' proxy
1005 me.mon(store.proxy, 'afterload', function(proxy, request, success) {
1006 me.loadCount++;
1007
1008 if (success) {
1009 PVE.Utils.setErrorMask(me, false);
1010 return;
1011 }
1012
1013 var msg;
1014 var operation = request.operation;
1015 var error = operation.getError();
1016 if (error.statusText) {
1017 msg = error.statusText + ' (' + error.status + ')';
1018 } else {
1019 msg = gettext('Connection error');
1020 }
1021 PVE.Utils.setErrorMask(me, msg);
1022 });
aff192e6 1023 }
176eee4f 1024
aff192e6
DM
1025}});
1026