Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / static / im / js / usage.js @ 37d59b27

History | View | Annotate | Download (7.3 kB)

1
;(function() {
2

    
3

    
4
// helper humanize methods
5
// https://github.com/taijinlee/humanize/blob/master/humanize.js 
6
humanize = {};
7
humanize.filesize = function(filesize, kilo, decimals, decPoint, thousandsSep) {
8
    kilo = (kilo === undefined) ? 1024 : kilo;
9
    decimals = isNaN(decimals) ? 2 : Math.abs(decimals);
10
    decPoint = (decPoint === undefined) ? '.' : decPoint;
11
    thousandsSep = (thousandsSep === undefined) ? ',' : thousandsSep;
12
    if (filesize <= 0) { return '0 bytes'; }
13

    
14
    var thresholds = [1];
15
    var units = ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB'];
16
    if (filesize < kilo) { return humanize.numberFormat(filesize, 0) + ' ' + units[0]; }
17

    
18
    for (var i = 1; i < units.length; i++) {
19
      thresholds[i] = thresholds[i-1] * kilo;
20
      if (filesize < thresholds[i]) {
21
        return humanize.numberFormat(filesize / thresholds[i-1], decimals, decPoint, thousandsSep) + ' ' + units[i-1];
22
      }
23
    }
24

    
25
    // use the last unit if we drop out to here
26
    return humanize.numberFormat(filesize / thresholds[units.length - 1], decimals, decPoint, thousandsSep) + ' ' + units[units.length - 1];
27
};
28
humanize.numberFormat = function(number, decimals, decPoint, thousandsSep) {
29
    decimals = isNaN(decimals) ? 2 : Math.abs(decimals);
30
    decPoint = (decPoint === undefined) ? '.' : decPoint;
31
    thousandsSep = (thousandsSep === undefined) ? ',' : thousandsSep;
32

    
33
    var sign = number < 0 ? '-' : '';
34
    number = Math.abs(+number || 0);
35

    
36
    var intPart = parseInt(number.toFixed(decimals), 10) + '';
37
    var j = intPart.length > 3 ? intPart.length % 3 : 0;
38

    
39
    return sign + (j ? intPart.substr(0, j) + thousandsSep : '') + intPart.substr(j).replace(/(\d{3})(?=\d)/g, '$1' + thousandsSep) + (decimals ? decPoint + Math.abs(number - intPart).toFixed(decimals).slice(2) : '');
40
  };
41

    
42

    
43
DO_LOG = false
44
LOG = DO_LOG ? _.bind(console.log, console) : function() {};
45
WARN = DO_LOG ? _.bind(console.warn, console) : function() {};
46

    
47
var default_usage_cls_map = {
48
  0: 'green',
49
  33: 'yellow',
50
  66: 'red'
51
}
52

    
53
function UsageView(settings) {
54
  this.settings = settings;
55
  this.url = this.settings.url;
56
  this.container = $(this.settings.container);
57
  this.meta = this.settings.meta;
58
  this.groups = this.settings.groups;
59
  this.el = {};
60
  this.usage_cls_map = this.settings.usage_cls_map || default_usage_cls_map;
61
  this.initialize();
62
}
63

    
64

    
65
_.extend(UsageView.prototype, {
66
  tpls: {
67
      'main': '<div class="stats clearfix"><ul></ul></div>',
68
      'quotas': "#quotaTpl"
69
  },
70

    
71
  initialize: function() {
72
    LOG("Initializing UsageView", this.settings);
73
    this.initResources();
74

    
75
    // initial usage set ????
76
    this.quotas = {};
77
    if (this.settings.quotas && _.keys(this.settings.quotas).length > 0) {
78
      this.setQuotas(this.settings.quotas);
79
    }
80
    this.initLayout();
81
    this.updateQuotas();
82
  },
83
  
84
  $: function(selector) {
85
    return this.container;
86
  },
87

    
88
  render: function(tpl, params) {
89
    LOG("Rendering", tpl, params);
90
    var tpl = this.tpls[tpl];
91
    if (/^[#\.]/.exec(tpl)) { 
92
      tpl = $(tpl).html();
93
    }
94
    var rendered = Mustache.render(tpl, params);
95
    return $(rendered);
96
  },
97

    
98
  initLayout: function() {
99
    LOG("Initializing layout");
100
    this.el.main = this.render('main');
101
    this.container.append(this.el.main);
102
    var ul = this.container.find("ul");
103
    this.el.list = this.render('quotas', {
104
      'resources': this.resources_ordered
105
    });
106
    ul.append(this.el.list);
107
  },
108
  
109
  initResources: function() {
110
    var ordered = this.meta.resources_order;
111
    var resources = {};
112
    var resources_ordered = [];
113

    
114
    _.each(this.meta.resources, function(group, index) {
115
      _.each(group[1], function(resource, rindex) {
116
        var resource_index = ordered.length;
117
        if (!_.contains(ordered, resource.name)) {
118
          ordered.push(resource.name);
119
        } else {
120
          resource_index = ordered.indexOf(resource.name);
121
        }
122
        resource.index = resource_index;
123
        resource.resource_name = resource.name.split(".")[1];
124
        resources[resource.name] = resource;
125
      })
126
    });
127
      
128
    resources_ordered = _.filter(_.map(ordered, 
129
                                       function(rk) { 
130
                                         return resources[rk] 
131
                                       }), 
132
                                 function(i) { return i});
133
    this.resources = resources;
134
    this.resources_ordered = resources_ordered;
135

    
136
    LOG("Resources initialized", this.resources_ordered, this.resources);
137
  },
138

    
139
  updateLayout: function() {
140
    LOG("Updating layout", this.quotas);
141
    var self = this;
142
    _.each(this.quotas, function(value, key) {
143
      var usage = self.getUsage(key);
144
      if (!usage) { return }
145
      var el = self.$().find("li[data-resource='"+key+"']");
146
      self.updateResourceElement(el, usage);
147
    })
148
  },
149

    
150
  updateResourceElement: function(el, usage) {
151
    el.find(".currValue").text(usage.curr);
152
    el.find(".maxValue").text(usage.max);
153
    el.find(".bar span").css({width:usage.perc+"%"});
154
    el.find(".bar .value").text(usage.perc+"%");
155
    var left = usage.label_left == 'auto' ? 
156
               usage.label_left : usage.label_left + "%";
157
    el.find(".bar .value").css({left:left});
158
    el.find(".bar .value").css({color:usage.label_color});
159
    el.removeClass("green yellow red");
160
    el.addClass(usage.cls);
161
  },
162
    
163
  getUsage: function(resource_name) {
164
    var resource = this.quotas[resource_name];
165
    var resource_meta = this.resources[resource_name];
166
    if (!resource_meta) { return }
167
    var value, limit, percentage; 
168
    
169
    limit = resource.limit;
170
    value = resource.usage;
171
    if (value < 0 ) { value = 0 }
172
  
173
    percentage = (value/limit) * 100;
174
    if (value == 0) { percentage = 0 }
175
    if (value > limit) {
176
      percentage = 100;
177
    }
178
  
179
    if (resource_meta.unit == 'bytes') {
180
      value = humanize.filesize(value);
181
      limit = humanize.filesize(limit);
182
    }
183

    
184
    var cls = 'green';
185
    _.each(this.usage_cls_map, function(ucls, u){
186
      if (percentage >= u) {
187
        cls = ucls
188
      }
189
    })
190
  
191
    var label_left = percentage >= 30 ? percentage - 17 : 'auto'; 
192
    var label_col = label_left == 'auto' ? 'inherit' : '#fff';
193
    percentage = humanize.numberFormat(percentage, 0);
194
    qdata = {'curr': value, 'max': limit, 'perc': percentage, 'cls': cls,
195
             'label_left': label_left, 'label_color': label_col}
196
    _.extend(qdata, resource);
197
    return qdata
198
  },
199

    
200
  setQuotas: function(data) {
201
    LOG("Set quotas", data);
202
    var self = this;
203
    this.quotas = data;
204
    _.each(this.quotas, function(v, k) {
205
      var r = self.resources[k];
206
      var usage = self.getUsage(k);
207
      if (!usage) { return }
208
      r.usage = usage;
209
      self.resources[k].usage = usage;
210
      if (!self.resources_ordered[r.index]) { return }
211
      self.resources_ordered[r.index].usage = usage;
212
    });
213
  },
214

    
215
  _ajaxOptions: function() {
216
    var token = $.cookie(this.settings.cookie_name).split("|")[1];
217
    return {
218
      'url': this.url,
219
      'headers': {
220
        'X-Auth-Token': token
221
      },
222
    }
223
  },
224
  
225
  updateQuotas: function() {
226
    LOG("Updating quotas");
227
    var self = this;
228
    this.getQuotas(function(data){
229
      self.setQuotas(data.system);
230
      self.updateLayout();
231
    })
232
  },
233

    
234
  getQuotas: function(callback) {
235
    var options = this._ajaxOptions();
236
    options.success = callback;
237
    LOG("Calling quotas API", options);
238
    $.ajax(options);
239
  }
240
  
241
});
242

    
243
window.UsageView = UsageView;
244
})();