Statistics
| Branch: | Tag: | Revision:

root / snf-cyclades-app / synnefo / ui / static / snf / js / models.js @ 3e323ae8

History | View | Annotate | Download (83.7 kB)

1
// Copyright 2011 GRNET S.A. All rights reserved.
2
// 
3
// Redistribution and use in source and binary forms, with or
4
// without modification, are permitted provided that the following
5
// conditions are met:
6
// 
7
//   1. Redistributions of source code must retain the above
8
//      copyright notice, this list of conditions and the following
9
//      disclaimer.
10
// 
11
//   2. Redistributions in binary form must reproduce the above
12
//      copyright notice, this list of conditions and the following
13
//      disclaimer in the documentation and/or other materials
14
//      provided with the distribution.
15
// 
16
// THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
17
// OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
20
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
23
// USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
24
// AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
26
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27
// POSSIBILITY OF SUCH DAMAGE.
28
// 
29
// The views and conclusions contained in the software and
30
// documentation are those of the authors and should not be
31
// interpreted as representing official policies, either expressed
32
// or implied, of GRNET S.A.
33
// 
34

    
35
;(function(root){
36
    
37
    // root
38
    var root = root;
39
    
40
    // setup namepsaces
41
    var snf = root.synnefo = root.synnefo || {};
42
    var models = snf.models = snf.models || {}
43
    var storage = snf.storage = snf.storage || {};
44
    var util = snf.util = snf.util || {};
45

    
46
    // shortcuts
47
    var bb = root.Backbone;
48
    var slice = Array.prototype.slice
49

    
50
    // logging
51
    var logger = new snf.logging.logger("SNF-MODELS");
52
    var debug = _.bind(logger.debug, logger);
53
    
54
    // get url helper
55
    var getUrl = function(baseurl) {
56
        var baseurl = baseurl || snf.config.api_urls[this.api_type];
57
        var append = "/";
58
        if (baseurl.split("").reverse()[0] == "/") {
59
          append = "";
60
        }
61
        return baseurl + append + this.path;
62
    }
63

    
64
    // i18n
65
    BUILDING_MESSAGES = window.BUILDING_MESSAGES || {'INIT': 'init', 'COPY': '{0}, {1}, {2}', 'FINAL': 'final'};
66

    
67
    // Base object for all our models
68
    models.Model = bb.Model.extend({
69
        sync: snf.api.sync,
70
        api: snf.api,
71
        api_type: 'compute',
72
        has_status: false,
73
        auto_bind: [],
74

    
75

    
76
        initialize: function() {
77
            var self = this;
78
            
79
            this._proxy_model_cache = {};
80
            _.each(this.auto_bind, function(fname) {
81
              self[fname] = _.bind(self[fname], self);
82
            });
83

    
84
            if (this.has_status) {
85
                this.bind("change:status", this.handle_remove);
86
                this.handle_remove();
87
            }
88
            
89
            this.api_call = _.bind(this.api.call, this);
90
              
91
            if (this.proxy_attrs) {
92
              this.init_proxy_attrs();             
93
            }
94

    
95
            if (this.storage_attrs) {
96
              this.init_storage_attrs();
97
            }
98

    
99
            if (this.model_actions) {
100
              this.init_model_actions();             
101
            }
102

    
103
            models.Model.__super__.initialize.apply(this, arguments);
104

    
105
        },
106
        
107
        // Initialize model actions object
108
        // For each entry in model's model_action object register the relevant 
109
        // model proxy `can_<actionname>` attributes.
110
        init_model_actions: function() {
111
          var actions = _.keys(this.model_actions);
112
          this.set({
113
            "actions": new models._ActionsModel({}, {
114
              actions: actions,
115
              model: this
116
            })
117
          });
118
          this.actions = this.get("actions");
119

    
120
          _.each(this.model_actions, function(params, key){
121
            var attr = 'can_' + key;
122
            if (params.length == 0) { return }
123
            var deps = params[0];
124
            var cb = _.bind(params[1], this);
125
            _.each(deps, function(dep) {
126
              this._set_proxy_attr(attr, dep, cb);
127
            }, this);
128
          }, this);
129
        },
130
        
131
        // Initialize proxy storage model attributes. These attribues allows 
132
        // us to automatically access cross collection associated objects.
133
        init_storage_attrs: function() {
134
          _.each(this.storage_attrs, function(params, attr) {
135
            var store, key, attr_name;
136
            store = synnefo.storage[params[0]];
137
            key = params[1];
138
            attr_resolver = params[2];
139
            if (!attr_resolver) {
140
              attr_resolver = function(model, attr) {
141
                return model.get(attr);
142
              }
143
            }
144
            attr_name = attr;
145
          
146
            var resolve_related_instance = function(storage, attr_name, val) {
147
              var data = {};
148

    
149
              if (!val) { 
150
                // update with undefined and return
151
                data[key] = undefined;
152
                this.set(data);
153
                return;
154
              };
155
            
156
              // retrieve related object (check if its a Model??)
157
              var obj = store.get(val);
158
              
159
              if (obj) {
160
                // set related object
161
                data[attr_name] = obj;
162
                this.set(data, {silent:true})
163
                this.trigger("change:" + attr_name, obj);
164
              } else {
165
                var self = this;
166
                var retry_to_resolve = function(store, val, key) {
167
                  var retries = 0;
168
                  var retry = window.setInterval(function(){
169
                    retries++;
170
                    if (retries > 200) {
171
                      clearInterval(retry);
172
                    }
173
                    var obj = store.get(val);
174
                    if (obj) {
175
                      data[key] = obj;
176
                      self.set(data, {silent:false});
177
                      clearInterval(retry);
178
                    }
179
                  }, 500);
180
                  return retry
181
                }
182
                retry_to_resolve(store, val, key);
183
              }
184
            }
185
            
186
            var self = this;
187
            function init_bindings(instance, store, key, attr, attr_resolver) {
188
              instance.bind('change:' + attr, function(model) {
189
                resolve_related_instance.call(model, store, key, attr_resolver(model, attr));
190
              }, this);
191

    
192
              instance.bind('add', function(model) {
193
                resolve_related_instance.call(model, store, key, attr_resolver(model, attr));
194
              }, this);
195
            }
196

    
197
            init_bindings(this, store, key, attr, attr_resolver);
198
            resolve_related_instance.call(this, store, key, attr_resolver(this, attr));
199
          }, this);
200
        },
201
        
202
        _proxy_model_cache: {},
203
        
204
        _bind_model: function(model, attr, check_attr, cb) {
205
          var proxy_cache_key = attr + '_' + check_attr;
206
          if (this._proxy_model_cache[proxy_cache_key]) {
207
            var proxy = this._proxy_model_cache[proxy_cache_key];
208
            proxy[0].unbind('change', proxy[1]);
209
          }
210
          var data = {};
211
          var changebind = _.bind(function() {
212
            data[attr] = cb.call(this, this.get(check_attr));
213
            this.set(data);
214
          }, this);
215
          model.bind('change', changebind);
216
          this._proxy_model_cache[proxy_cache_key] = [model, changebind];
217
        },
218

    
219
        _bind_attr: function(attr, check_attr, cb) {
220
          this.bind('change:' + check_attr, function() {
221
            if (this.get(check_attr) instanceof models.Model) {
222
              var model = this.get(check_attr);
223
              this._bind_model(model, attr, check_attr, cb);
224
            }
225
            var val = cb.call(this, this.get(check_attr));
226
            var data = {};
227
            if (this.get(attr) !== val) {
228
              data[attr] = val;
229
              this.set(data);
230
            }
231
          }, this);
232
        },
233

    
234
        _set_proxy_attr: function(attr, check_attr, cb) {
235
          // initial set
236
          var data = {};
237
          data[attr] = cb.call(this, this.get(check_attr));
238
          if (data[attr] !== undefined) {
239
            this.set(data, {silent:true});
240
          }
241
          if(this.get(check_attr) instanceof models.Model) {
242
            this._bind_model(this.get(check_attr), attr, check_attr, cb);
243
          }
244
          this._bind_attr(attr, check_attr, cb);
245
        },
246

    
247
        init_proxy_attrs: function() {
248
          _.each(this.proxy_attrs, function(opts, attr){
249
            var cb = opts[1];
250
            _.each(opts[0], function(check_attr){
251
              this._set_proxy_attr(attr, check_attr, cb)
252
            }, this);
253
          }, this);
254
        },
255
        
256
        handle_remove: function() {
257
            if (this.get("status") == 'DELETED') {
258
                if (this.collection) {
259
                    try { this.clear_pending_action();} catch (err) {};
260
                    try { this.reset_pending_actions();} catch (err) {};
261
                    try { this.stop_stats_update();} catch (err) {};
262
                    this.collection.remove(this.id);
263
                }
264
            }
265
        },
266
        
267
        // custom set method to allow submodels to use
268
        // set_<attr> methods for handling the value of each
269
        // attribute and overriding the default set method
270
        // for specific parameters
271
        set: function(params, options) {
272
            _.each(params, _.bind(function(value, key){
273
                if (this["set_" + key]) {
274
                    params[key] = this["set_" + key](value);
275
                }
276
            }, this))
277
            var ret = bb.Model.prototype.set.call(this, params, options);
278
            return ret;
279
        },
280

    
281
        url: function(options) {
282
            return getUrl.call(this, this.base_url) + "/" + this.id;
283
        },
284

    
285
        api_path: function(options) {
286
            return this.path + "/" + this.id;
287
        },
288

    
289
        parse: function(resp, xhr) {
290
        },
291

    
292
        remove: function(complete, error, success) {
293
            this.api_call(this.api_path(), "delete", undefined, complete, error, success);
294
        },
295

    
296
        changedKeys: function() {
297
            return _.keys(this.changedAttributes() || {});
298
        },
299
            
300
        // return list of changed attributes that included in passed list
301
        // argument
302
        getKeysChanged: function(keys) {
303
            return _.intersection(keys, this.changedKeys());
304
        },
305
        
306
        // boolean check of keys changed
307
        keysChanged: function(keys) {
308
            return this.getKeysChanged(keys).length > 0;
309
        },
310

    
311
        // check if any of the passed attribues has changed
312
        hasOnlyChange: function(keys) {
313
            var ret = false;
314
            _.each(keys, _.bind(function(key) {
315
                if (this.changedKeys().length == 1 && this.changedKeys().indexOf(key) > -1) { ret = true};
316
            }, this));
317
            return ret;
318
        }
319

    
320
    })
321
    
322
    // Base object for all our model collections
323
    models.Collection = bb.Collection.extend({
324
        sync: snf.api.sync,
325
        api: snf.api,
326
        api_type: 'compute',
327
        supportIncUpdates: true,
328

    
329
        initialize: function() {
330
            models.Collection.__super__.initialize.apply(this, arguments);
331
            this.api_call = _.bind(this.api.call, this);
332
            if (this.sortFields) {
333
              _.each(this.sortFields, function(f) {
334
                this.bind("change:" + f, _.bind(this.resort, this));
335
              }, this);
336
            }
337
        },
338
          
339
        resort: function() {
340
          this.sort();
341
        },
342

    
343
        url: function(options, method) {
344
            return getUrl.call(this, this.base_url) + (
345
                    options.details || this.details && method != 'create' ? '/detail' : '');
346
        },
347

    
348
        fetch: function(options) {
349
            if (!options) { options = {} };
350
            // default to update
351
            if (!this.noUpdate) {
352
                if (options.update === undefined) { options.update = true };
353
                if (!options.removeMissing && options.refresh) { 
354
                  options.removeMissing = true;
355
                };
356
                // for collections which associated models don't support 
357
                // deleted state identification through attributes, resolve  
358
                // deleted entries by checking for missing objects in fetch 
359
                // responses.
360
                if (this.updateEntries && options.removeMissing === undefined) {
361
                  options.removeMissing = true;
362
                }
363
            } else {
364
                if (options.refresh === undefined) {
365
                    options.refresh = true;
366
                    if (this.updateEntries) {
367
                      options.update = true;
368
                      options.removeMissing = true;
369
                    }
370
                }
371
            }
372
            // custom event foreach fetch
373
            return bb.Collection.prototype.fetch.call(this, options)
374
        },
375

    
376
        create: function(model, options) {
377
            var coll = this;
378
            options || (options = {});
379
            model = this._prepareModel(model, options);
380
            if (!model) return false;
381
            var success = options.success;
382
            options.success = function(nextModel, resp, xhr) {
383
                if (coll.add_on_create) {
384
                  coll.add(nextModel, options);
385
                }
386
                if (success) success(nextModel, resp, xhr);
387
            };
388
            model.save(null, options);
389
            return model;
390
        },
391

    
392
        get_fetcher: function(interval, increase, fast, increase_after_calls, max, initial_call, params) {
393
            var fetch_params = params || {};
394
            var handler_options = {};
395

    
396
            fetch_params.skips_timeouts = true;
397
            handler_options.interval = interval;
398
            handler_options.increase = increase;
399
            handler_options.fast = fast;
400
            handler_options.increase_after_calls = increase_after_calls;
401
            handler_options.max= max;
402
            handler_options.id = "collection id";
403

    
404
            var last_ajax = undefined;
405
            var callback = _.bind(function() {
406
                // clone to avoid referenced objects
407
                var params = _.clone(fetch_params);
408
                updater._ajax = last_ajax;
409
                
410
                // wait for previous request to finish
411
                if (last_ajax && last_ajax.readyState < 4 && last_ajax.statusText != "timeout") {
412
                    // opera readystate for 304 responses is 0
413
                    if (!($.browser.opera && last_ajax.readyState == 0 && last_ajax.status == 304)) {
414
                        return;
415
                    }
416
                }
417
                last_ajax = this.fetch(params);
418
            }, this);
419
            handler_options.callback = callback;
420

    
421
            var updater = new snf.api.updateHandler(_.clone(_.extend(handler_options, fetch_params)));
422
            snf.api.bind("call", _.throttle(_.bind(function(){ updater.faster(true)}, this)), 1000);
423
            return updater;
424
        }
425
    });
426
    
427
    // Image model
428
    models.Image = models.Model.extend({
429
        path: 'images',
430
        
431
        get_size: function() {
432
            return parseInt(this.get('metadata') ? this.get('metadata').size : -1)
433
        },
434

    
435
        get_description: function(escape) {
436
            if (escape == undefined) { escape = true };
437
            if (escape) { return this.escape('description') || "No description available"}
438
            return this.get('description') || "No description available."
439
        },
440

    
441
        get_meta: function(key) {
442
            if (this.get('metadata') && this.get('metadata')) {
443
                if (!this.get('metadata')[key]) { return null }
444
                return _.escape(this.get('metadata')[key]);
445
            } else {
446
                return null;
447
            }
448
        },
449

    
450
        get_meta_keys: function() {
451
            if (this.get('metadata') && this.get('metadata')) {
452
                return _.keys(this.get('metadata'));
453
            } else {
454
                return [];
455
            }
456
        },
457

    
458
        get_owner: function() {
459
            return this.get('owner') || _.keys(synnefo.config.system_images_owners)[0];
460
        },
461

    
462
        get_owner_uuid: function() {
463
            return this.get('owner_uuid');
464
        },
465

    
466
        is_system_image: function() {
467
          var owner = this.get_owner();
468
          return _.include(_.keys(synnefo.config.system_images_owners), owner)
469
        },
470

    
471
        owned_by: function(user) {
472
          if (!user) { user = synnefo.user }
473
          return user.get_username() == this.get('owner_uuid');
474
        },
475

    
476
        display_owner: function() {
477
            var owner = this.get_owner();
478
            if (_.include(_.keys(synnefo.config.system_images_owners), owner)) {
479
                return synnefo.config.system_images_owners[owner];
480
            } else {
481
                return owner;
482
            }
483
        },
484
    
485
        get_readable_size: function() {
486
            if (this.is_deleted()) {
487
                return synnefo.config.image_deleted_size_title || '(none)';
488
            }
489
            return this.get_size() > 0 ? util.readablizeBytes(this.get_size() * 1024 * 1024) : '(none)';
490
        },
491

    
492
        get_os: function() {
493
            return this.get_meta('OS');
494
        },
495

    
496
        get_gui: function() {
497
            return this.get_meta('GUI');
498
        },
499

    
500
        get_created_users: function() {
501
            try {
502
              var users = this.get_meta('users').split(" ");
503
            } catch (err) { users = null }
504
            if (!users) {
505
                var osfamily = this.get_meta('osfamily');
506
                if (osfamily == 'windows') { 
507
                  users = ['Administrator'];
508
                } else {
509
                  users = ['root'];
510
                }
511
            }
512
            return users;
513
        },
514

    
515
        get_sort_order: function() {
516
            return parseInt(this.get('metadata') ? this.get('metadata').sortorder : -1)
517
        },
518

    
519
        get_vm: function() {
520
            var vm_id = this.get("serverRef");
521
            var vm = undefined;
522
            vm = storage.vms.get(vm_id);
523
            return vm;
524
        },
525

    
526
        is_public: function() {
527
            return this.get('is_public') == undefined ? true : this.get('is_public');
528
        },
529

    
530
        is_deleted: function() {
531
            return this.get('status') == "DELETED"
532
        },
533
        
534
        ssh_keys_paths: function() {
535
            return _.map(this.get_created_users(), function(username) {
536
                prepend = '';
537
                if (username != 'root') {
538
                    prepend = '/home'
539
                }
540
                return {'user': username, 'path': '{1}/{0}/.ssh/authorized_keys'.format(username, 
541
                                                             prepend)};
542
            });
543
        },
544

    
545
        _supports_ssh: function() {
546
            if (synnefo.config.support_ssh_os_list.indexOf(this.get_os()) > -1) {
547
                return true;
548
            }
549
            if (this.get_meta('osfamily') == 'linux') {
550
              return true;
551
            }
552
            return false;
553
        },
554

    
555
        supports: function(feature) {
556
            if (feature == "ssh") {
557
                return this._supports_ssh()
558
            }
559
            return false;
560
        },
561

    
562
        personality_data_for_keys: function(keys) {
563
            return _.map(this.ssh_keys_paths(), function(pathinfo) {
564
                var contents = '';
565
                _.each(keys, function(key){
566
                    contents = contents + key.get("content") + "\n"
567
                });
568
                contents = $.base64.encode(contents);
569

    
570
                return {
571
                    path: pathinfo.path,
572
                    contents: contents,
573
                    mode: 0600,
574
                    owner: pathinfo.user
575
                }
576
            });
577
        }
578
    });
579

    
580
    // Flavor model
581
    models.Flavor = models.Model.extend({
582
        path: 'flavors',
583

    
584
        details_string: function() {
585
            return "{0} CPU, {1}MB, {2}GB".format(this.get('cpu'), this.get('ram'), this.get('disk'));
586
        },
587

    
588
        get_disk_size: function() {
589
            return parseInt(this.get("disk") * 1024)
590
        },
591

    
592
        get_ram_size: function() {
593
            return parseInt(this.get("ram"))
594
        },
595

    
596
        get_disk_template_info: function() {
597
            var info = snf.config.flavors_disk_templates_info[this.get("disk_template")];
598
            if (!info) {
599
                info = { name: this.get("disk_template"), description:'' };
600
            }
601
            return info
602
        },
603

    
604
        disk_to_bytes: function() {
605
            return parseInt(this.get("disk")) * 1024 * 1024 * 1024;
606
        },
607

    
608
        ram_to_bytes: function() {
609
            return parseInt(this.get("ram")) * 1024 * 1024;
610
        },
611

    
612
    });
613
    
614
    models.ParamsList = function(){this.initialize.apply(this, arguments)};
615
    _.extend(models.ParamsList.prototype, bb.Events, {
616

    
617
        initialize: function(parent, param_name) {
618
            this.parent = parent;
619
            this.actions = {};
620
            this.param_name = param_name;
621
            this.length = 0;
622
        },
623
        
624
        has_action: function(action) {
625
            return this.actions[action] ? true : false;
626
        },
627
            
628
        _parse_params: function(arguments) {
629
            if (arguments.length <= 1) {
630
                return [];
631
            }
632

    
633
            var args = _.toArray(arguments);
634
            return args.splice(1);
635
        },
636

    
637
        contains: function(action, params) {
638
            params = this._parse_params(arguments);
639
            var has_action = this.has_action(action);
640
            if (!has_action) { return false };
641

    
642
            var paramsEqual = false;
643
            _.each(this.actions[action], function(action_params) {
644
                if (_.isEqual(action_params, params)) {
645
                    paramsEqual = true;
646
                }
647
            });
648
                
649
            return paramsEqual;
650
        },
651
        
652
        is_empty: function() {
653
            return _.isEmpty(this.actions);
654
        },
655

    
656
        add: function(action, params) {
657
            params = this._parse_params(arguments);
658
            if (this.contains.apply(this, arguments)) { return this };
659
            var isnew = false
660
            if (!this.has_action(action)) {
661
                this.actions[action] = [];
662
                isnew = true;
663
            };
664

    
665
            this.actions[action].push(params);
666
            this.parent.trigger("change:" + this.param_name, this.parent, this);
667
            if (isnew) {
668
                this.trigger("add", action, params);
669
            } else {
670
                this.trigger("change", action, params);
671
            }
672
            return this;
673
        },
674
        
675
        remove_all: function(action) {
676
            if (this.has_action(action)) {
677
                delete this.actions[action];
678
                this.parent.trigger("change:" + this.param_name, this.parent, this);
679
                this.trigger("remove", action);
680
            }
681
            return this;
682
        },
683

    
684
        reset: function() {
685
            this.actions = {};
686
            this.parent.trigger("change:" + this.param_name, this.parent, this);
687
            this.trigger("reset");
688
            this.trigger("remove");
689
        },
690

    
691
        remove: function(action, params) {
692
            params = this._parse_params(arguments);
693
            if (!this.has_action(action)) { return this };
694
            var index = -1;
695
            _.each(this.actions[action], _.bind(function(action_params) {
696
                if (_.isEqual(action_params, params)) {
697
                    index = this.actions[action].indexOf(action_params);
698
                }
699
            }, this));
700
            
701
            if (index > -1) {
702
                this.actions[action].splice(index, 1);
703
                if (_.isEmpty(this.actions[action])) {
704
                    delete this.actions[action];
705
                }
706
                this.parent.trigger("change:" + this.param_name, this.parent, this);
707
                this.trigger("remove", action, params);
708
            }
709
        }
710

    
711
    });
712

    
713
    // Virtualmachine model
714
    models.VM = models.Model.extend({
715

    
716
        path: 'servers',
717
        has_status: true,
718
        proxy_attrs: {
719
          'busy': [
720
            ['status', 'state'], function() {
721
              return !_.contains(['ACTIVE', 'STOPPED'], this.get('status'));
722
            }
723
          ],
724
        },
725

    
726
        initialize: function(params) {
727
            var self = this;
728
            this.ports = new Backbone.FilteredCollection(undefined, {
729
              collection: synnefo.storage.ports,
730
              collectionFilter: function(m) {
731
                return self.id == m.get('device_id')
732
            }});
733

    
734
            this.pending_firewalls = {};
735
            
736
            models.VM.__super__.initialize.apply(this, arguments);
737

    
738

    
739
            this.set({state: params.status || "ERROR"});
740
            this.log = new snf.logging.logger("VM " + this.id);
741
            this.pending_action = undefined;
742
            
743
            // init stats parameter
744
            this.set({'stats': undefined}, {silent: true});
745
            // defaults to not update the stats
746
            // each view should handle this vm attribute 
747
            // depending on if it displays stat images or not
748
            this.do_update_stats = false;
749
            
750
            // interval time
751
            // this will dynamicaly change if the server responds that
752
            // images get refreshed on different intervals
753
            this.stats_update_interval = synnefo.config.STATS_INTERVAL || 5000;
754
            this.stats_available = false;
755

    
756
            // initialize interval
757
            this.init_stats_intervals(this.stats_update_interval);
758
            
759
            // handle progress message on instance change
760
            this.bind("change", _.bind(this.update_status_message, this));
761
            this.bind("change:task_state", _.bind(this.update_status, this));
762
            // force update of progress message
763
            this.update_status_message(true);
764
            
765
            // default values
766
            this.bind("change:state", _.bind(function(){
767
                if (this.state() == "DESTROY") { 
768
                    this.handle_destroy() 
769
                }
770
            }, this));
771

    
772
        },
773

    
774
        status: function(st) {
775
            if (!st) { return this.get("status")}
776
            return this.set({status:st});
777
        },
778
        
779
        update_status: function() {
780
            this.set_status(this.get('status'));
781
        },
782

    
783
        set_status: function(st) {
784
            var new_state = this.state_for_api_status(st);
785
            var transition = false;
786

    
787
            if (this.state() != new_state) {
788
                if (models.VM.STATES_TRANSITIONS[this.state()]) {
789
                    transition = this.state();
790
                }
791
            }
792
            
793
            // call it silently to avoid double change trigger
794
            var state = this.state_for_api_status(st);
795
            this.set({'state': state}, {silent: true});
796
            
797
            // trigger transition
798
            if (transition && models.VM.TRANSITION_STATES.indexOf(new_state) == -1) { 
799
                this.trigger("transition", {from:transition, to:new_state}) 
800
            };
801
            return st;
802
        },
803
            
804
        get_diagnostics: function(success) {
805
            this.__make_api_call(this.get_diagnostics_url(),
806
                                 "read", // create so that sync later uses POST to make the call
807
                                 null, // payload
808
                                 function(data) {
809
                                     success(data);
810
                                 },  
811
                                 null, 'diagnostics');
812
        },
813

    
814
        has_diagnostics: function() {
815
            return this.get("diagnostics") && this.get("diagnostics").length;
816
        },
817

    
818
        get_progress_info: function() {
819
            // details about progress message
820
            // contains a list of diagnostic messages
821
            return this.get("status_messages");
822
        },
823

    
824
        get_status_message: function() {
825
            return this.get('status_message');
826
        },
827
        
828
        // extract status message from diagnostics
829
        status_message_from_diagnostics: function(diagnostics) {
830
            var valid_sources_map = synnefo.config.diagnostics_status_messages_map;
831
            var valid_sources = valid_sources_map[this.get('status')];
832
            if (!valid_sources) { return null };
833
            
834
            // filter messsages based on diagnostic source
835
            var messages = _.filter(diagnostics, function(diag) {
836
                return valid_sources.indexOf(diag.source) > -1;
837
            });
838

    
839
            var msg = messages[0];
840
            if (msg) {
841
              var message = msg.message;
842
              var message_tpl = snf.config.diagnostic_messages_tpls[msg.source];
843

    
844
              if (message_tpl) {
845
                  message = message_tpl.replace('MESSAGE', msg.message);
846
              }
847
              return message;
848
            }
849
            
850
            // no message to display, but vm in build state, display
851
            // finalizing message.
852
            if (this.is_building() == 'BUILD') {
853
                return synnefo.config.BUILDING_MESSAGES['FINAL'];
854
            }
855
            return null;
856
        },
857

    
858
        update_status_message: function(force) {
859
            // update only if one of the specified attributes has changed
860
            if (
861
              !this.keysChanged(['diagnostics', 'progress', 'status', 'state'])
862
                && !force
863
            ) { return };
864
            
865
            // if user requested to destroy the vm set the appropriate 
866
            // message.
867
            if (this.get('state') == "DESTROY") { 
868
                message = "Terminating..."
869
                this.set({status_message: message})
870
                return;
871
            }
872
            
873
            // set error message, if vm has diagnostic message display it as
874
            // progress message
875
            if (this.in_error_state()) {
876
                var d = this.get('diagnostics');
877
                if (d && d.length) {
878
                    var message = this.status_message_from_diagnostics(d);
879
                    this.set({status_message: message});
880
                } else {
881
                    this.set({status_message: null});
882
                }
883
                return;
884
            }
885
            
886
            // identify building status message
887
            if (this.is_building()) {
888
                var self = this;
889
                var success = function(msg) {
890
                    self.set({status_message: msg});
891
                }
892
                this.get_building_status_message(success);
893
                return;
894
            }
895

    
896
            this.set({status_message:null});
897
        },
898
            
899
        // get building status message. Asynchronous function since it requires
900
        // access to vm image.
901
        get_building_status_message: function(callback) {
902
            // no progress is set, vm is in initial build status
903
            var progress = this.get("progress");
904
            if (progress == 0 || !progress) {
905
                return callback(BUILDING_MESSAGES['INIT']);
906
            }
907
            
908
            // vm has copy progress, display copy percentage
909
            if (progress > 0 && progress <= 99) {
910
                this.get_copy_details(true, undefined, _.bind(
911
                    function(details){
912
                        callback(BUILDING_MESSAGES['COPY'].format(details.copy, 
913
                                                           details.size, 
914
                                                           details.progress));
915
                }, this));
916
                return;
917
            }
918

    
919
            // copy finished display FINAL message or identify status message
920
            // from diagnostics.
921
            if (progress >= 100) {
922
                if (!this.has_diagnostics()) {
923
                        callback(BUILDING_MESSAGES['FINAL']);
924
                } else {
925
                        var d = this.get("diagnostics");
926
                        var msg = this.status_message_from_diagnostics(d);
927
                        if (msg) {
928
                              callback(msg);
929
                        }
930
                }
931
            }
932
        },
933

    
934
        get_copy_details: function(human, image, callback) {
935
            var human = human || false;
936
            var image = image || this.get_image(_.bind(function(image){
937
                var progress = this.get('progress');
938
                var size = image.get_size();
939
                var size_copied = (size * progress / 100).toFixed(2);
940
                
941
                if (human) {
942
                    size = util.readablizeBytes(size*1024*1024);
943
                    size_copied = util.readablizeBytes(size_copied*1024*1024);
944
                }
945

    
946
                callback({'progress': progress, 'size': size, 'copy': size_copied})
947
            }, this));
948
        },
949

    
950
        start_stats_update: function(force_if_empty) {
951
            var prev_state = this.do_update_stats;
952

    
953
            this.do_update_stats = true;
954
            
955
            // fetcher initialized ??
956
            if (!this.stats_fetcher) {
957
                this.init_stats_intervals();
958
            }
959

    
960

    
961
            // fetcher running ???
962
            if (!this.stats_fetcher.running || !prev_state) {
963
                this.stats_fetcher.start();
964
            }
965

    
966
            if (force_if_empty && this.get("stats") == undefined) {
967
                this.update_stats(true);
968
            }
969
        },
970

    
971
        stop_stats_update: function(stop_calls) {
972
            this.do_update_stats = false;
973

    
974
            if (stop_calls) {
975
                this.stats_fetcher.stop();
976
            }
977
        },
978

    
979
        // clear and reinitialize update interval
980
        init_stats_intervals: function (interval) {
981
            this.stats_fetcher = this.get_stats_fetcher(this.stats_update_interval);
982
            this.stats_fetcher.start();
983
        },
984
        
985
        get_stats_fetcher: function(timeout) {
986
            var cb = _.bind(function(data){
987
                this.update_stats();
988
            }, this);
989
            var fetcher = new snf.api.updateHandler({'callback': cb, interval: timeout, id:'stats'});
990
            return fetcher;
991
        },
992

    
993
        // do the api call
994
        update_stats: function(force) {
995
            // do not update stats if flag not set
996
            if ((!this.do_update_stats && !force) || this.updating_stats) {
997
                return;
998
            }
999

    
1000
            // make the api call, execute handle_stats_update on sucess
1001
            // TODO: onError handler ???
1002
            stats_url = this.url() + "/stats";
1003
            this.updating_stats = true;
1004
            this.sync("read", this, {
1005
                handles_error:true, 
1006
                url: stats_url, 
1007
                refresh:true, 
1008
                success: _.bind(this.handle_stats_update, this),
1009
                error: _.bind(this.handle_stats_error, this),
1010
                complete: _.bind(function(){this.updating_stats = false;}, this),
1011
                critical: false,
1012
                log_error: false,
1013
                skips_timeouts: true
1014
            });
1015
        },
1016

    
1017
        get_attachment: function(id) {
1018
          var attachment = undefined;
1019
          _.each(this.get("attachments"), function(a) {
1020
            if (a.id == id) {
1021
              attachment = a;
1022
            }
1023
          });
1024
          return attachment
1025
        },
1026

    
1027
        _set_stats: function(stats) {
1028
            var silent = silent === undefined ? false : silent;
1029
            // unavailable stats while building
1030
            if (this.get("status") == "BUILD") { 
1031
                this.stats_available = false;
1032
            } else { this.stats_available = true; }
1033

    
1034
            if (this.get("status") == "DESTROY") { this.stats_available = false; }
1035
            
1036
            this.set({stats: stats}, {silent:true});
1037
            this.trigger("stats:update", stats);
1038
        },
1039

    
1040
        unbind: function() {
1041
            models.VM.__super__.unbind.apply(this, arguments);
1042
        },
1043
        
1044
        can_connect: function() {
1045
          return _.contains(["ACTIVE", "STOPPED"], this.get("status"))
1046
        },
1047

    
1048
        can_disconnect: function() {
1049
          return _.contains(["ACTIVE", "STOPPED"], this.get("status"))
1050
        },
1051

    
1052
        can_resize: function() {
1053
          return this.get('status') == 'STOPPED';
1054
        },
1055

    
1056
        handle_stats_error: function() {
1057
            stats = {};
1058
            _.each(['cpuBar', 'cpuTimeSeries', 'netBar', 'netTimeSeries'], function(k) {
1059
                stats[k] = false;
1060
            });
1061

    
1062
            this.set({'stats': stats});
1063
        },
1064

    
1065
        // this method gets executed after a successful vm stats api call
1066
        handle_stats_update: function(data) {
1067
            var self = this;
1068
            // avoid browser caching
1069
            
1070
            if (data.stats && _.size(data.stats) > 0) {
1071
                var ts = $.now();
1072
                var stats = data.stats;
1073
                var images_loaded = 0;
1074
                var images = {};
1075

    
1076
                function check_images_loaded() {
1077
                    images_loaded++;
1078

    
1079
                    if (images_loaded == 4) {
1080
                        self._set_stats(images);
1081
                    }
1082
                }
1083
                _.each(['cpuBar', 'cpuTimeSeries', 'netBar', 'netTimeSeries'], function(k) {
1084
                    
1085
                    stats[k] = stats[k] + "?_=" + ts;
1086
                    
1087
                    var stat = k.slice(0,3);
1088
                    var type = k.slice(3,6) == "Bar" ? "bar" : "time";
1089
                    var img = $("<img />");
1090
                    var val = stats[k];
1091
                    
1092
                    // load stat image to a temporary dom element
1093
                    // update model stats on image load/error events
1094
                    img.load(function() {
1095
                        images[k] = val;
1096
                        check_images_loaded();
1097
                    });
1098

    
1099
                    img.error(function() {
1100
                        images[stat + type] = false;
1101
                        check_images_loaded();
1102
                    });
1103

    
1104
                    img.attr({'src': stats[k]});
1105
                })
1106
                data.stats = stats;
1107
            }
1108

    
1109
            // do we need to change the interval ??
1110
            if (data.stats.refresh * 1000 != this.stats_update_interval) {
1111
                this.stats_update_interval = data.stats.refresh * 1000;
1112
                this.stats_fetcher.interval = this.stats_update_interval;
1113
                this.stats_fetcher.maximum_interval = this.stats_update_interval;
1114
                this.stats_fetcher.stop();
1115
                this.stats_fetcher.start(false);
1116
            }
1117
        },
1118

    
1119
        // helper method that sets the do_update_stats
1120
        // in the future this method could also make an api call
1121
        // immediaetly if needed
1122
        enable_stats_update: function() {
1123
            this.do_update_stats = true;
1124
        },
1125
        
1126
        handle_destroy: function() {
1127
            this.stats_fetcher.stop();
1128
        },
1129

    
1130
        require_reboot: function() {
1131
            if (this.is_active()) {
1132
                this.set({'reboot_required': true});
1133
            }
1134
        },
1135
        
1136
        set_pending_action: function(data) {
1137
            this.pending_action = data;
1138
            return data;
1139
        },
1140

    
1141
        // machine has pending action
1142
        update_pending_action: function(action, force) {
1143
            this.set({pending_action: action});
1144
        },
1145

    
1146
        clear_pending_action: function() {
1147
            this.set({pending_action: undefined});
1148
        },
1149

    
1150
        has_pending_action: function() {
1151
            return this.get("pending_action") ? this.get("pending_action") : false;
1152
        },
1153
        
1154
        // machine is active
1155
        is_active: function() {
1156
            return models.VM.ACTIVE_STATES.indexOf(this.state()) > -1;
1157
        },
1158
        
1159
        // machine is building 
1160
        is_building: function() {
1161
            return models.VM.BUILDING_STATES.indexOf(this.state()) > -1;
1162
        },
1163
        
1164
        is_rebooting: function() {
1165
            return this.state() == 'REBOOT';
1166
        },
1167

    
1168
        in_error_state: function() {
1169
            return this.state() === "ERROR"
1170
        },
1171

    
1172
        // user can connect to machine
1173
        is_connectable: function() {
1174
            return models.VM.CONNECT_STATES.indexOf(this.state()) > -1;
1175
        },
1176
        
1177
        remove_meta: function(key, complete, error) {
1178
            var url = this.api_path() + "/metadata/" + key;
1179
            this.api_call(url, "delete", undefined, complete, error);
1180
        },
1181

    
1182
        save_meta: function(meta, complete, error) {
1183
            var url = this.api_path() + "/metadata/" + meta.key;
1184
            var payload = {meta:{}};
1185
            payload.meta[meta.key] = meta.value;
1186
            payload._options = {
1187
                critical:false, 
1188
                error_params: {
1189
                    title: "Machine metadata error",
1190
                    extra_details: {"Machine id": this.id}
1191
            }};
1192

    
1193
            this.api_call(url, "update", payload, complete, error);
1194
        },
1195

    
1196

    
1197
        // update/get the state of the machine
1198
        state: function() {
1199
            var args = slice.call(arguments);
1200
                
1201
            if (args.length > 0 && models.VM.STATES.indexOf(args[0]) > -1) {
1202
                this.set({'state': args[0]});
1203
            }
1204

    
1205
            return this.get('state');
1206
        },
1207
        
1208
        // get the state that the api status corresponds to
1209
        state_for_api_status: function(status) {
1210
            return this.state_transition(this.state(), status);
1211
        },
1212
        
1213
        // get transition state for the corresponging api status
1214
        state_transition: function(state, new_status) {
1215
            var statuses = models.VM.STATES_TRANSITIONS[state];
1216
            if (statuses) {
1217
                if (statuses.indexOf(new_status) > -1) {
1218
                    return new_status;
1219
                } else {
1220
                    return state;
1221
                }
1222
            } else {
1223
                return new_status;
1224
            }
1225
        },
1226
        
1227
        // the current vm state is a transition state
1228
        in_transition: function() {
1229
            return models.VM.TRANSITION_STATES.indexOf(this.state()) > -1 || 
1230
                models.VM.TRANSITION_STATES.indexOf(this.get('status')) > -1;
1231
        },
1232
        
1233
        // get image object
1234
        get_image: function(callback) {
1235
            if (callback == undefined) { callback = function(){} }
1236
            var image = storage.images.get(this.get('image'));
1237
            if (!image) {
1238
                storage.images.update_unknown_id(this.get('image'), callback);
1239
                return;
1240
            }
1241
            callback(image);
1242
            return image;
1243
        },
1244
        
1245
        // get flavor object
1246
        get_flavor: function() {
1247
            var flv = storage.flavors.get(this.get('flavor'));
1248
            if (!flv) {
1249
                storage.flavors.update_unknown_id(this.get('flavor'));
1250
                flv = storage.flavors.get(this.get('flavor'));
1251
            }
1252
            return flv;
1253
        },
1254

    
1255
        get_resize_flavors: function() {
1256
          var vm_flavor = this.get_flavor();
1257
          var flavors = synnefo.storage.flavors.filter(function(f){
1258
              return f.get('disk_template') ==
1259
              vm_flavor.get('disk_template') && f.get('disk') ==
1260
              vm_flavor.get('disk');
1261
          });
1262
          return flavors;
1263
        },
1264

    
1265
        get_flavor_quotas: function() {
1266
          var flavor = this.get_flavor();
1267
          return {
1268
            cpu: flavor.get('cpu') + 1, 
1269
            ram: flavor.get_ram_size() + 1, 
1270
            disk:flavor.get_disk_size() + 1
1271
          }
1272
        },
1273

    
1274
        get_meta: function(key, deflt) {
1275
            if (this.get('metadata') && this.get('metadata')) {
1276
                if (!this.get('metadata')[key]) { return deflt }
1277
                return _.escape(this.get('metadata')[key]);
1278
            } else {
1279
                return deflt;
1280
            }
1281
        },
1282

    
1283
        get_meta_keys: function() {
1284
            if (this.get('metadata') && this.get('metadata')) {
1285
                return _.keys(this.get('metadata'));
1286
            } else {
1287
                return [];
1288
            }
1289
        },
1290
        
1291
        // get metadata OS value
1292
        get_os: function() {
1293
            var image = this.get_image();
1294
            return this.get_meta('OS') || (image ? 
1295
                                            image.get_os() || "okeanos" : "okeanos");
1296
        },
1297

    
1298
        get_gui: function() {
1299
            return this.get_meta('GUI');
1300
        },
1301
        
1302
        get_hostname: function() {
1303
          var hostname = this.get_meta('hostname') || this.get('fqdn');
1304
          if (!hostname) {
1305
            if (synnefo.config.vm_hostname_format) {
1306
              hostname = synnefo.config.vm_hostname_format.format(this.id);
1307
            } else {
1308
              hostname = 'unknown';
1309
            }
1310
          }
1311
          return hostname;
1312
        },
1313

    
1314
        // get actions that the user can execute
1315
        // depending on the vm state/status
1316
        get_available_actions: function() {
1317
            return models.VM.AVAILABLE_ACTIONS[this.state()];
1318
        },
1319

    
1320
        set_profile: function(profile, net_id) {
1321
        },
1322
        
1323
        // call rename api
1324
        rename: function(new_name) {
1325
            //this.set({'name': new_name});
1326
            this.sync("update", this, {
1327
                critical: true,
1328
                data: {
1329
                    'server': {
1330
                        'name': new_name
1331
                    }
1332
                }, 
1333
                success: _.bind(function(){
1334
                    snf.api.trigger("call");
1335
                }, this)
1336
            });
1337
        },
1338
        
1339
        get_console_url: function(data) {
1340
            var url_params = {
1341
                machine: this.get("name"),
1342
                host_ip: this.get_hostname(),
1343
                host_ip_v6: this.get_hostname(),
1344
                host: data.host,
1345
                port: data.port,
1346
                password: data.password
1347
            }
1348
            return synnefo.config.ui_console_url + '?' + $.param(url_params);
1349
        },
1350
      
1351
        connect_floating_ip: function(ip, cb) {
1352
          this.set({'status': 'CONNECTING'});
1353
          synnefo.storage.ports.create({
1354
            port: {
1355
              network_id: ip.get('floating_network_id'),
1356
              device_id: this.id,
1357
              fixed_ips: [{'ip_address': ip.get('floating_ip_address')}]
1358
            }
1359
          }, {complete: cb, skip_api_error: false})
1360
        },
1361

    
1362
        // action helper
1363
        call: function(action_name, success, error, params) {
1364
            var id_param = [this.id];
1365
            
1366
            params = params || {};
1367
            success = success || function() {};
1368
            error = error || function() {};
1369

    
1370
            var self = this;
1371

    
1372
            switch(action_name) {
1373
                case 'start':
1374
                    this.__make_api_call(this.get_action_url(), // vm actions url
1375
                                         "create", // create so that sync later uses POST to make the call
1376
                                         {start:{}}, // payload
1377
                                         function() {
1378
                                             // set state after successful call
1379
                                             self.state("START"); 
1380
                                             success.apply(this, arguments);
1381
                                             snf.api.trigger("call");
1382
                                         },  
1383
                                         error, 'start', params);
1384
                    break;
1385
                case 'reboot':
1386
                    this.__make_api_call(this.get_action_url(), // vm actions url
1387
                                         "create", // create so that sync later uses POST to make the call
1388
                                         {reboot:{}}, // payload
1389
                                         function() {
1390
                                             // set state after successful call
1391
                                             self.state("REBOOT"); 
1392
                                             success.apply(this, arguments)
1393
                                             snf.api.trigger("call");
1394
                                             self.set({'reboot_required': false});
1395
                                         },
1396
                                         error, 'reboot', params);
1397
                    break;
1398
                case 'shutdown':
1399
                    this.__make_api_call(this.get_action_url(), // vm actions url
1400
                                         "create", // create so that sync later uses POST to make the call
1401
                                         {shutdown:{}}, // payload
1402
                                         function() {
1403
                                             // set state after successful call
1404
                                             self.state("SHUTDOWN"); 
1405
                                             success.apply(this, arguments)
1406
                                             snf.api.trigger("call");
1407
                                         },  
1408
                                         error, 'shutdown', params);
1409
                    break;
1410
                case 'console':
1411
                    this.__make_api_call(this.url() + "/action", "create", 
1412
                                         {'console': {'type':'vnc'}}, 
1413
                                         function(data) {
1414
                        var cons_data = data.console;
1415
                        success.apply(this, [cons_data]);
1416
                    }, undefined, 'console', params)
1417
                    break;
1418
                case 'destroy':
1419
                    this.__make_api_call(this.url(), // vm actions url
1420
                                         "delete", // create so that sync later uses POST to make the call
1421
                                         undefined, // payload
1422
                                         function() {
1423
                                             // set state after successful call
1424
                                             self.state('DESTROY');
1425
                                             success.apply(this, arguments);
1426
                                             synnefo.storage.quotas.get('cyclades.vm').decrease();
1427

    
1428
                                         },  
1429
                                         error, 'destroy', params);
1430
                    break;
1431
                case 'resize':
1432
                    this.__make_api_call(this.get_action_url(), // vm actions url
1433
                                         "create", // create so that sync later uses POST to make the call
1434
                                         {resize: {flavorRef:params.flavor}}, // payload
1435
                                         function() {
1436
                                             self.state('RESIZE');
1437
                                             success.apply(this, arguments);
1438
                                             snf.api.trigger("call");
1439
                                         },  
1440
                                         error, 'resize', params);
1441
                    break;
1442
                case 'addFloatingIp':
1443
                    this.__make_api_call(this.get_action_url(), // vm actions url
1444
                                         "create", // create so that sync later uses POST to make the call
1445
                                         {addFloatingIp: {address:params.address}}, // payload
1446
                                         function() {
1447
                                             self.state('CONNECT');
1448
                                             success.apply(this, arguments);
1449
                                             snf.api.trigger("call");
1450
                                         },  
1451
                                         error, 'addFloatingIp', params);
1452
                    break;
1453
                case 'removeFloatingIp':
1454
                    this.__make_api_call(this.get_action_url(), // vm actions url
1455
                                         "create", // create so that sync later uses POST to make the call
1456
                                         {removeFloatingIp: {address:params.address}}, // payload
1457
                                         function() {
1458
                                             self.state('DISCONNECT');
1459
                                             success.apply(this, arguments);
1460
                                             snf.api.trigger("call");
1461
                                         },  
1462
                                         error, 'addFloatingIp', params);
1463
                    break;
1464
                case 'destroy':
1465
                    this.__make_api_call(this.url(), // vm actions url
1466
                                         "delete", // create so that sync later uses POST to make the call
1467
                                         undefined, // payload
1468
                                         function() {
1469
                                             // set state after successful call
1470
                                             self.state('DESTROY');
1471
                                             success.apply(this, arguments);
1472
                                             synnefo.storage.quotas.get('cyclades.vm').decrease();
1473

    
1474
                                         },  
1475
                                         error, 'destroy', params);
1476
                    break;
1477
                default:
1478
                    throw "Invalid VM action ("+action_name+")";
1479
            }
1480
        },
1481
        
1482
        __make_api_call: function(url, method, data, success, error, action, 
1483
                                  extra_params) {
1484
            var self = this;
1485
            error = error || function(){};
1486
            success = success || function(){};
1487

    
1488
            var params = {
1489
                url: url,
1490
                data: data,
1491
                success: function() { 
1492
                  self.handle_action_succeed.apply(self, arguments); 
1493
                  success.apply(this, arguments)
1494
                },
1495
                error: function() { 
1496
                  self.handle_action_fail.apply(self, arguments);
1497
                  error.apply(this, arguments)
1498
                },
1499
                error_params: { ns: "Machines actions", 
1500
                                title: "'" + this.get("name") + "'" + " " + action + " failed", 
1501
                                extra_details: {
1502
                                  'Machine ID': this.id, 
1503
                                  'URL': url, 
1504
                                  'Action': action || "undefined" },
1505
                                allow_reload: false
1506
                              },
1507
                display: false,
1508
                critical: false
1509
            }
1510
            _.extend(params, extra_params);
1511
            this.sync(method, this, params);
1512
        },
1513

    
1514
        handle_action_succeed: function() {
1515
            this.trigger("action:success", arguments);
1516
        },
1517
        
1518
        reset_action_error: function() {
1519
            this.action_error = false;
1520
            this.trigger("action:fail:reset", this.action_error);
1521
        },
1522

    
1523
        handle_action_fail: function() {
1524
            this.action_error = arguments;
1525
            this.trigger("action:fail", arguments);
1526
        },
1527

    
1528
        get_action_url: function(name) {
1529
            return this.url() + "/action";
1530
        },
1531

    
1532
        get_diagnostics_url: function() {
1533
            return this.url() + "/diagnostics";
1534
        },
1535

    
1536
        get_users: function() {
1537
            var image;
1538
            var users = [];
1539
            try {
1540
              var users = this.get_meta('users').split(" ");
1541
            } catch (err) { users = null }
1542
            if (!users) {
1543
              image = this.get_image();
1544
              if (image) {
1545
                  users = image.get_created_users();
1546
              }
1547
            }
1548
            return users;
1549
        },
1550

    
1551
        get_connection_info: function(host_os, success, error) {
1552
            var url = synnefo.config.ui_connect_url;
1553
            var users = this.get_users();
1554

    
1555
            params = {
1556
                ip_address: this.get_hostname(),
1557
                hostname: this.get_hostname(),
1558
                os: this.get_os(),
1559
                host_os: host_os,
1560
                srv: this.id
1561
            }
1562
            
1563
            if (users.length) { 
1564
                params['username'] = _.last(users)
1565
            }
1566

    
1567
            url = url + "?" + $.param(params);
1568

    
1569
            var ajax = snf.api.sync("read", undefined, { url: url, 
1570
                                                         error:error, 
1571
                                                         success:success, 
1572
                                                         handles_error:1});
1573
        }
1574
    });
1575
    
1576
    models.VM.ACTIONS = [
1577
        'start',
1578
        'shutdown',
1579
        'reboot',
1580
        'console',
1581
        'destroy',
1582
        'resize'
1583
    ]
1584

    
1585
    models.VM.TASK_STATE_STATUS_MAP = {
1586
      'BULDING': 'BUILD',
1587
      'REBOOTING': 'REBOOT',
1588
      'STOPPING': 'SHUTDOWN',
1589
      'STARTING': 'START',
1590
      'RESIZING': 'RESIZE',
1591
      'CONNECTING': 'CONNECT',
1592
      'DISCONNECTING': 'DISCONNECT',
1593
      'DESTROYING': 'DESTROY'
1594
    }
1595

    
1596
    models.VM.AVAILABLE_ACTIONS = {
1597
        'UNKNWON'       : ['destroy'],
1598
        'BUILD'         : ['destroy'],
1599
        'REBOOT'        : ['destroy'],
1600
        'STOPPED'       : ['start', 'destroy', 'resize'],
1601
        'ACTIVE'        : ['shutdown', 'destroy', 'reboot', 'console', 'resize'],
1602
        'ERROR'         : ['destroy'],
1603
        'DELETED'       : ['destroy'],
1604
        'DESTROY'       : ['destroy'],
1605
        'SHUTDOWN'      : ['destroy'],
1606
        'START'         : ['destroy'],
1607
        'CONNECT'       : ['destroy'],
1608
        'DISCONNECT'    : ['destroy'],
1609
        'RESIZE'        : ['destroy']
1610
    }
1611
    
1612
    models.VM.AVAILABLE_ACTIONS_INACTIVE = {
1613
      'resize': ['ACTIVE']
1614
    }
1615

    
1616
    // api status values
1617
    models.VM.STATUSES = [
1618
        'UNKNWON',
1619
        'BUILD',
1620
        'REBOOT',
1621
        'STOPPED',
1622
        'ACTIVE',
1623
        'ERROR',
1624
        'DELETED',
1625
        'RESIZE'
1626
    ]
1627

    
1628
    // api status values
1629
    models.VM.CONNECT_STATES = [
1630
        'ACTIVE',
1631
        'REBOOT',
1632
        'SHUTDOWN'
1633
    ]
1634

    
1635
    // vm states
1636
    models.VM.STATES = models.VM.STATUSES.concat([
1637
        'DESTROY',
1638
        'SHUTDOWN',
1639
        'START',
1640
        'CONNECT',
1641
        'DISCONNECT',
1642
        'FIREWALL',
1643
        'RESIZE'
1644
    ]);
1645
    
1646
    models.VM.STATES_TRANSITIONS = {
1647
        'DESTROY' : ['DELETED'],
1648
        'SHUTDOWN': ['ERROR', 'STOPPED', 'DESTROY'],
1649
        'STOPPED': ['ERROR', 'ACTIVE', 'DESTROY'],
1650
        'ACTIVE': ['ERROR', 'STOPPED', 'REBOOT', 'SHUTDOWN', 'DESTROY'],
1651
        'START': ['ERROR', 'ACTIVE', 'DESTROY'],
1652
        'REBOOT': ['ERROR', 'ACTIVE', 'STOPPED', 'DESTROY'],
1653
        'BUILD': ['ERROR', 'ACTIVE', 'DESTROY'],
1654
        'RESIZE': ['ERROR', 'STOPPED']
1655
    }
1656

    
1657
    models.VM.TRANSITION_STATES = [
1658
        'DESTROY',
1659
        'SHUTDOWN',
1660
        'START',
1661
        'REBOOT',
1662
        'BUILD',
1663
        'RESIZE'
1664
    ]
1665

    
1666
    models.VM.ACTIVE_STATES = [
1667
        'BUILD', 'REBOOT', 'ACTIVE',
1668
        'SHUTDOWN', 'CONNECT', 'DISCONNECT'
1669
    ]
1670

    
1671
    models.VM.BUILDING_STATES = [
1672
        'BUILD'
1673
    ]
1674

    
1675
    models.Images = models.Collection.extend({
1676
        model: models.Image,
1677
        path: 'images',
1678
        details: true,
1679
        noUpdate: true,
1680
        supportIncUpdates: false,
1681
        meta_keys_as_attrs: ["OS", "description", "kernel", "size", "GUI"],
1682
        meta_labels: {},
1683
        read_method: 'read',
1684

    
1685
        // update collection model with id passed
1686
        // making a direct call to the image
1687
        // api url
1688
        update_unknown_id: function(id, callback) {
1689
            var url = getUrl.call(this) + "/" + id;
1690
            this.api_call(this.path + "/" + id, this.read_method, {
1691
              _options:{
1692
                async:true, 
1693
                skip_api_error:true}
1694
              }, undefined, 
1695
            _.bind(function() {
1696
                if (!this.get(id)) {
1697
                            if (this.fallback_service) {
1698
                        // if current service has fallback_service attribute set
1699
                        // use this service to retrieve the missing image model
1700
                        var tmpservice = new this.fallback_service();
1701
                        tmpservice.update_unknown_id(id, _.bind(function(img){
1702
                            img.attributes.status = "DELETED";
1703
                            this.add(img.attributes);
1704
                            callback(this.get(id));
1705
                        }, this));
1706
                    } else {
1707
                        var title = synnefo.config.image_deleted_title || 'Deleted';
1708
                        // else add a dummy DELETED state image entry
1709
                        this.add({id:id, name:title, size:-1, 
1710
                                  progress:100, status:"DELETED"});
1711
                        callback(this.get(id));
1712
                    }   
1713
                } else {
1714
                    callback(this.get(id));
1715
                }
1716
            }, this), _.bind(function(image, msg, xhr) {
1717
                if (!image) {
1718
                    var title = synnefo.config.image_deleted_title || 'Deleted';
1719
                    this.add({id:id, name:title, size:-1, 
1720
                              progress:100, status:"DELETED"});
1721
                    callback(this.get(id));
1722
                    return;
1723
                }
1724
                var img_data = this._read_image_from_request(image, msg, xhr);
1725
                this.add(img_data);
1726
                callback(this.get(id));
1727
            }, this));
1728
        },
1729

    
1730
        _read_image_from_request: function(image, msg, xhr) {
1731
            return image.image;
1732
        },
1733

    
1734
        parse: function (resp, xhr) {
1735
            var parsed = _.map(resp.images, _.bind(this.parse_meta, this));
1736
            parsed = this.fill_owners(parsed);
1737
            return parsed;
1738
        },
1739

    
1740
        fill_owners: function(images) {
1741
            // do translate uuid->displayname if needed
1742
            // store display name in owner attribute for compatibility
1743
            var uuids = [];
1744

    
1745
            var images = _.map(images, function(img, index) {
1746
                if (synnefo.config.translate_uuids) {
1747
                    uuids.push(img['owner']);
1748
                }
1749
                img['owner_uuid'] = img['owner'];
1750
                return img;
1751
            });
1752
            
1753
            if (uuids.length > 0) {
1754
                var handle_results = function(data) {
1755
                    _.each(images, function (img) {
1756
                        img['owner'] = data.uuid_catalog[img['owner_uuid']];
1757
                    });
1758
                }
1759
                // notice the async false
1760
                var uuid_map = this.translate_uuids(uuids, false, 
1761
                                                    handle_results)
1762
            }
1763
            return images;
1764
        },
1765

    
1766
        translate_uuids: function(uuids, async, cb) {
1767
            var url = synnefo.config.user_catalog_url;
1768
            var data = JSON.stringify({'uuids': uuids});
1769
          
1770
            // post to user_catalogs api
1771
            snf.api.sync('create', undefined, {
1772
                url: url,
1773
                data: data,
1774
                async: async,
1775
                success:  cb
1776
            });
1777
        },
1778

    
1779
        get_meta_key: function(img, key) {
1780
            if (img.metadata && img.metadata && img.metadata[key]) {
1781
                return _.escape(img.metadata[key]);
1782
            }
1783
            return undefined;
1784
        },
1785

    
1786
        comparator: function(img) {
1787
            return -img.get_sort_order("sortorder") || 1000 * img.id;
1788
        },
1789

    
1790
        parse_meta: function(img) {
1791
            _.each(this.meta_keys_as_attrs, _.bind(function(key){
1792
                if (img[key]) { return };
1793
                img[key] = this.get_meta_key(img, key) || "";
1794
            }, this));
1795
            return img;
1796
        },
1797

    
1798
        active: function() {
1799
            return this.filter(function(img){return img.get('status') != "DELETED"});
1800
        },
1801

    
1802
        predefined: function() {
1803
            return _.filter(this.active(), function(i) { return !i.get("serverRef")});
1804
        },
1805
        
1806
        fetch_for_type: function(type, complete, error) {
1807
            this.fetch({update:true, 
1808
                        success: complete, 
1809
                        error: error, 
1810
                        skip_api_error: true });
1811
        },
1812
        
1813
        get_images_for_type: function(type) {
1814
            if (this['get_{0}_images'.format(type)]) {
1815
                return this['get_{0}_images'.format(type)]();
1816
            }
1817

    
1818
            return this.active();
1819
        },
1820

    
1821
        update_images_for_type: function(type, onStart, onComplete, onError, force_load) {
1822
            var load = false;
1823
            error = onError || function() {};
1824
            function complete(collection) { 
1825
                onComplete(collection.get_images_for_type(type)); 
1826
            }
1827
            
1828
            // do we need to fetch/update current collection entries
1829
            if (load) {
1830
                onStart();
1831
                this.fetch_for_type(type, complete, error);
1832
            } else {
1833
                // fallback to complete
1834
                complete(this);
1835
            }
1836
        }
1837
    })
1838

    
1839
    models.Flavors = models.Collection.extend({
1840
        model: models.Flavor,
1841
        path: 'flavors',
1842
        details: true,
1843
        noUpdate: true,
1844
        supportIncUpdates: false,
1845
        // update collection model with id passed
1846
        // making a direct call to the flavor
1847
        // api url
1848
        update_unknown_id: function(id, callback) {
1849
            var url = getUrl.call(this) + "/" + id;
1850
            this.api_call(this.path + "/" + id, "read", {_options:{async:false, skip_api_error:true}}, undefined, 
1851
            _.bind(function() {
1852
                this.add({id:id, cpu:"Unknown", ram:"Unknown", disk:"Unknown", name: "Unknown", status:"DELETED"})
1853
            }, this), _.bind(function(flv) {
1854
                if (!flv.flavor.status) { flv.flavor.status = "DELETED" };
1855
                this.add(flv.flavor);
1856
            }, this));
1857
        },
1858

    
1859
        parse: function (resp, xhr) {
1860
            return _.map(resp.flavors, function(o) {
1861
              o.cpu = o['vcpus'];
1862
              o.disk_template = o['SNF:disk_template'];
1863
              return o
1864
            });
1865
        },
1866

    
1867
        comparator: function(flv) {
1868
            return flv.get("disk") * flv.get("cpu") * flv.get("ram");
1869
        },
1870
          
1871
        unavailable_values_for_quotas: function(quotas, flavors, extra) {
1872
            var flavors = flavors || this.active();
1873
            var index = {cpu:[], disk:[], ram:[]};
1874
            var extra = extra == undefined ? {cpu:0, disk:0, ram:0} : extra;
1875
            
1876
            _.each(flavors, function(el) {
1877

    
1878
                var disk_available = quotas['disk'] + extra.disk;
1879
                var disk_size = el.get_disk_size();
1880
                if (index.disk.indexOf(disk_size) == -1) {
1881
                  var disk = el.disk_to_bytes();
1882
                  if (disk > disk_available) {
1883
                    index.disk.push(disk_size);
1884
                  }
1885
                }
1886
                
1887
                var ram_available = quotas['ram'] + extra.ram * 1024 * 1024;
1888
                var ram_size = el.get_ram_size();
1889
                if (index.ram.indexOf(ram_size) == -1) {
1890
                  var ram = el.ram_to_bytes();
1891
                  if (ram > ram_available) {
1892
                    index.ram.push(el.get('ram'))
1893
                  }
1894
                }
1895

    
1896
                var cpu = el.get('cpu');
1897
                var cpu_available = quotas['cpu'] + extra.cpu;
1898
                if (index.cpu.indexOf(cpu) == -1) {
1899
                  if (cpu > cpu_available) {
1900
                    index.cpu.push(el.get('cpu'))
1901
                  }
1902
                }
1903
            });
1904
            return index;
1905
        },
1906

    
1907
        unavailable_values_for_image: function(img, flavors) {
1908
            var flavors = flavors || this.active();
1909
            var size = img.get_size();
1910
            
1911
            var index = {cpu:[], disk:[], ram:[]};
1912

    
1913
            _.each(this.active(), function(el) {
1914
                var img_size = size;
1915
                var flv_size = el.get_disk_size();
1916
                if (flv_size < img_size) {
1917
                    if (index.disk.indexOf(flv_size) == -1) {
1918
                        index.disk.push(flv_size);
1919
                    }
1920
                };
1921
            });
1922
            
1923
            return index;
1924
        },
1925

    
1926
        get_flavor: function(cpu, mem, disk, disk_template, filter_list) {
1927
            if (!filter_list) { filter_list = this.models };
1928
            
1929
            return this.select(function(flv){
1930
                if (flv.get("cpu") == cpu + "" &&
1931
                   flv.get("ram") == mem + "" &&
1932
                   flv.get("disk") == disk + "" &&
1933
                   flv.get("disk_template") == disk_template &&
1934
                   filter_list.indexOf(flv) > -1) { return true; }
1935
            })[0];
1936
        },
1937
        
1938
        get_data: function(lst) {
1939
            var data = {'cpu': [], 'mem':[], 'disk':[], 'disk_template':[]};
1940

    
1941
            _.each(lst, function(flv) {
1942
                if (data.cpu.indexOf(flv.get("cpu")) == -1) {
1943
                    data.cpu.push(flv.get("cpu"));
1944
                }
1945
                if (data.mem.indexOf(flv.get("ram")) == -1) {
1946
                    data.mem.push(flv.get("ram"));
1947
                }
1948
                if (data.disk.indexOf(flv.get("disk")) == -1) {
1949
                    data.disk.push(flv.get("disk"));
1950
                }
1951
                if (data.disk_template.indexOf(flv.get("disk_template")) == -1) {
1952
                    data.disk_template.push(flv.get("disk_template"));
1953
                }
1954
            })
1955
            
1956
            return data;
1957
        },
1958

    
1959
        active: function() {
1960
            return this.filter(function(flv){return flv.get('status') != "DELETED"});
1961
        }
1962
            
1963
    })
1964

    
1965
    models.VMS = models.Collection.extend({
1966
        model: models.VM,
1967
        path: 'servers',
1968
        details: true,
1969
        copy_image_meta: true,
1970

    
1971
        parse: function (resp, xhr) {
1972
            var data = resp;
1973
            if (!resp) { return [] };
1974
            data = _.filter(_.map(resp.servers, 
1975
                                  _.bind(this.parse_vm_api_data, this)), 
1976
                                  function(v){return v});
1977
            return data;
1978
        },
1979

    
1980
        parse_vm_api_data: function(data) {
1981
            // do not add non existing DELETED entries
1982
            if (data.status && data.status == "DELETED") {
1983
                if (!this.get(data.id)) {
1984
                    return false;
1985
                }
1986
            }
1987
            
1988
            if ('SNF:task_state' in data) { 
1989
                data['task_state'] = data['SNF:task_state'];
1990
                if (data['task_state']) {
1991
                    var status = models.VM.TASK_STATE_STATUS_MAP[data['task_state']];
1992
                    if (status) { data['status'] = status }
1993
                }
1994
            }
1995

    
1996
            // OS attribute
1997
            if (this.has_meta(data)) {
1998
                data['OS'] = data.metadata.OS || snf.config.unknown_os;
1999
            }
2000
            
2001
            if (!data.diagnostics) {
2002
                data.diagnostics = [];
2003
            }
2004

    
2005
            // network metadata
2006
            data['firewalls'] = {};
2007
            
2008
            data['fqdn'] = data['SNF:fqdn'] || synnefo.config.vm_hostname_format.format(data['id']);
2009

    
2010
            // if vm has no metadata, no metadata object
2011
            // is in json response, reset it to force
2012
            // value update
2013
            if (!data['metadata']) {
2014
                data['metadata'] = {};
2015
            }
2016
            
2017
            // v2.0 API returns objects
2018
            data.image_obj = data.image;
2019
            data.image = data.image_obj.id;
2020
            data.flavor_obj = data.flavor;
2021
            data.flavor = data.flavor_obj.id;
2022

    
2023
            return data;
2024
        },
2025

    
2026
        get_reboot_required: function() {
2027
            return this.filter(function(vm){return vm.get("reboot_required") == true})
2028
        },
2029

    
2030
        has_pending_actions: function() {
2031
            return this.filter(function(vm){return vm.pending_action}).length > 0;
2032
        },
2033

    
2034
        reset_pending_actions: function() {
2035
            this.each(function(vm) {
2036
                vm.clear_pending_action();
2037
            })
2038
        },
2039

    
2040
        do_all_pending_actions: function(success, error) {
2041
            this.each(function(vm) {
2042
                if (vm.has_pending_action()) {
2043
                    vm.call(vm.pending_action, success, error);
2044
                    vm.clear_pending_action();
2045
                }
2046
            })
2047
        },
2048
        
2049
        do_all_reboots: function(success, error) {
2050
            this.each(function(vm) {
2051
                if (vm.get("reboot_required")) {
2052
                    vm.call("reboot", success, error);
2053
                }
2054
            });
2055
        },
2056

    
2057
        reset_reboot_required: function() {
2058
            this.each(function(vm) {
2059
                vm.set({'reboot_required': undefined});
2060
            })
2061
        },
2062
        
2063
        stop_stats_update: function(exclude) {
2064
            var exclude = exclude || [];
2065
            this.each(function(vm) {
2066
                if (exclude.indexOf(vm) > -1) {
2067
                    return;
2068
                }
2069
                vm.stop_stats_update();
2070
            })
2071
        },
2072
        
2073
        has_meta: function(vm_data) {
2074
            return vm_data.metadata && vm_data.metadata
2075
        },
2076

    
2077
        has_addresses: function(vm_data) {
2078
            return vm_data.metadata && vm_data.metadata
2079
        },
2080

    
2081
        create: function (name, image, flavor, meta, extra, callback) {
2082

    
2083
            if (this.copy_image_meta) {
2084
                if (synnefo.config.vm_image_common_metadata) {
2085
                    _.each(synnefo.config.vm_image_common_metadata, 
2086
                        function(key){
2087
                            if (image.get_meta(key)) {
2088
                                meta[key] = image.get_meta(key);
2089
                            }
2090
                    });
2091
                }
2092

    
2093
                if (image.get("OS")) {
2094
                    meta['OS'] = image.get("OS");
2095
                }
2096
            }
2097
            
2098
            opts = {name: name, imageRef: image.id, flavorRef: flavor.id, 
2099
                    metadata:meta}
2100
            opts = _.extend(opts, extra);
2101
            
2102
            var cb = function(data) {
2103
              synnefo.storage.quotas.get('cyclades.vm').increase();
2104
              callback(data);
2105
            }
2106

    
2107
            this.api_call(this.path, "create", {'server': opts}, undefined, 
2108
                          undefined, cb, {critical: true});
2109
        },
2110

    
2111
        load_missing_images: function(callback) {
2112
          var missing_ids = [];
2113
          var resolved = 0;
2114

    
2115
          // fill missing_ids
2116
          this.each(function(el) {
2117
            var imgid = el.get("image");
2118
            var existing = synnefo.storage.images.get(imgid);
2119
            if (!existing && missing_ids.indexOf(imgid) == -1) {
2120
              missing_ids.push(imgid);
2121
            }
2122
          });
2123
          var check = function() {
2124
            // once all missing ids where resolved continue calling the 
2125
            // callback
2126
            resolved++;
2127
            if (resolved == missing_ids.length) {
2128
              callback(missing_ids)
2129
            }
2130
          }
2131
          if (missing_ids.length == 0) {
2132
            callback(missing_ids);
2133
            return;
2134
          }
2135
          // start resolving missing image ids
2136
          _(missing_ids).each(function(imgid){
2137
            synnefo.storage.images.update_unknown_id(imgid, check);
2138
          });
2139
        },
2140

    
2141
        get_connectable: function() {
2142
            return storage.vms.filter(function(vm){
2143
                return !vm.in_error_state() && !vm.is_building();
2144
            });
2145
        }
2146
    })
2147
    
2148
    models.PublicKey = models.Model.extend({
2149
        path: 'keys',
2150
        api_type: 'userdata',
2151
        detail: false,
2152
        model_actions: {
2153
          'remove': [['name'], function() {
2154
            return true;
2155
          }]
2156
        },
2157

    
2158
        get_public_key: function() {
2159
            return cryptico.publicKeyFromString(this.get("content"));
2160
        },
2161

    
2162
        get_filename: function() {
2163
            return "{0}.pub".format(this.get("name"));
2164
        },
2165

    
2166
        identify_type: function() {
2167
            try {
2168
                var cont = snf.util.validatePublicKey(this.get("content"));
2169
                var type = cont.split(" ")[0];
2170
                return synnefo.util.publicKeyTypesMap[type];
2171
            } catch (err) { return false };
2172
        },
2173

    
2174
        rename: function(new_name) {
2175
          //this.set({'name': new_name});
2176
          this.sync("update", this, {
2177
            critical: true,
2178
            data: {'name': new_name}, 
2179
            success: _.bind(function(){
2180
              snf.api.trigger("call");
2181
            }, this)
2182
          });
2183
        }
2184
    })
2185
    
2186
    models._ActionsModel = models.Model.extend({
2187
      defaults: { pending: null },
2188
      actions: [],
2189
      status: {
2190
        INACTIVE: 0,
2191
        PENDING: 1,
2192
        CALLED: 2
2193
      },
2194

    
2195
      initialize: function(attrs, opts) {
2196
        models._ActionsModel.__super__.initialize.call(this, attrs);
2197
        this.actions = opts.actions;
2198
        this.model = opts.model;
2199
        this.bind("change", function() {
2200
          this.set({'pending': this.get_pending()});
2201
        }, this);
2202
        this.clear();
2203
      },
2204
      
2205
      _in_status: function(st) {
2206
        var actions = null;
2207
        _.each(this.attributes, function(status, action){
2208
          if (status == st) {
2209
            if (!actions) {
2210
              actions = []
2211
            }
2212
            actions.push(action);
2213
          }
2214
        });
2215
        return actions;
2216
      },
2217

    
2218
      get_pending: function() {
2219
        return this._in_status(this.status.PENDING);
2220
      },
2221

    
2222
      unset_pending_action: function(action) {
2223
        var data = {};
2224
        data[action] = this.status.INACTIVE;
2225
        this.set(data);
2226
      },
2227

    
2228
      set_pending_action: function(action, reset_pending) {
2229
        reset_pending = reset_pending === undefined ? true : reset_pending;
2230
        var data = {};
2231
        data[action] = this.status.PENDING;
2232
        if (reset_pending) {
2233
          this.reset_pending();
2234
        }
2235
        this.set(data);
2236
      },
2237
      
2238
      reset_pending: function() {
2239
        var data = {};
2240
        _.each(this.actions, function(action) {
2241
          data[action] = this.status.INACTIVE;
2242
        }, this);
2243
        this.set(data);
2244
      }
2245
    });
2246

    
2247
    models.PublicPool = models.Model.extend({});
2248
    models.PublicPools = models.Collection.extend({
2249
      model: models.PublicPool,
2250
      path: 'os-floating-ip-pools',
2251
      api_type: 'compute',
2252
      noUpdate: true,
2253

    
2254
      parse: function(data) {
2255
        return _.map(data.floating_ip_pools, function(pool) {
2256
          pool.id = pool.name;
2257
          return pool;
2258
        });
2259
      }
2260
    });
2261

    
2262
    models.PublicKeys = models.Collection.extend({
2263
        model: models.PublicKey,
2264
        details: false,
2265
        path: 'keys',
2266
        api_type: 'userdata',
2267
        noUpdate: true,
2268
        updateEntries: true,
2269

    
2270
        generate_new: function(success, error) {
2271
            snf.api.sync('create', undefined, {
2272
                url: getUrl.call(this, this.base_url) + "/generate", 
2273
                success: success, 
2274
                error: error,
2275
                skip_api_error: true
2276
            });
2277
        },
2278
        
2279
        add_crypto_key: function(key, success, error, options) {
2280
            var options = options || {};
2281
            var m = new models.PublicKey();
2282

    
2283
            // guess a name
2284
            var name_tpl = "my generated public key";
2285
            var name = name_tpl;
2286
            var name_count = 1;
2287
            
2288
            while(this.filter(function(m){ return m.get("name") == name }).length > 0) {
2289
                name = name_tpl + " " + name_count;
2290
                name_count++;
2291
            }
2292
            
2293
            m.set({name: name});
2294
            m.set({content: key});
2295
            
2296
            options.success = function () { return success(m) };
2297
            options.errror = error;
2298
            options.skip_api_error = true;
2299
            
2300
            this.create(m.attributes, options);
2301
        }
2302
    });
2303

    
2304
  
2305
    models.Quota = models.Model.extend({
2306

    
2307
        initialize: function() {
2308
            models.Quota.__super__.initialize.apply(this, arguments);
2309
            this.bind("change", this.check, this);
2310
            this.check();
2311
        },
2312
        
2313
        check: function() {
2314
            var usage, limit;
2315
            usage = this.get('usage');
2316
            limit = this.get('limit');
2317
            if (usage >= limit) {
2318
                this.trigger("available");
2319
            } else {
2320
                this.trigger("unavailable");
2321
            }
2322
        },
2323

    
2324
        increase: function(val) {
2325
            if (val === undefined) { val = 1};
2326
            this.set({'usage': this.get('usage') + val})
2327
        },
2328

    
2329
        decrease: function(val) {
2330
            if (val === undefined) { val = 1};
2331
            this.set({'usage': this.get('usage') - val})
2332
        },
2333

    
2334
        can_consume: function() {
2335
            var usage, limit;
2336
            usage = this.get('usage');
2337
            limit = this.get('limit');
2338
            if (usage >= limit) {
2339
                return false
2340
            } else {
2341
                return true
2342
            }
2343
        },
2344
        
2345
        is_bytes: function() {
2346
            return this.get('resource').get('unit') == 'bytes';
2347
        },
2348
        
2349
        get_available: function(active) {
2350
            suffix = '';
2351
            if (active) { suffix = '_active'}
2352
            var value = this.get('limit'+suffix) - this.get('usage'+suffix);
2353
            if (active) {
2354
              if (this.get('available') <= value) {
2355
                value = this.get('available');
2356
              }
2357
            }
2358
            if (value < 0) { return value }
2359
            return value
2360
        },
2361

    
2362
        get_readable: function(key, active) {
2363
            var value;
2364
            if (key == 'available') {
2365
                value = this.get_available(active);
2366
            } else {
2367
                value = this.get(key)
2368
            }
2369
            if (value <= 0) { value = 0 }
2370
            if (!this.is_bytes()) {
2371
              return value + "";
2372
            }
2373
            return snf.util.readablizeBytes(value);
2374
        }
2375
    });
2376

    
2377
    models.Quotas = models.Collection.extend({
2378
        model: models.Quota,
2379
        api_type: 'accounts',
2380
        path: 'quotas',
2381
        parse: function(resp) {
2382
            filtered = _.map(resp.system, function(value, key) {
2383
                var available = (value.limit - value.usage) || 0;
2384
                var available_active = available;
2385
                var keysplit = key.split(".");
2386
                var limit_active = value.limit;
2387
                var usage_active = value.usage;
2388
                keysplit[keysplit.length-1] = "total_" + keysplit[keysplit.length-1];
2389
                var activekey = keysplit.join(".");
2390
                var exists = resp.system[activekey];
2391
                if (exists) {
2392
                    available_active = exists.limit - exists.usage;
2393
                    limit_active = exists.limit;
2394
                    usage_active = exists.usage;
2395
                }
2396
                return _.extend(value, {'name': key, 'id': key, 
2397
                          'available': available,
2398
                          'available_active': available_active,
2399
                          'limit_active': limit_active,
2400
                          'usage_active': usage_active,
2401
                          'resource': snf.storage.resources.get(key)});
2402
            });
2403
            return filtered;
2404
        },
2405
        
2406
        get_by_id: function(k) {
2407
          return this.filter(function(q) { return q.get('name') == k})[0]
2408
        },
2409

    
2410
        get_available_for_vm: function(options) {
2411
          var quotas = synnefo.storage.quotas;
2412
          var key = 'available';
2413
          var available_quota = {};
2414
          _.each(['cyclades.ram', 'cyclades.cpu', 'cyclades.disk'], 
2415
            function (key) {
2416
              var value = quotas.get(key).get_available(true);
2417
              available_quota[key.replace('cyclades.', '')] = value;
2418
          });
2419
          return available_quota;
2420
        }
2421
    })
2422

    
2423
    models.Resource = models.Model.extend({
2424
        api_type: 'accounts',
2425
        path: 'resources'
2426
    });
2427

    
2428
    models.Resources = models.Collection.extend({
2429
        api_type: 'accounts',
2430
        path: 'resources',
2431
        model: models.Network,
2432

    
2433
        parse: function(resp) {
2434
            return _.map(resp, function(value, key) {
2435
                return _.extend(value, {'name': key, 'id': key});
2436
            })
2437
        }
2438
    });
2439
    
2440
    // storage initialization
2441
    snf.storage.images = new models.Images();
2442
    snf.storage.flavors = new models.Flavors();
2443
    snf.storage.vms = new models.VMS();
2444
    snf.storage.keys = new models.PublicKeys();
2445
    snf.storage.resources = new models.Resources();
2446
    snf.storage.quotas = new models.Quotas();
2447
    snf.storage.public_pools = new models.PublicPools();
2448

    
2449
})(this);