]> git.proxmox.com Git - proxmox-widget-toolkit.git/blame - Utils.js
add task_desc_table and format_task_description from pve
[proxmox-widget-toolkit.git] / Utils.js
CommitLineData
0bb29d35
DM
1Ext.ns('Proxmox');
2Ext.ns('Proxmox.Setup');
3
0ee4c725
DM
4if (!Ext.isFunction(gettext)) {
5 function gettext(buf) { return buf; }
6}
0bb29d35 7
757cc58a
DM
8if (!Ext.isDefined(Proxmox.Setup.auth_cookie_name)) {
9 throw "Proxmox library not initialized";
0bb29d35
DM
10}
11
12// avoid errors related to Accessible Rich Internet Applications
13// (access for people with disabilities)
14// TODO reenable after all components are upgraded
15Ext.enableAria = false;
16Ext.enableAriaButtons = false;
17Ext.enableAriaPanels = false;
18
19// avoid errors when running without development tools
20if (!Ext.isDefined(Ext.global.console)) {
21 var console = {
22 dir: function() {},
23 log: function() {}
24 };
25}
26
27Ext.Ajax.defaultHeaders = {
28 'Accept': 'application/json'
29};
30
31Ext.Ajax.on('beforerequest', function(conn, options) {
32 if (Proxmox.CSRFPreventionToken) {
33 if (!options.headers) {
34 options.headers = {};
35 }
36 options.headers.CSRFPreventionToken = Proxmox.CSRFPreventionToken;
37 }
38});
39
40Ext.define('Proxmox.Utils', { utilities: {
41
42 // this singleton contains miscellaneous utilities
43
30f885cb
DM
44 yesText: gettext('Yes'),
45 noText: gettext('No'),
46 enabledText: gettext('Enabled'),
47 disabledText: gettext('Disabled'),
48 noneText: gettext('none'),
49 errorText: gettext('Error'),
a58001dd 50 unknownText: gettext('Unknown'),
30f885cb
DM
51 defaultText: gettext('Default'),
52 daysText: gettext('days'),
53 dayText: gettext('day'),
54 runningText: gettext('running'),
55 stoppedText: gettext('stopped'),
56 neverText: gettext('never'),
57 totalText: gettext('Total'),
58 usedText: gettext('Used'),
59 directoryText: gettext('Directory'),
60 stateText: gettext('State'),
61 groupText: gettext('Group'),
62
f6f0066a 63 language_map: {
f97a2a34
DC
64 zh_CN: 'Chinese',
65 ca: 'Catalan',
66 da: 'Danish',
f6f0066a 67 en: 'English',
f97a2a34 68 eu: 'Euskera (Basque)',
f6f0066a
DM
69 fr: 'French',
70 de: 'German',
71 it: 'Italian',
f97a2a34
DC
72 es: 'Spanish',
73 ja: 'Japanese',
74 nb: 'Norwegian (Bokmal)',
75 nn: 'Norwegian (Nynorsk)',
76 fa: 'Persian (Farsi)',
77 pl: 'Polish',
78 pt_BR: 'Portuguese (Brazil)',
79 ru: 'Russian',
80 sl: 'Slovenian',
81 sv: 'Swedish',
82 tr: 'Turkish'
f6f0066a
DM
83 },
84
85 render_language: function (value) {
86 if (!value) {
87 return Proxmox.Utils.defaultText + ' (English)';
88 }
89 var text = Proxmox.Utils.language_map[value];
90 if (text) {
91 return text + ' (' + value + ')';
92 }
93 return value;
94 },
95
96 language_array: function() {
97 var data = [['__default__', Proxmox.Utils.render_language('')]];
98 Ext.Object.each(Proxmox.Utils.language_map, function(key, value) {
99 data.push([key, Proxmox.Utils.render_language(value)]);
100 });
101
102 return data;
103 },
104
5f93e010
DM
105 getNoSubKeyHtml: function(url) {
106 // url http://www.proxmox.com/products/proxmox-ve/subscription-service-plans
107 return Ext.String.format('You do not have a valid subscription for this server. Please visit <a target="_blank" href="{0}">www.proxmox.com</a> to get a list of available options.', url || 'http://www.proxmox.com');
108 },
109
b0d9b5d1
DM
110 format_boolean_with_default: function(value) {
111 if (Ext.isDefined(value) && value !== '__default__') {
112 return value ? Proxmox.Utils.yesText : Proxmox.Utils.noText;
113 }
114 return Proxmox.Utils.defaultText;
115 },
116
117 format_boolean: function(value) {
118 return value ? Proxmox.Utils.yesText : Proxmox.Utils.noText;
119 },
120
121 format_neg_boolean: function(value) {
122 return !value ? Proxmox.Utils.yesText : Proxmox.Utils.noText;
123 },
a58001dd 124
0e49da6d
DM
125 format_enabled_toggle: function(value) {
126 return value ? Proxmox.Utils.enabledText : Proxmox.Utils.disabledText;
127 },
128
2d0153a5
DM
129 format_expire: function(date) {
130 if (!date) {
131 return Proxmox.Utils.neverText;
132 }
133 return Ext.Date.format(date, "Y-m-d");
134 },
135
452892df
DM
136 format_duration_long: function(ut) {
137
138 var days = Math.floor(ut / 86400);
139 ut -= days*86400;
140 var hours = Math.floor(ut / 3600);
141 ut -= hours*3600;
142 var mins = Math.floor(ut / 60);
143 ut -= mins*60;
144
145 var hours_str = '00' + hours.toString();
146 hours_str = hours_str.substr(hours_str.length - 2);
147 var mins_str = "00" + mins.toString();
148 mins_str = mins_str.substr(mins_str.length - 2);
149 var ut_str = "00" + ut.toString();
150 ut_str = ut_str.substr(ut_str.length - 2);
151
152 if (days) {
153 var ds = days > 1 ? Proxmox.Utils.daysText : Proxmox.Utils.dayText;
154 return days.toString() + ' ' + ds + ' ' +
155 hours_str + ':' + mins_str + ':' + ut_str;
156 } else {
157 return hours_str + ':' + mins_str + ':' + ut_str;
158 }
159 },
160
02ef30c9
DM
161 format_subscription_level: function(level) {
162 if (level === 'c') {
8f5a1a08 163 return 'Community';
02ef30c9 164 } else if (level === 'b') {
8f5a1a08 165 return 'Basic';
02ef30c9 166 } else if (level === 's') {
8f5a1a08 167 return 'Standard';
02ef30c9 168 } else if (level === 'p') {
8f5a1a08 169 return 'Premium';
02ef30c9
DM
170 } else {
171 return Proxmox.Utils.noneText;
172 }
173 },
174
28e54f37
DM
175 compute_min_label_width: function(text, width) {
176
177 if (width === undefined) { width = 100; }
178
179 var tm = new Ext.util.TextMetrics();
180 var min = tm.getWidth(text + ':');
181
182 return min < width ? width : min;
183 },
184
0bb29d35
DM
185 authOK: function() {
186 return (Proxmox.UserName !== '') && Ext.util.Cookies.get(Proxmox.Setup.auth_cookie_name);
187 },
188
189 authClear: function() {
190 Ext.util.Cookies.clear(Proxmox.Setup.auth_cookie_name);
191 },
192
193 // comp.setLoading() is buggy in ExtJS 4.0.7, so we
194 // use el.mask() instead
195 setErrorMask: function(comp, msg) {
196 var el = comp.el;
197 if (!el) {
198 return;
199 }
200 if (!msg) {
201 el.unmask();
202 } else {
203 if (msg === true) {
204 el.mask(gettext("Loading..."));
205 } else {
206 el.mask(msg);
207 }
208 }
209 },
210
5b4b3ffd
DM
211 monStoreErrors: function(me, store, clearMaskBeforeLoad) {
212 if (clearMaskBeforeLoad) {
213 me.mon(store, 'beforeload', function(s, operation, eOpts) {
214 Proxmox.Utils.setErrorMask(me, false);
e94c0767 215 });
5b4b3ffd
DM
216 } else {
217 me.mon(store, 'beforeload', function(s, operation, eOpts) {
218 if (!me.loadCount) {
219 me.loadCount = 0; // make sure it is numeric
220 Proxmox.Utils.setErrorMask(me, true);
221 }
222 });
223 }
0bb29d35
DM
224
225 // only works with 'proxmox' proxy
226 me.mon(store.proxy, 'afterload', function(proxy, request, success) {
227 me.loadCount++;
228
229 if (success) {
230 Proxmox.Utils.setErrorMask(me, false);
231 return;
232 }
233
234 var msg;
235 /*jslint nomen: true */
236 var operation = request._operation;
237 var error = operation.getError();
238 if (error.statusText) {
239 msg = error.statusText + ' (' + error.status + ')';
240 } else {
241 msg = gettext('Connection error');
242 }
243 Proxmox.Utils.setErrorMask(me, msg);
244 });
245 },
246
247 extractRequestError: function(result, verbose) {
248 var msg = gettext('Successful');
249
250 if (!result.success) {
251 msg = gettext("Unknown error");
252 if (result.message) {
253 msg = result.message;
254 if (result.status) {
255 msg += ' (' + result.status + ')';
256 }
257 }
258 if (verbose && Ext.isObject(result.errors)) {
259 msg += "<br>";
260 Ext.Object.each(result.errors, function(prop, desc) {
261 msg += "<br><b>" + Ext.htmlEncode(prop) + "</b>: " +
262 Ext.htmlEncode(desc);
263 });
264 }
265 }
266
267 return msg;
268 },
269
270 // Ext.Ajax.request
271 API2Request: function(reqOpts) {
272
273 var newopts = Ext.apply({
274 waitMsg: gettext('Please wait...')
275 }, reqOpts);
276
277 if (!newopts.url.match(/^\/api2/)) {
278 newopts.url = '/api2/extjs' + newopts.url;
279 }
280 delete newopts.callback;
281
282 var createWrapper = function(successFn, callbackFn, failureFn) {
283 Ext.apply(newopts, {
284 success: function(response, options) {
285 if (options.waitMsgTarget) {
286 options.waitMsgTarget.setLoading(false);
287 }
288 var result = Ext.decode(response.responseText);
289 response.result = result;
290 if (!result.success) {
291 response.htmlStatus = Proxmox.Utils.extractRequestError(result, true);
292 Ext.callback(callbackFn, options.scope, [options, false, response]);
293 Ext.callback(failureFn, options.scope, [response, options]);
294 return;
295 }
296 Ext.callback(callbackFn, options.scope, [options, true, response]);
297 Ext.callback(successFn, options.scope, [response, options]);
298 },
299 failure: function(response, options) {
300 if (options.waitMsgTarget) {
301 options.waitMsgTarget.setLoading(false);
302 }
303 response.result = {};
304 try {
305 response.result = Ext.decode(response.responseText);
306 } catch(e) {}
307 var msg = gettext('Connection error') + ' - server offline?';
308 if (response.aborted) {
309 msg = gettext('Connection error') + ' - aborted.';
310 } else if (response.timedout) {
311 msg = gettext('Connection error') + ' - Timeout.';
312 } else if (response.status && response.statusText) {
313 msg = gettext('Connection error') + ' ' + response.status + ': ' + response.statusText;
314 }
315 response.htmlStatus = msg;
316 Ext.callback(callbackFn, options.scope, [options, false, response]);
317 Ext.callback(failureFn, options.scope, [response, options]);
318 }
319 });
320 };
321
322 createWrapper(reqOpts.success, reqOpts.callback, reqOpts.failure);
323
324 var target = newopts.waitMsgTarget;
325 if (target) {
326 // Note: ExtJS bug - this does not work when component is not rendered
327 target.setLoading(newopts.waitMsg);
328 }
329 Ext.Ajax.request(newopts);
330 },
331
5f93e010
DM
332 checked_command: function(orig_cmd) {
333 Proxmox.Utils.API2Request({
334 url: '/nodes/localhost/subscription',
335 method: 'GET',
336 //waitMsgTarget: me,
337 failure: function(response, opts) {
338 Ext.Msg.alert(gettext('Error'), response.htmlStatus);
339 },
340 success: function(response, opts) {
341 var data = response.result.data;
342
343 if (data.status !== 'Active') {
344 Ext.Msg.show({
345 title: gettext('No valid subscription'),
346 icon: Ext.Msg.WARNING,
347 msg: Proxmox.Utils.getNoSubKeyHtml(data.url),
348 buttons: Ext.Msg.OK,
349 callback: function(btn) {
350 if (btn !== 'ok') {
351 return;
352 }
353 orig_cmd();
354 }
355 });
356 } else {
357 orig_cmd();
358 }
359 }
360 });
361 },
362
06694509
DM
363 assemble_field_data: function(values, data) {
364 if (Ext.isObject(data)) {
365 Ext.Object.each(data, function(name, val) {
366 if (values.hasOwnProperty(name)) {
367 var bucket = values[name];
368 if (!Ext.isArray(bucket)) {
369 bucket = values[name] = [bucket];
370 }
371 if (Ext.isArray(val)) {
372 values[name] = bucket.concat(val);
373 } else {
374 bucket.push(val);
375 }
376 } else {
377 values[name] = val;
378 }
379 });
380 }
381 },
382
383 dialog_title: function(subject, create, isAdd) {
384 if (create) {
385 if (isAdd) {
386 return gettext('Add') + ': ' + subject;
387 } else {
388 return gettext('Create') + ': ' + subject;
389 }
390 } else {
391 return gettext('Edit') + ': ' + subject;
392 }
393 },
394
a58001dd
DM
395 network_iface_types: {
396 eth: gettext("Network Device"),
397 bridge: 'Linux Bridge',
398 bond: 'Linux Bond',
399 OVSBridge: 'OVS Bridge',
400 OVSBond: 'OVS Bond',
401 OVSPort: 'OVS Port',
402 OVSIntPort: 'OVS IntPort'
403 },
404
405 render_network_iface_type: function(value) {
406 return Proxmox.Utils.network_iface_types[value] ||
407 Proxmox.Utils.unknownText;
408 },
409
ab7fac0b
DC
410 task_desc_table: {
411 diskinit: [ 'Disk', gettext('Initialize Disk with GPT') ],
412 vncproxy: [ 'VM/CT', gettext('Console') ],
413 spiceproxy: [ 'VM/CT', gettext('Console') + ' (Spice)' ],
414 vncshell: [ '', gettext('Shell') ],
415 spiceshell: [ '', gettext('Shell') + ' (Spice)' ],
416 qmsnapshot: [ 'VM', gettext('Snapshot') ],
417 qmrollback: [ 'VM', gettext('Rollback') ],
418 qmdelsnapshot: [ 'VM', gettext('Delete Snapshot') ],
419 qmcreate: [ 'VM', gettext('Create') ],
420 qmrestore: [ 'VM', gettext('Restore') ],
421 qmdestroy: [ 'VM', gettext('Destroy') ],
422 qmigrate: [ 'VM', gettext('Migrate') ],
423 qmclone: [ 'VM', gettext('Clone') ],
424 qmmove: [ 'VM', gettext('Move disk') ],
425 qmtemplate: [ 'VM', gettext('Convert to template') ],
426 qmstart: [ 'VM', gettext('Start') ],
427 qmstop: [ 'VM', gettext('Stop') ],
428 qmreset: [ 'VM', gettext('Reset') ],
429 qmshutdown: [ 'VM', gettext('Shutdown') ],
430 qmsuspend: [ 'VM', gettext('Suspend') ],
431 qmresume: [ 'VM', gettext('Resume') ],
432 qmconfig: [ 'VM', gettext('Configure') ],
433 vzsnapshot: [ 'CT', gettext('Snapshot') ],
434 vzrollback: [ 'CT', gettext('Rollback') ],
435 vzdelsnapshot: [ 'CT', gettext('Delete Snapshot') ],
436 vzcreate: ['CT', gettext('Create') ],
437 vzrestore: ['CT', gettext('Restore') ],
438 vzdestroy: ['CT', gettext('Destroy') ],
439 vzmigrate: [ 'CT', gettext('Migrate') ],
440 vzclone: [ 'CT', gettext('Clone') ],
441 vztemplate: [ 'CT', gettext('Convert to template') ],
442 vzstart: ['CT', gettext('Start') ],
443 vzstop: ['CT', gettext('Stop') ],
444 vzmount: ['CT', gettext('Mount') ],
445 vzumount: ['CT', gettext('Unmount') ],
446 vzshutdown: ['CT', gettext('Shutdown') ],
447 vzsuspend: [ 'CT', gettext('Suspend') ],
448 vzresume: [ 'CT', gettext('Resume') ],
449 hamigrate: [ 'HA', gettext('Migrate') ],
450 hastart: [ 'HA', gettext('Start') ],
451 hastop: [ 'HA', gettext('Stop') ],
452 srvstart: ['SRV', gettext('Start') ],
453 srvstop: ['SRV', gettext('Stop') ],
454 srvrestart: ['SRV', gettext('Restart') ],
455 srvreload: ['SRV', gettext('Reload') ],
456 cephcreatemon: ['Ceph Monitor', gettext('Create') ],
457 cephdestroymon: ['Ceph Monitor', gettext('Destroy') ],
458 cephcreateosd: ['Ceph OSD', gettext('Create') ],
459 cephdestroyosd: ['Ceph OSD', gettext('Destroy') ],
460 cephcreatepool: ['Ceph Pool', gettext('Create') ],
461 cephdestroypool: ['Ceph Pool', gettext('Destroy') ],
462 imgcopy: ['', gettext('Copy data') ],
463 imgdel: ['', gettext('Erase data') ],
464 download: ['', gettext('Download') ],
465 vzdump: ['', gettext('Backup') ],
466 aptupdate: ['', gettext('Update package database') ],
467 startall: [ '', gettext('Start all VMs and Containers') ],
468 stopall: [ '', gettext('Stop all VMs and Containers') ],
469 migrateall: [ '', gettext('Migrate all VMs and Containers') ]
470 },
471
53ac9bca 472 format_task_description: function(type, id) {
ab7fac0b
DC
473 var farray = Proxmox.Utils.task_desc_table[type];
474 if (!farray) {
475 var text = type;
476 if (id) {
477 type += ' ' + id;
478 }
479 return text;
480 }
481 var prefix = farray[0];
482 var text = farray[1];
483 if (prefix) {
484 return prefix + ' ' + id + ' - ' + text;
485 }
486 return text;
53ac9bca
DM
487 },
488
b91c7ce2
DC
489 format_size: function(size) {
490 /*jslint confusion: true */
491
492 var units = ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi', 'Yi'];
493 var num = 0;
494
495 while (size >= 1024 && ((num++)+1) < units.length) {
496 size = size / 1024;
497 }
498
499 return size.toFixed((num > 0)?2:0) + " " + units[num] + "B";
500 },
501
53ac9bca
DM
502 render_upid: function(value, metaData, record) {
503 var type = record.data.type;
504 var id = record.data.id;
505
506 return Proxmox.Utils.format_task_description(type, id);
507 },
508
452892df
DM
509 render_uptime: function(value) {
510
511 var uptime = value;
512
513 if (uptime === undefined) {
514 return '';
515 }
516
517 if (uptime <= 0) {
518 return '-';
519 }
520
521 return Proxmox.Utils.format_duration_long(uptime);
522 },
523
06694509
DM
524 parse_task_upid: function(upid) {
525 var task = {};
526
527 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]+):$/);
528 if (!res) {
529 throw "unable to parse upid '" + upid + "'";
530 }
531 task.node = res[1];
532 task.pid = parseInt(res[2], 16);
533 task.pstart = parseInt(res[3], 16);
534 task.starttime = parseInt(res[4], 16);
535 task.type = res[5];
536 task.id = res[6];
537 task.user = res[7];
538
53ac9bca
DM
539 task.desc = Proxmox.Utils.format_task_description(task.type, task.id);
540
06694509
DM
541 return task;
542 },
543
544 render_timestamp: function(value, metaData, record, rowIndex, colIndex, store) {
545 var servertime = new Date(value * 1000);
546 return Ext.Date.format(servertime, 'Y-m-d H:i:s');
881c9c0c
DC
547 },
548
549 openXtermJsViewer: function(vmtype, vmid, nodename, vmname) {
550 var url = Ext.urlEncode({
551 console: vmtype, // kvm, lxc, upgrade or shell
552 xtermjs: 1,
553 vmid: vmid,
554 vmname: vmname,
555 node: nodename
556 });
557 var nw = window.open("?" + url, '_blank', 'toolbar=no,location=no,status=no,menubar=no,resizable=yes,width=800,height=420');
558 nw.focus();
e94c0767 559 }
06694509 560
881c9c0c 561},
5ffef550 562
0bb29d35
DM
563 singleton: true,
564 constructor: function() {
565 var me = this;
566 Ext.apply(me, me.utilities);
567
568 var IPV4_OCTET = "(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])";
569 var IPV4_REGEXP = "(?:(?:" + IPV4_OCTET + "\\.){3}" + IPV4_OCTET + ")";
570 var IPV6_H16 = "(?:[0-9a-fA-F]{1,4})";
571 var IPV6_LS32 = "(?:(?:" + IPV6_H16 + ":" + IPV6_H16 + ")|" + IPV4_REGEXP + ")";
572
573
574 me.IP4_match = new RegExp("^(?:" + IPV4_REGEXP + ")$");
575 me.IP4_cidr_match = new RegExp("^(?:" + IPV4_REGEXP + ")\/([0-9]{1,2})$");
576
577 var IPV6_REGEXP = "(?:" +
578 "(?:(?:" + "(?:" + IPV6_H16 + ":){6})" + IPV6_LS32 + ")|" +
579 "(?:(?:" + "::" + "(?:" + IPV6_H16 + ":){5})" + IPV6_LS32 + ")|" +
580 "(?:(?:(?:" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){4})" + IPV6_LS32 + ")|" +
581 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,1}" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){3})" + IPV6_LS32 + ")|" +
582 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,2}" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){2})" + IPV6_LS32 + ")|" +
583 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,3}" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){1})" + IPV6_LS32 + ")|" +
584 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,4}" + IPV6_H16 + ")?::" + ")" + IPV6_LS32 + ")|" +
585 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,5}" + IPV6_H16 + ")?::" + ")" + IPV6_H16 + ")|" +
586 "(?:(?:(?:(?:" + IPV6_H16 + ":){0,7}" + IPV6_H16 + ")?::" + ")" + ")" +
587 ")";
588
589 me.IP6_match = new RegExp("^(?:" + IPV6_REGEXP + ")$");
590 me.IP6_cidr_match = new RegExp("^(?:" + IPV6_REGEXP + ")\/([0-9]{1,3})$");
591 me.IP6_bracket_match = new RegExp("^\\[(" + IPV6_REGEXP + ")\\]");
592
593 me.IP64_match = new RegExp("^(?:" + IPV6_REGEXP + "|" + IPV4_REGEXP + ")$");
594
595 var DnsName_REGEXP = "(?:(([a-zA-Z0-9]([a-zA-Z0-9\\-]*[a-zA-Z0-9])?)\\.)*([A-Za-z0-9]([A-Za-z0-9\\-]*[A-Za-z0-9])?))";
596 me.DnsName_match = new RegExp("^" + DnsName_REGEXP + "$");
597
598 me.HostPort_match = new RegExp("^(" + IPV4_REGEXP + "|" + DnsName_REGEXP + ")(:\\d+)?$");
599 me.HostPortBrackets_match = new RegExp("^\\[(?:" + IPV6_REGEXP + "|" + IPV4_REGEXP + "|" + DnsName_REGEXP + ")\\](:\\d+)?$");
600 me.IP6_dotnotation_match = new RegExp("^" + IPV6_REGEXP + "(\\.\\d+)?$");
601 }
602});