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