CMS improvements
[snf-cloudcms] / cloudcms / static / cloudcms / js / service-stats.js
1 var cloudcms = {};
2 cloudcms.utils = {};
3
4 cloudcms.utils.addCommas = function(nStr)
5 {
6         nStr += '';
7         x = nStr.split('.');
8         x1 = x[0];
9         x2 = x.length > 1 ? '.' + x[1] : '';
10         var rgx = /(\d+)(\d{3})/;
11         while (rgx.test(x1)) {
12                 x1 = x1.replace(rgx, '$1' + ',' + '$2');
13         }
14         return x1 + x2;
15 }
16
17 function ServiceStats(opts, wrapper) {
18         this.options = opts;
19         this.wrapper = wrapper; 
20 }
21
22
23 ServiceStats.prototype.updateStats = function(data) {
24         var self = this;
25         function filldata(value, key) {
26                 self.wrapper.find("li."+key).find('span').text(cloudcms.utils.addCommas(value));
27         }
28         _.each(data,filldata);
29 }
30
31
32 ServiceStats.prototype.addArray = function(data) {
33         return _.reduce(data, function(memo, num){ return memo + num; }, 0);
34 }
35
36
37 ServiceStats.prototype.getActive = function(data) {
38         var active = _.omit(data,'DELETED');
39         var active_count =  _.pluck(active, 'count');
40         return this.addArray(active_count);
41 }
42
43 ServiceStats.prototype.getAll = function(data) {
44         return this.addArray(_.pluck(data, 'count'));
45
46
47 ServiceStats.prototype.loadStats = function() {
48         var self = this;
49         if (this.options.compute_url) {
50                 $.ajax({
51                         url: this.options.compute_url,
52                         dataType:'jsonp',
53                         success: function(data) {       
54                                 self.updateStats({
55                                         'running_vms': data.servers.ACTIVE.count, 
56                                         'active_vms': self.getActive(data.servers),
57                                         'spawned_vms': self.getAll(data.servers),
58                                         'running_networks': data.networks.ACTIVE.count, 
59                                         'active_networks': self.getActive(data.networks),
60                                         'spawned_networks': self.getAll(data.networks),
61
62                                 })
63                         }
64                 })      
65         }
66         if (this.options.storage_url) {
67                 $.ajax({
68                         url: this.options.storage,
69                         success: function(data) {
70                                 self.storage.find("span").text(data.storage);
71                         }
72                 })      
73         }
74 }
75
76 ServiceStats.prototype.startUpdate = function(interval) {
77         var self = this;
78         self.loadStats();
79         window.setTimeout(function(){ 
80                 self.startUpdate(interval);
81         }, interval);
82 }