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