Statistics
| Branch: | Tag: | Revision:

root / snf-cyclades-app / synnefo / ui / static / snf / js / models.js @ 1fee361d

History | View | Annotate | Download (85.6 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
          this.actions.bind("set-pending", function(action) {
120
            this.trigger("action:set-pending", action, this.actions, this);
121
          }, this);
122
          this.actions.bind("unset-pending", function(action) {
123
            this.trigger("action:unset-pending", action, this.actions, this);
124
          }, this);
125
          this.actions.bind("reset-pending", function() {
126
            this.trigger("action:reset-pending", this.actions, this);
127
          }, this);
128

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

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

    
201
              instance.bind('add', function(model) {
202
                resolve_related_instance.call(model, store, key, attr_resolver(model, attr));
203
              }, this);
204
            }
205

    
206
            init_bindings(this, store, key, attr, attr_resolver);
207
            resolve_related_instance.call(this, store, key, attr_resolver(this, attr));
208
          }, this);
209
        },
210
        
211
        _proxy_model_cache: {},
212
        
213
        _bind_model: function(model, attr, check_attr, cb) {
214
          var proxy_cache_key = attr + '_' + check_attr;
215
          if (this._proxy_model_cache[proxy_cache_key]) {
216
            var proxy = this._proxy_model_cache[proxy_cache_key];
217
            proxy[0].unbind('change', proxy[1]);
218
          }
219
          var data = {};
220
          var changebind = _.bind(function() {
221
            data[attr] = cb.call(this, this.get(check_attr));
222
            this.set(data);
223
          }, this);
224
          model.bind('change', changebind);
225
          this._proxy_model_cache[proxy_cache_key] = [model, changebind];
226
        },
227

    
228
        _bind_attr: function(attr, check_attr, cb) {
229
          this.bind('change:' + check_attr, function() {
230
            if (this.get(check_attr) instanceof models.Model) {
231
              var model = this.get(check_attr);
232
              this._bind_model(model, attr, check_attr, cb);
233
            }
234
            var val = cb.call(this, this.get(check_attr));
235
            var data = {};
236
            if (this.get(attr) !== val) {
237
              data[attr] = val;
238
              this.set(data);
239
            }
240
          }, this);
241
        },
242

    
243
        _set_proxy_attr: function(attr, check_attr, cb) {
244
          // initial set
245
          var data = {};
246
          data[attr] = cb.call(this, this.get(check_attr));
247
          if (data[attr] !== undefined) {
248
            this.set(data, {silent:true});
249
          }
250
          if(this.get(check_attr) instanceof models.Model) {
251
            this._bind_model(this.get(check_attr), attr, check_attr, cb);
252
          }
253
          this._bind_attr(attr, check_attr, cb);
254
        },
255

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

    
290
        url: function(options) {
291
            return getUrl.call(this, this.base_url) + "/" + this.id;
292
        },
293

    
294
        api_path: function(options) {
295
            return this.path + "/" + this.id;
296
        },
297

    
298
        parse: function(resp, xhr) {
299
        },
300

    
301
        remove: function(complete, error, success) {
302
            this.api_call(this.api_path(), "delete", undefined, complete, error, success);
303
        },
304

    
305
        changedKeys: function() {
306
            return _.keys(this.changedAttributes() || {});
307
        },
308
            
309
        // return list of changed attributes that included in passed list
310
        // argument
311
        getKeysChanged: function(keys) {
312
            return _.intersection(keys, this.changedKeys());
313
        },
314
        
315
        // boolean check of keys changed
316
        keysChanged: function(keys) {
317
            return this.getKeysChanged(keys).length > 0;
318
        },
319

    
320
        // check if any of the passed attribues has changed
321
        hasOnlyChange: function(keys) {
322
            var ret = false;
323
            _.each(keys, _.bind(function(key) {
324
                if (this.changedKeys().length == 1 && this.changedKeys().indexOf(key) > -1) { ret = true};
325
            }, this));
326
            return ret;
327
        }
328

    
329
    })
330
    
331
    // Base object for all our model collections
332
    models.Collection = bb.Collection.extend({
333
        sync: snf.api.sync,
334
        api: snf.api,
335
        api_type: 'compute',
336
        supportIncUpdates: true,
337

    
338
        initialize: function() {
339
            models.Collection.__super__.initialize.apply(this, arguments);
340
            this.api_call = _.bind(this.api.call, this);
341
            if (this.sortFields) {
342
              _.each(this.sortFields, function(f) {
343
                this.bind("change:" + f, _.bind(this.resort, this));
344
              }, this);
345
            }
346
        },
347
          
348
        resort: function() {
349
          this.sort();
350
        },
351

    
352
        url: function(options, method) {
353
            return getUrl.call(this, this.base_url) + (
354
                    options.details || this.details && method != 'create' ? '/detail' : '');
355
        },
356

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

    
385
        create: function(model, options) {
386
            var coll = this;
387
            options || (options = {});
388
            model = this._prepareModel(model, options);
389
            if (!model) return false;
390
            var success = options.success;
391
            options.success = function(nextModel, resp, xhr) {
392
                if (coll.add_on_create) {
393
                  coll.add(nextModel, options);
394
                }
395
                if (success) success(nextModel, resp, xhr);
396
            };
397
            model.save(null, options);
398
            return model;
399
        },
400

    
401
        get_fetcher: function(interval, increase, fast, increase_after_calls, max, initial_call, params) {
402
            var fetch_params = params || {};
403
            var handler_options = {};
404

    
405
            fetch_params.skips_timeouts = true;
406
            handler_options.interval = interval;
407
            handler_options.increase = increase;
408
            handler_options.fast = fast;
409
            handler_options.increase_after_calls = increase_after_calls;
410
            handler_options.max= max;
411
            handler_options.id = "collection id";
412

    
413
            var last_ajax = undefined;
414
            var callback = _.bind(function() {
415
                // clone to avoid referenced objects
416
                var params = _.clone(fetch_params);
417
                updater._ajax = last_ajax;
418
                
419
                // wait for previous request to finish
420
                if (last_ajax && last_ajax.readyState < 4 && last_ajax.statusText != "timeout") {
421
                    // opera readystate for 304 responses is 0
422
                    if (!($.browser.opera && last_ajax.readyState == 0 && last_ajax.status == 304)) {
423
                        return;
424
                    }
425
                }
426
                last_ajax = this.fetch(params);
427
            }, this);
428
            handler_options.callback = callback;
429

    
430
            var updater = new snf.api.updateHandler(_.clone(_.extend(handler_options, fetch_params)));
431
            snf.api.bind("call", _.throttle(_.bind(function(){ updater.faster(true)}, this)), 1000);
432
            return updater;
433
        }
434
    });
435
    
436
    // Image model
437
    models.Image = models.Model.extend({
438
        path: 'images',
439
        
440
        get_size: function() {
441
            return parseInt(this.get('metadata') ? this.get('metadata').size : -1)
442
        },
443

    
444
        get_description: function(escape) {
445
            if (escape == undefined) { escape = true };
446
            if (escape) { return this.escape('description') || "No description available"}
447
            return this.get('description') || "No description available."
448
        },
449

    
450
        get_meta: function(key) {
451
            if (this.get('metadata') && this.get('metadata')) {
452
                if (!this.get('metadata')[key]) { return null }
453
                return _.escape(this.get('metadata')[key]);
454
            } else {
455
                return null;
456
            }
457
        },
458

    
459
        get_meta_keys: function() {
460
            if (this.get('metadata') && this.get('metadata')) {
461
                return _.keys(this.get('metadata'));
462
            } else {
463
                return [];
464
            }
465
        },
466

    
467
        get_owner: function() {
468
            return this.get('owner') || _.keys(synnefo.config.system_images_owners)[0];
469
        },
470

    
471
        get_owner_uuid: function() {
472
            return this.get('owner_uuid');
473
        },
474

    
475
        is_system_image: function() {
476
          var owner = this.get_owner();
477
          return _.include(_.keys(synnefo.config.system_images_owners), owner)
478
        },
479

    
480
        owned_by: function(user) {
481
          if (!user) { user = synnefo.user }
482
          return user.get_username() == this.get('owner_uuid');
483
        },
484

    
485
        display_owner: function() {
486
            var owner = this.get_owner();
487
            if (_.include(_.keys(synnefo.config.system_images_owners), owner)) {
488
                return synnefo.config.system_images_owners[owner];
489
            } else {
490
                return owner;
491
            }
492
        },
493
    
494
        get_readable_size: function() {
495
            if (this.is_deleted()) {
496
                return synnefo.config.image_deleted_size_title || '(none)';
497
            }
498
            return this.get_size() > 0 ? util.readablizeBytes(this.get_size() * 1024 * 1024) : '(none)';
499
        },
500

    
501
        get_os: function() {
502
            return this.get_meta('OS');
503
        },
504

    
505
        get_gui: function() {
506
            return this.get_meta('GUI');
507
        },
508

    
509
        get_created_users: function() {
510
            try {
511
              var users = this.get_meta('users').split(" ");
512
            } catch (err) { users = null }
513
            if (!users) {
514
                var osfamily = this.get_meta('osfamily');
515
                if (osfamily == 'windows') { 
516
                  users = ['Administrator'];
517
                } else {
518
                  users = ['root'];
519
                }
520
            }
521
            return users;
522
        },
523

    
524
        get_sort_order: function() {
525
            return parseInt(this.get('metadata') ? this.get('metadata').sortorder : -1)
526
        },
527

    
528
        get_vm: function() {
529
            var vm_id = this.get("serverRef");
530
            var vm = undefined;
531
            vm = storage.vms.get(vm_id);
532
            return vm;
533
        },
534

    
535
        is_public: function() {
536
            return this.get('is_public') == undefined ? true : this.get('is_public');
537
        },
538

    
539
        is_deleted: function() {
540
            return this.get('status') == "DELETED"
541
        },
542
        
543
        ssh_keys_paths: function() {
544
            return _.map(this.get_created_users(), function(username) {
545
                prepend = '';
546
                if (username != 'root') {
547
                    prepend = '/home'
548
                }
549
                return {'user': username, 'path': '{1}/{0}/.ssh/authorized_keys'.format(username, 
550
                                                             prepend)};
551
            });
552
        },
553

    
554
        _supports_ssh: function() {
555
            if (synnefo.config.support_ssh_os_list.indexOf(this.get_os()) > -1) {
556
                return true;
557
            }
558
            if (this.get_meta('osfamily') == 'linux') {
559
              return true;
560
            }
561
            return false;
562
        },
563

    
564
        supports: function(feature) {
565
            if (feature == "ssh") {
566
                return this._supports_ssh()
567
            }
568
            return false;
569
        },
570

    
571
        personality_data_for_keys: function(keys) {
572
            return _.map(this.ssh_keys_paths(), function(pathinfo) {
573
                var contents = '';
574
                _.each(keys, function(key){
575
                    contents = contents + key.get("content") + "\n"
576
                });
577
                contents = $.base64.encode(contents);
578

    
579
                return {
580
                    path: pathinfo.path,
581
                    contents: contents,
582
                    mode: 0600,
583
                    owner: pathinfo.user
584
                }
585
            });
586
        }
587
    });
588

    
589
    // Flavor model
590
    models.Flavor = models.Model.extend({
591
        path: 'flavors',
592

    
593
        details_string: function() {
594
            return "{0} CPU, {1}MB, {2}GB".format(this.get('cpu'), this.get('ram'), this.get('disk'));
595
        },
596

    
597
        get_disk_size: function() {
598
            return parseInt(this.get("disk") * 1024)
599
        },
600

    
601
        get_ram_size: function() {
602
            return parseInt(this.get("ram"))
603
        },
604

    
605
        get_disk_template_info: function() {
606
            var info = snf.config.flavors_disk_templates_info[this.get("disk_template")];
607
            if (!info) {
608
                info = { name: this.get("disk_template"), description:'' };
609
            }
610
            return info
611
        },
612

    
613
        disk_to_bytes: function() {
614
            return parseInt(this.get("disk")) * 1024 * 1024 * 1024;
615
        },
616

    
617
        ram_to_bytes: function() {
618
            return parseInt(this.get("ram")) * 1024 * 1024;
619
        },
620

    
621
    });
622
    
623
    models.ParamsList = function(){this.initialize.apply(this, arguments)};
624
    _.extend(models.ParamsList.prototype, bb.Events, {
625

    
626
        initialize: function(parent, param_name) {
627
            this.parent = parent;
628
            this.actions = {};
629
            this.param_name = param_name;
630
            this.length = 0;
631
        },
632
        
633
        has_action: function(action) {
634
            return this.actions[action] ? true : false;
635
        },
636
            
637
        _parse_params: function(arguments) {
638
            if (arguments.length <= 1) {
639
                return [];
640
            }
641

    
642
            var args = _.toArray(arguments);
643
            return args.splice(1);
644
        },
645

    
646
        contains: function(action, params) {
647
            params = this._parse_params(arguments);
648
            var has_action = this.has_action(action);
649
            if (!has_action) { return false };
650

    
651
            var paramsEqual = false;
652
            _.each(this.actions[action], function(action_params) {
653
                if (_.isEqual(action_params, params)) {
654
                    paramsEqual = true;
655
                }
656
            });
657
                
658
            return paramsEqual;
659
        },
660
        
661
        is_empty: function() {
662
            return _.isEmpty(this.actions);
663
        },
664

    
665
        add: function(action, params) {
666
            params = this._parse_params(arguments);
667
            if (this.contains.apply(this, arguments)) { return this };
668
            var isnew = false
669
            if (!this.has_action(action)) {
670
                this.actions[action] = [];
671
                isnew = true;
672
            };
673

    
674
            this.actions[action].push(params);
675
            this.parent.trigger("change:" + this.param_name, this.parent, this);
676
            if (isnew) {
677
                this.trigger("add", action, params);
678
            } else {
679
                this.trigger("change", action, params);
680
            }
681
            return this;
682
        },
683
        
684
        remove_all: function(action) {
685
            if (this.has_action(action)) {
686
                delete this.actions[action];
687
                this.parent.trigger("change:" + this.param_name, this.parent, this);
688
                this.trigger("remove", action);
689
            }
690
            return this;
691
        },
692

    
693
        reset: function() {
694
            this.actions = {};
695
            this.parent.trigger("change:" + this.param_name, this.parent, this);
696
            this.trigger("reset");
697
            this.trigger("remove");
698
        },
699

    
700
        remove: function(action, params) {
701
            params = this._parse_params(arguments);
702
            if (!this.has_action(action)) { return this };
703
            var index = -1;
704
            _.each(this.actions[action], _.bind(function(action_params) {
705
                if (_.isEqual(action_params, params)) {
706
                    index = this.actions[action].indexOf(action_params);
707
                }
708
            }, this));
709
            
710
            if (index > -1) {
711
                this.actions[action].splice(index, 1);
712
                if (_.isEmpty(this.actions[action])) {
713
                    delete this.actions[action];
714
                }
715
                this.parent.trigger("change:" + this.param_name, this.parent, this);
716
                this.trigger("remove", action, params);
717
            }
718
        }
719

    
720
    });
721

    
722
    // Virtualmachine model
723
    models.VM = models.Model.extend({
724

    
725
        path: 'servers',
726
        has_status: true,
727
        proxy_attrs: {
728
          'busy': [
729
            ['status', 'state'], function() {
730
              return !_.contains(['ACTIVE', 'STOPPED'], this.get('status'));
731
            }
732
          ],
733
          'in_progress': [
734
            ['status', 'state'], function() {
735
              return this.in_transition();
736
            }
737
          ]
738
        },
739

    
740
        initialize: function(params) {
741
            var self = this;
742
            this.ports = new Backbone.FilteredCollection(undefined, {
743
              collection: synnefo.storage.ports,
744
              collectionFilter: function(m) {
745
                return self.id == m.get('device_id')
746
            }});
747

    
748
            this.pending_firewalls = {};
749
            
750
            models.VM.__super__.initialize.apply(this, arguments);
751

    
752

    
753
            this.set({state: params.status || "ERROR"});
754
            this.log = new snf.logging.logger("VM " + this.id);
755
            this.pending_action = undefined;
756
            
757
            // init stats parameter
758
            this.set({'stats': undefined}, {silent: true});
759
            // defaults to not update the stats
760
            // each view should handle this vm attribute 
761
            // depending on if it displays stat images or not
762
            this.do_update_stats = false;
763
            
764
            // interval time
765
            // this will dynamicaly change if the server responds that
766
            // images get refreshed on different intervals
767
            this.stats_update_interval = synnefo.config.STATS_INTERVAL || 5000;
768
            this.stats_available = false;
769

    
770
            // initialize interval
771
            this.init_stats_intervals(this.stats_update_interval);
772
            
773
            // handle progress message on instance change
774
            this.bind("change", _.bind(this.update_status_message, this));
775
            this.bind("change:task_state", _.bind(this.update_status, this));
776
            // force update of progress message
777
            this.update_status_message(true);
778
            
779
            // default values
780
            this.bind("change:state", _.bind(function(){
781
                if (this.state() == "DESTROY") { 
782
                    this.handle_destroy() 
783
                }
784
            }, this));
785

    
786
        },
787
        
788
        get_public_ips: function() {
789
          var ips = [];
790
          this.ports.filter(function(port) {
791
            if (port.get('network') && !port.get('network').get('is_public')) { return }
792
            if (!port.get("ips")) { return }
793
            port.get("ips").each(function(ip) {
794
              ips.push(ip);
795
            });
796
          });
797
          return ips;
798
        },
799

    
800
        has_public_ip: function() {
801
          return this.ports.filter(function(port) {
802
            return port.get("network") && 
803
                   port.get("network").get("is_public") && 
804
                   port.get("ips").length > 0;
805
          }).length > 0;
806
        },
807

    
808
        has_public_ipv6: function() {
809
          return this.has_ip_version("v6", true);
810
        },
811

    
812
        has_public_ipv4: function() {
813
          return this.has_ip_version("v4", true);
814
        },
815
        
816
        has_ip_version: function(ver, public) {
817
          var found = false;
818
          this.ports.each(function(port) {
819
            if (found) { return }
820
            if (public !== undefined) {
821
              if (port.get("network") && 
822
                  port.get("network").get("is_public") != public) {
823
                return
824
              }
825
            }
826
            port.get('ips').each(function(ip) {
827
              if (found) { return }
828
              if (ip.get("type") == ver) {
829
                found = true
830
              }
831
            })
832
          }, this)
833
          return found;
834
        },
835

    
836
        status: function(st) {
837
            if (!st) { return this.get("status")}
838
            return this.set({status:st});
839
        },
840
        
841
        update_status: function() {
842
            this.set_status(this.get('status'));
843
        },
844

    
845
        set_status: function(st) {
846
            var new_state = this.state_for_api_status(st);
847
            var transition = false;
848

    
849
            if (this.state() != new_state) {
850
                if (models.VM.STATES_TRANSITIONS[this.state()]) {
851
                    transition = this.state();
852
                }
853
            }
854
            
855
            // call it silently to avoid double change trigger
856
            var state = this.state_for_api_status(st);
857
            this.set({'state': state}, {silent: true});
858
            
859
            // trigger transition
860
            if (transition && models.VM.TRANSITION_STATES.indexOf(new_state) == -1) { 
861
                this.trigger("transition", {from:transition, to:new_state}) 
862
            };
863
            return st;
864
        },
865
            
866
        get_diagnostics: function(success) {
867
            this.__make_api_call(this.get_diagnostics_url(),
868
                                 "read", // create so that sync later uses POST to make the call
869
                                 null, // payload
870
                                 function(data) {
871
                                     success(data);
872
                                 },  
873
                                 null, 'diagnostics');
874
        },
875

    
876
        has_diagnostics: function() {
877
            return this.get("diagnostics") && this.get("diagnostics").length;
878
        },
879

    
880
        get_progress_info: function() {
881
            // details about progress message
882
            // contains a list of diagnostic messages
883
            return this.get("status_messages");
884
        },
885

    
886
        get_status_message: function() {
887
            return this.get('status_message');
888
        },
889
        
890
        // extract status message from diagnostics
891
        status_message_from_diagnostics: function(diagnostics) {
892
            var valid_sources_map = synnefo.config.diagnostics_status_messages_map;
893
            var valid_sources = valid_sources_map[this.get('status')];
894
            if (!valid_sources) { return null };
895
            
896
            // filter messsages based on diagnostic source
897
            var messages = _.filter(diagnostics, function(diag) {
898
                return valid_sources.indexOf(diag.source) > -1;
899
            });
900

    
901
            var msg = messages[0];
902
            if (msg) {
903
              var message = msg.message;
904
              var message_tpl = snf.config.diagnostic_messages_tpls[msg.source];
905

    
906
              if (message_tpl) {
907
                  message = message_tpl.replace('MESSAGE', msg.message);
908
              }
909
              return message;
910
            }
911
            
912
            // no message to display, but vm in build state, display
913
            // finalizing message.
914
            if (this.is_building() == 'BUILD') {
915
                return synnefo.config.BUILDING_MESSAGES['FINAL'];
916
            }
917
            return null;
918
        },
919

    
920
        update_status_message: function(force) {
921
            // update only if one of the specified attributes has changed
922
            if (
923
              !this.keysChanged(['diagnostics', 'progress', 'status', 'state'])
924
                && !force
925
            ) { return };
926
            
927
            // if user requested to destroy the vm set the appropriate 
928
            // message.
929
            if (this.get('state') == "DESTROY") { 
930
                message = "Terminating..."
931
                this.set({status_message: message})
932
                return;
933
            }
934
            
935
            // set error message, if vm has diagnostic message display it as
936
            // progress message
937
            if (this.in_error_state()) {
938
                var d = this.get('diagnostics');
939
                if (d && d.length) {
940
                    var message = this.status_message_from_diagnostics(d);
941
                    this.set({status_message: message});
942
                } else {
943
                    this.set({status_message: null});
944
                }
945
                return;
946
            }
947
            
948
            // identify building status message
949
            if (this.is_building()) {
950
                var self = this;
951
                var success = function(msg) {
952
                    self.set({status_message: msg});
953
                }
954
                this.get_building_status_message(success);
955
                return;
956
            }
957

    
958
            this.set({status_message:null});
959
        },
960
            
961
        // get building status message. Asynchronous function since it requires
962
        // access to vm image.
963
        get_building_status_message: function(callback) {
964
            // no progress is set, vm is in initial build status
965
            var progress = this.get("progress");
966
            if (progress == 0 || !progress) {
967
                return callback(BUILDING_MESSAGES['INIT']);
968
            }
969
            
970
            // vm has copy progress, display copy percentage
971
            if (progress > 0 && progress <= 99) {
972
                this.get_copy_details(true, undefined, _.bind(
973
                    function(details){
974
                        callback(BUILDING_MESSAGES['COPY'].format(details.copy, 
975
                                                           details.size, 
976
                                                           details.progress));
977
                }, this));
978
                return;
979
            }
980

    
981
            // copy finished display FINAL message or identify status message
982
            // from diagnostics.
983
            if (progress >= 100) {
984
                if (!this.has_diagnostics()) {
985
                        callback(BUILDING_MESSAGES['FINAL']);
986
                } else {
987
                        var d = this.get("diagnostics");
988
                        var msg = this.status_message_from_diagnostics(d);
989
                        if (msg) {
990
                              callback(msg);
991
                        }
992
                }
993
            }
994
        },
995

    
996
        get_copy_details: function(human, image, callback) {
997
            var human = human || false;
998
            var image = image || this.get_image(_.bind(function(image){
999
                var progress = this.get('progress');
1000
                var size = image.get_size();
1001
                var size_copied = (size * progress / 100).toFixed(2);
1002
                
1003
                if (human) {
1004
                    size = util.readablizeBytes(size*1024*1024);
1005
                    size_copied = util.readablizeBytes(size_copied*1024*1024);
1006
                }
1007

    
1008
                callback({'progress': progress, 'size': size, 'copy': size_copied})
1009
            }, this));
1010
        },
1011

    
1012
        start_stats_update: function(force_if_empty) {
1013
            var prev_state = this.do_update_stats;
1014

    
1015
            this.do_update_stats = true;
1016
            
1017
            // fetcher initialized ??
1018
            if (!this.stats_fetcher) {
1019
                this.init_stats_intervals();
1020
            }
1021

    
1022

    
1023
            // fetcher running ???
1024
            if (!this.stats_fetcher.running || !prev_state) {
1025
                this.stats_fetcher.start();
1026
            }
1027

    
1028
            if (force_if_empty && this.get("stats") == undefined) {
1029
                this.update_stats(true);
1030
            }
1031
        },
1032

    
1033
        stop_stats_update: function(stop_calls) {
1034
            this.do_update_stats = false;
1035

    
1036
            if (stop_calls) {
1037
                this.stats_fetcher.stop();
1038
            }
1039
        },
1040

    
1041
        // clear and reinitialize update interval
1042
        init_stats_intervals: function (interval) {
1043
            this.stats_fetcher = this.get_stats_fetcher(this.stats_update_interval);
1044
            this.stats_fetcher.start();
1045
        },
1046
        
1047
        get_stats_fetcher: function(timeout) {
1048
            var cb = _.bind(function(data){
1049
                this.update_stats();
1050
            }, this);
1051
            var fetcher = new snf.api.updateHandler({'callback': cb, interval: timeout, id:'stats'});
1052
            return fetcher;
1053
        },
1054

    
1055
        // do the api call
1056
        update_stats: function(force) {
1057
            // do not update stats if flag not set
1058
            if ((!this.do_update_stats && !force) || this.updating_stats) {
1059
                return;
1060
            }
1061

    
1062
            // make the api call, execute handle_stats_update on sucess
1063
            // TODO: onError handler ???
1064
            stats_url = this.url() + "/stats";
1065
            this.updating_stats = true;
1066
            this.sync("read", this, {
1067
                handles_error:true, 
1068
                url: stats_url, 
1069
                refresh:true, 
1070
                success: _.bind(this.handle_stats_update, this),
1071
                error: _.bind(this.handle_stats_error, this),
1072
                complete: _.bind(function(){this.updating_stats = false;}, this),
1073
                critical: false,
1074
                log_error: false,
1075
                skips_timeouts: true
1076
            });
1077
        },
1078

    
1079
        get_attachment: function(id) {
1080
          var attachment = undefined;
1081
          _.each(this.get("attachments"), function(a) {
1082
            if (a.id == id) {
1083
              attachment = a;
1084
            }
1085
          });
1086
          return attachment
1087
        },
1088

    
1089
        _set_stats: function(stats) {
1090
            var silent = silent === undefined ? false : silent;
1091
            // unavailable stats while building
1092
            if (this.get("status") == "BUILD") { 
1093
                this.stats_available = false;
1094
            } else { this.stats_available = true; }
1095

    
1096
            if (this.get("status") == "DESTROY") { this.stats_available = false; }
1097
            
1098
            this.set({stats: stats}, {silent:true});
1099
            this.trigger("stats:update", stats);
1100
        },
1101

    
1102
        unbind: function() {
1103
            models.VM.__super__.unbind.apply(this, arguments);
1104
        },
1105
        
1106
        can_connect: function() {
1107
          return _.contains(["ACTIVE", "STOPPED"], this.get("status")) && 
1108
                 !this.get('suspended')
1109
        },
1110

    
1111
        can_disconnect: function() {
1112
          return _.contains(["ACTIVE", "STOPPED"], this.get("status"))
1113
        },
1114

    
1115
        can_resize: function() {
1116
          return this.get('status') == 'STOPPED';
1117
        },
1118

    
1119
        handle_stats_error: function() {
1120
            stats = {};
1121
            _.each(['cpuBar', 'cpuTimeSeries', 'netBar', 'netTimeSeries'], function(k) {
1122
                stats[k] = false;
1123
            });
1124

    
1125
            this.set({'stats': stats});
1126
        },
1127

    
1128
        // this method gets executed after a successful vm stats api call
1129
        handle_stats_update: function(data) {
1130
            var self = this;
1131
            // avoid browser caching
1132
            
1133
            if (data.stats && _.size(data.stats) > 0) {
1134
                var ts = $.now();
1135
                var stats = data.stats;
1136
                var images_loaded = 0;
1137
                var images = {};
1138

    
1139
                function check_images_loaded() {
1140
                    images_loaded++;
1141

    
1142
                    if (images_loaded == 4) {
1143
                        self._set_stats(images);
1144
                    }
1145
                }
1146
                _.each(['cpuBar', 'cpuTimeSeries', 'netBar', 'netTimeSeries'], function(k) {
1147
                    
1148
                    stats[k] = stats[k] + "?_=" + ts;
1149
                    
1150
                    var stat = k.slice(0,3);
1151
                    var type = k.slice(3,6) == "Bar" ? "bar" : "time";
1152
                    var img = $("<img />");
1153
                    var val = stats[k];
1154
                    
1155
                    // load stat image to a temporary dom element
1156
                    // update model stats on image load/error events
1157
                    img.load(function() {
1158
                        images[k] = val;
1159
                        check_images_loaded();
1160
                    });
1161

    
1162
                    img.error(function() {
1163
                        images[stat + type] = false;
1164
                        check_images_loaded();
1165
                    });
1166

    
1167
                    img.attr({'src': stats[k]});
1168
                })
1169
                data.stats = stats;
1170
            }
1171

    
1172
            // do we need to change the interval ??
1173
            if (data.stats.refresh * 1000 != this.stats_update_interval) {
1174
                this.stats_update_interval = data.stats.refresh * 1000;
1175
                this.stats_fetcher.interval = this.stats_update_interval;
1176
                this.stats_fetcher.maximum_interval = this.stats_update_interval;
1177
                this.stats_fetcher.stop();
1178
                this.stats_fetcher.start(false);
1179
            }
1180
        },
1181

    
1182
        // helper method that sets the do_update_stats
1183
        // in the future this method could also make an api call
1184
        // immediaetly if needed
1185
        enable_stats_update: function() {
1186
            this.do_update_stats = true;
1187
        },
1188
        
1189
        handle_destroy: function() {
1190
            this.stats_fetcher.stop();
1191
        },
1192

    
1193
        require_reboot: function() {
1194
            if (this.is_active()) {
1195
                this.set({'reboot_required': true});
1196
            }
1197
        },
1198
        
1199
        set_pending_action: function(data) {
1200
            this.pending_action = data;
1201
            return data;
1202
        },
1203

    
1204
        // machine has pending action
1205
        update_pending_action: function(action, force) {
1206
            this.set({pending_action: action});
1207
        },
1208

    
1209
        clear_pending_action: function() {
1210
            this.set({pending_action: undefined});
1211
        },
1212

    
1213
        has_pending_action: function() {
1214
            return this.get("pending_action") ? this.get("pending_action") : false;
1215
        },
1216
        
1217
        // machine is active
1218
        is_active: function() {
1219
            return models.VM.ACTIVE_STATES.indexOf(this.state()) > -1;
1220
        },
1221
        
1222
        // machine is building 
1223
        is_building: function() {
1224
            return models.VM.BUILDING_STATES.indexOf(this.state()) > -1;
1225
        },
1226
        
1227
        is_rebooting: function() {
1228
            return this.state() == 'REBOOT';
1229
        },
1230

    
1231
        in_error_state: function() {
1232
            return this.state() === "ERROR"
1233
        },
1234

    
1235
        // user can connect to machine
1236
        is_connectable: function() {
1237
            return models.VM.CONNECT_STATES.indexOf(this.state()) > -1;
1238
        },
1239
        
1240
        remove_meta: function(key, complete, error) {
1241
            var url = this.api_path() + "/metadata/" + key;
1242
            this.api_call(url, "delete", undefined, complete, error);
1243
        },
1244

    
1245
        save_meta: function(meta, complete, error) {
1246
            var url = this.api_path() + "/metadata/" + meta.key;
1247
            var payload = {meta:{}};
1248
            payload.meta[meta.key] = meta.value;
1249
            payload._options = {
1250
                critical:false, 
1251
                error_params: {
1252
                    title: "Machine metadata error",
1253
                    extra_details: {"Machine id": this.id}
1254
            }};
1255

    
1256
            this.api_call(url, "update", payload, complete, error);
1257
        },
1258

    
1259

    
1260
        // update/get the state of the machine
1261
        state: function() {
1262
            var args = slice.call(arguments);
1263
                
1264
            if (args.length > 0 && models.VM.STATES.indexOf(args[0]) > -1) {
1265
                this.set({'state': args[0]});
1266
            }
1267

    
1268
            return this.get('state');
1269
        },
1270
        
1271
        // get the state that the api status corresponds to
1272
        state_for_api_status: function(status) {
1273
            return this.state_transition(this.state(), status);
1274
        },
1275
        
1276
        // get transition state for the corresponging api status
1277
        state_transition: function(state, new_status) {
1278
            var statuses = models.VM.STATES_TRANSITIONS[state];
1279
            if (statuses) {
1280
                if (statuses.indexOf(new_status) > -1) {
1281
                    return new_status;
1282
                } else {
1283
                    return state;
1284
                }
1285
            } else {
1286
                return new_status;
1287
            }
1288
        },
1289
        
1290
        // the current vm state is a transition state
1291
        in_transition: function() {
1292
            return models.VM.TRANSITION_STATES.indexOf(this.state()) > -1 || 
1293
                models.VM.TRANSITION_STATES.indexOf(this.get('status')) > -1;
1294
        },
1295
        
1296
        // get image object
1297
        get_image: function(callback) {
1298
            if (callback == undefined) { callback = function(){} }
1299
            var image = storage.images.get(this.get('image'));
1300
            if (!image) {
1301
                storage.images.update_unknown_id(this.get('image'), callback);
1302
                return;
1303
            }
1304
            callback(image);
1305
            return image;
1306
        },
1307
        
1308
        // get flavor object
1309
        get_flavor: function() {
1310
            var flv = storage.flavors.get(this.get('flavor'));
1311
            if (!flv) {
1312
                storage.flavors.update_unknown_id(this.get('flavor'));
1313
                flv = storage.flavors.get(this.get('flavor'));
1314
            }
1315
            return flv;
1316
        },
1317

    
1318
        get_resize_flavors: function() {
1319
          var vm_flavor = this.get_flavor();
1320
          var flavors = synnefo.storage.flavors.filter(function(f){
1321
              return f.get('disk_template') ==
1322
              vm_flavor.get('disk_template') && f.get('disk') ==
1323
              vm_flavor.get('disk');
1324
          });
1325
          return flavors;
1326
        },
1327

    
1328
        get_flavor_quotas: function() {
1329
          var flavor = this.get_flavor();
1330
          return {
1331
            cpu: flavor.get('cpu') + 1, 
1332
            ram: flavor.get_ram_size() + 1, 
1333
            disk:flavor.get_disk_size() + 1
1334
          }
1335
        },
1336

    
1337
        get_meta: function(key, deflt) {
1338
            if (this.get('metadata') && this.get('metadata')) {
1339
                if (!this.get('metadata')[key]) { return deflt }
1340
                return _.escape(this.get('metadata')[key]);
1341
            } else {
1342
                return deflt;
1343
            }
1344
        },
1345

    
1346
        get_meta_keys: function() {
1347
            if (this.get('metadata') && this.get('metadata')) {
1348
                return _.keys(this.get('metadata'));
1349
            } else {
1350
                return [];
1351
            }
1352
        },
1353
        
1354
        // get metadata OS value
1355
        get_os: function() {
1356
            var image = this.get_image();
1357
            return this.get_meta('OS') || (image ? 
1358
                                            image.get_os() || "okeanos" : "okeanos");
1359
        },
1360

    
1361
        get_gui: function() {
1362
            return this.get_meta('GUI');
1363
        },
1364
        
1365
        get_hostname: function() {
1366
          return this.get_meta('hostname') || this.get('fqdn') || synnefo.config.no_fqdn_message;
1367
        },
1368

    
1369
        // get actions that the user can execute
1370
        // depending on the vm state/status
1371
        get_available_actions: function() {
1372
            return models.VM.AVAILABLE_ACTIONS[this.state()];
1373
        },
1374

    
1375
        set_profile: function(profile, net_id) {
1376
        },
1377
        
1378
        // call rename api
1379
        rename: function(new_name) {
1380
            //this.set({'name': new_name});
1381
            this.sync("update", this, {
1382
                critical: true,
1383
                data: {
1384
                    'server': {
1385
                        'name': new_name
1386
                    }
1387
                }, 
1388
                success: _.bind(function(){
1389
                    snf.api.trigger("call");
1390
                }, this)
1391
            });
1392
        },
1393
        
1394
        get_console_url: function(data) {
1395
            var url_params = {
1396
                machine: this.get("name"),
1397
                host_ip: this.get_hostname(),
1398
                host_ip_v6: this.get_hostname(),
1399
                host: data.host,
1400
                port: data.port,
1401
                password: data.password
1402
            }
1403
            return synnefo.config.ui_console_url + '?' + $.param(url_params);
1404
        },
1405
        
1406
        set_firewall: function(nic, value, success_cb, error_cb) {
1407
          var self = this;
1408
          var success = function() { self.require_reboot(); success_cb() }
1409
          var error = function() { error_cb() }
1410
          var data = {'nic': nic.id, 'profile': value, 'display': true};
1411
          var url = this.url() + "/action";
1412
          //var params = {skip_api_error: false, display: true};
1413
          this.call('firewallProfile', success, error, data);
1414
        },
1415

    
1416
        connect_floating_ip: function(ip, cb) {
1417
          this.set({'status': 'CONNECTING'});
1418
          synnefo.storage.ports.create({
1419
            port: {
1420
              network_id: ip.get('floating_network_id'),
1421
              device_id: this.id,
1422
              fixed_ips: [{'ip_address': ip.get('floating_ip_address')}]
1423
            }
1424
          }, {complete: cb, skip_api_error: false})
1425
        },
1426

    
1427
        // action helper
1428
        call: function(action_name, success, error, params) {
1429
            var id_param = [this.id];
1430
            
1431
            params = params || {};
1432
            success = success || function() {};
1433
            error = error || function() {};
1434

    
1435
            var self = this;
1436

    
1437
            switch(action_name) {
1438
                case 'start':
1439
                    this.__make_api_call(this.get_action_url(), // vm actions url
1440
                                         "create", // create so that sync later uses POST to make the call
1441
                                         {start:{}}, // payload
1442
                                         function() {
1443
                                             // set state after successful call
1444
                                             self.state("START"); 
1445
                                             success.apply(this, arguments);
1446
                                             snf.api.trigger("call");
1447
                                         },  
1448
                                         error, 'start', params);
1449
                    break;
1450
                case 'reboot':
1451
                    this.__make_api_call(this.get_action_url(), // vm actions url
1452
                                         "create", // create so that sync later uses POST to make the call
1453
                                         {reboot:{}}, // payload
1454
                                         function() {
1455
                                             // set state after successful call
1456
                                             self.state("REBOOT"); 
1457
                                             success.apply(this, arguments)
1458
                                             snf.api.trigger("call");
1459
                                             self.set({'reboot_required': false});
1460
                                         },
1461
                                         error, 'reboot', params);
1462
                    break;
1463
                case 'shutdown':
1464
                    this.__make_api_call(this.get_action_url(), // vm actions url
1465
                                         "create", // create so that sync later uses POST to make the call
1466
                                         {shutdown:{}}, // payload
1467
                                         function() {
1468
                                             // set state after successful call
1469
                                             self.state("SHUTDOWN"); 
1470
                                             success.apply(this, arguments)
1471
                                             snf.api.trigger("call");
1472
                                         },  
1473
                                         error, 'shutdown', params);
1474
                    break;
1475
                case 'console':
1476
                    this.__make_api_call(this.url() + "/action", "create", 
1477
                                         {'console': {'type':'vnc'}}, 
1478
                                         function(data) {
1479
                        var cons_data = data.console;
1480
                        success.apply(this, [cons_data]);
1481
                    }, undefined, 'console', params)
1482
                    break;
1483
                case 'destroy':
1484
                    this.__make_api_call(this.url(), // vm actions url
1485
                                         "delete", // create so that sync later uses POST to make the call
1486
                                         undefined, // payload
1487
                                         function() {
1488
                                             // set state after successful call
1489
                                             self.state('DESTROY');
1490
                                             success.apply(this, arguments);
1491
                                             synnefo.storage.quotas.get('cyclades.vm').decrease();
1492

    
1493
                                         },  
1494
                                         error, 'destroy', params);
1495
                    break;
1496
                case 'resize':
1497
                    this.__make_api_call(this.get_action_url(), // vm actions url
1498
                                         "create", // create so that sync later uses POST to make the call
1499
                                         {resize: {flavorRef:params.flavor}}, // payload
1500
                                         function() {
1501
                                             self.state('RESIZE');
1502
                                             success.apply(this, arguments);
1503
                                             snf.api.trigger("call");
1504
                                         },  
1505
                                         error, 'resize', params);
1506
                    break;
1507
                case 'destroy':
1508
                    this.__make_api_call(this.url(), // vm actions url
1509
                                         "delete", // create so that sync later uses POST to make the call
1510
                                         undefined, // payload
1511
                                         function() {
1512
                                             // set state after successful call
1513
                                             self.state('DESTROY');
1514
                                             success.apply(this, arguments);
1515
                                             synnefo.storage.quotas.get('cyclades.vm').decrease();
1516

    
1517
                                         },  
1518
                                         error, 'destroy', params);
1519
                    break;
1520
                case 'firewallProfile':
1521
                    this.__make_api_call(this.get_action_url(), // vm actions url
1522
                                         "create",
1523
                                         {firewallProfile:{nic:params.nic, profile:params.profile}}, // payload
1524
                                         function() {
1525
                                             success.apply(this, arguments);
1526
                                             snf.api.trigger("call");
1527
                                         },  
1528
                                         error, 'start', params);
1529
                    break;
1530
                default:
1531
                    throw "Invalid VM action ("+action_name+")";
1532
            }
1533
        },
1534
        
1535
        __make_api_call: function(url, method, data, success, error, action, 
1536
                                  extra_params) {
1537
            var self = this;
1538
            error = error || function(){};
1539
            success = success || function(){};
1540

    
1541
            var params = {
1542
                url: url,
1543
                data: data,
1544
                success: function() { 
1545
                  self.handle_action_succeed.apply(self, arguments); 
1546
                  success.apply(this, arguments)
1547
                },
1548
                error: function() { 
1549
                  self.handle_action_fail.apply(self, arguments);
1550
                  error.apply(this, arguments)
1551
                },
1552
                error_params: { ns: "Machines actions", 
1553
                                title: "'" + this.get("name") + "'" + " " + action + " failed", 
1554
                                extra_details: {
1555
                                  'Machine ID': this.id, 
1556
                                  'URL': url, 
1557
                                  'Action': action || "undefined" },
1558
                                allow_reload: false
1559
                              },
1560
                display: false,
1561
                critical: false
1562
            }
1563
            _.extend(params, extra_params);
1564
            this.sync(method, this, params);
1565
        },
1566

    
1567
        handle_action_succeed: function() {
1568
            this.trigger("action:success", arguments);
1569
        },
1570
        
1571
        reset_action_error: function() {
1572
            this.action_error = false;
1573
            this.trigger("action:fail:reset", this.action_error);
1574
        },
1575

    
1576
        handle_action_fail: function() {
1577
            this.action_error = arguments;
1578
            this.trigger("action:fail", arguments);
1579
        },
1580

    
1581
        get_action_url: function(name) {
1582
            return this.url() + "/action";
1583
        },
1584

    
1585
        get_diagnostics_url: function() {
1586
            return this.url() + "/diagnostics";
1587
        },
1588

    
1589
        get_users: function() {
1590
            var image;
1591
            var users = [];
1592
            try {
1593
              var users = this.get_meta('users').split(" ");
1594
            } catch (err) { users = null }
1595
            if (!users) {
1596
              image = this.get_image();
1597
              if (image) {
1598
                  users = image.get_created_users();
1599
              }
1600
            }
1601
            return users;
1602
        },
1603

    
1604
        get_connection_info: function(host_os, success, error) {
1605
            var url = synnefo.config.ui_connect_url;
1606
            var users = this.get_users();
1607

    
1608
            params = {
1609
                ip_address: this.get_hostname(),
1610
                hostname: this.get_hostname(),
1611
                os: this.get_os(),
1612
                host_os: 'windows',
1613
                ports: JSON.stringify(this.get('SNF:port_forwarding') || {}),
1614
                srv: this.id
1615
            }
1616
            
1617
            if (users.length) { 
1618
                params['username'] = _.last(users)
1619
            }
1620

    
1621
            url = url + "?" + $.param(params);
1622

    
1623
            var ajax = snf.api.sync("read", undefined, { url: url, 
1624
                                                         error:error, 
1625
                                                         success:success, 
1626
                                                         handles_error:1});
1627
        }
1628
    });
1629
    
1630
    models.VM.ACTIONS = [
1631
        'start',
1632
        'shutdown',
1633
        'reboot',
1634
        'console',
1635
        'destroy',
1636
        'resize',
1637
        'snapshot'
1638
    ]
1639

    
1640
    models.VM.TASK_STATE_STATUS_MAP = {
1641
      'BULDING': 'BUILD',
1642
      'REBOOTING': 'REBOOT',
1643
      'STOPPING': 'SHUTDOWN',
1644
      'STARTING': 'START',
1645
      'RESIZING': 'RESIZE',
1646
      'CONNECTING': 'CONNECT',
1647
      'DISCONNECTING': 'DISCONNECT',
1648
      'DESTROYING': 'DESTROY'
1649
    }
1650

    
1651
    models.VM.AVAILABLE_ACTIONS = {
1652
        'UNKNWON'       : ['destroy'],
1653
        'BUILD'         : ['destroy'],
1654
        'REBOOT'        : ['destroy'],
1655
        'STOPPED'       : ['start', 'destroy', 'resize', 'snapshot'],
1656
        'ACTIVE'        : ['shutdown', 'destroy', 'reboot', 'console', 'resize', 'snapshot'],
1657
        'ERROR'         : ['destroy'],
1658
        'DELETED'       : ['destroy'],
1659
        'DESTROY'       : ['destroy'],
1660
        'SHUTDOWN'      : ['destroy'],
1661
        'START'         : ['destroy'],
1662
        'CONNECT'       : ['destroy'],
1663
        'DISCONNECT'    : ['destroy'],
1664
        'RESIZE'        : ['destroy']
1665
    }
1666
    
1667
    models.VM.AVAILABLE_ACTIONS_INACTIVE = {}
1668

    
1669
    // api status values
1670
    models.VM.STATUSES = [
1671
        'UNKNWON',
1672
        'BUILD',
1673
        'REBOOT',
1674
        'STOPPED',
1675
        'ACTIVE',
1676
        'ERROR',
1677
        'DELETED',
1678
        'RESIZE'
1679
    ]
1680

    
1681
    // api status values
1682
    models.VM.CONNECT_STATES = [
1683
        'ACTIVE',
1684
        'REBOOT',
1685
        'SHUTDOWN'
1686
    ]
1687

    
1688
    // vm states
1689
    models.VM.STATES = models.VM.STATUSES.concat([
1690
        'DESTROY',
1691
        'SHUTDOWN',
1692
        'START',
1693
        'CONNECT',
1694
        'DISCONNECT',
1695
        'FIREWALL',
1696
        'RESIZE'
1697
    ]);
1698
    
1699
    models.VM.STATES_TRANSITIONS = {
1700
        'DESTROY' : ['DELETED'],
1701
        'SHUTDOWN': ['ERROR', 'STOPPED', 'DESTROY'],
1702
        'STOPPED': ['ERROR', 'ACTIVE', 'DESTROY'],
1703
        'ACTIVE': ['ERROR', 'STOPPED', 'REBOOT', 'SHUTDOWN', 'DESTROY'],
1704
        'START': ['ERROR', 'ACTIVE', 'DESTROY'],
1705
        'REBOOT': ['ERROR', 'ACTIVE', 'STOPPED', 'DESTROY'],
1706
        'BUILD': ['ERROR', 'ACTIVE', 'DESTROY'],
1707
        'RESIZE': ['ERROR', 'STOPPED']
1708
    }
1709

    
1710
    models.VM.TRANSITION_STATES = [
1711
        'DESTROY',
1712
        'SHUTDOWN',
1713
        'START',
1714
        'REBOOT',
1715
        'BUILD',
1716
        'RESIZE',
1717
        'DISCONNECT',
1718
        'CONNECT'
1719
    ]
1720

    
1721
    models.VM.ACTIVE_STATES = [
1722
        'BUILD', 'REBOOT', 'ACTIVE',
1723
        'SHUTDOWN', 'CONNECT', 'DISCONNECT'
1724
    ]
1725

    
1726
    models.VM.BUILDING_STATES = [
1727
        'BUILD'
1728
    ]
1729

    
1730
    models.Images = models.Collection.extend({
1731
        model: models.Image,
1732
        path: 'images',
1733
        details: true,
1734
        noUpdate: true,
1735
        supportIncUpdates: false,
1736
        meta_keys_as_attrs: ["OS", "description", "kernel", "size", "GUI"],
1737
        meta_labels: {},
1738
        read_method: 'read',
1739

    
1740
        // update collection model with id passed
1741
        // making a direct call to the image
1742
        // api url
1743
        update_unknown_id: function(id, callback) {
1744
            var url = getUrl.call(this) + "/" + id;
1745
            this.api_call(this.path + "/" + id, this.read_method, {
1746
              _options:{
1747
                async:true, 
1748
                skip_api_error:true}
1749
              }, undefined, 
1750
            _.bind(function() {
1751
                if (!this.get(id)) {
1752
                            if (this.fallback_service) {
1753
                        // if current service has fallback_service attribute set
1754
                        // use this service to retrieve the missing image model
1755
                        var tmpservice = new this.fallback_service();
1756
                        tmpservice.update_unknown_id(id, _.bind(function(img){
1757
                            img.attributes.status = "DELETED";
1758
                            this.add(img.attributes);
1759
                            callback(this.get(id));
1760
                        }, this));
1761
                    } else {
1762
                        var title = synnefo.config.image_deleted_title || 'Deleted';
1763
                        // else add a dummy DELETED state image entry
1764
                        this.add({id:id, name:title, size:-1, 
1765
                                  progress:100, status:"DELETED"});
1766
                        callback(this.get(id));
1767
                    }   
1768
                } else {
1769
                    callback(this.get(id));
1770
                }
1771
            }, this), _.bind(function(image, msg, xhr) {
1772
                if (!image) {
1773
                    var title = synnefo.config.image_deleted_title || 'Deleted';
1774
                    this.add({id:id, name:title, size:-1, 
1775
                              progress:100, status:"DELETED"});
1776
                    callback(this.get(id));
1777
                    return;
1778
                }
1779
                var img_data = this._read_image_from_request(image, msg, xhr);
1780
                this.add(img_data);
1781
                callback(this.get(id));
1782
            }, this));
1783
        },
1784

    
1785
        _read_image_from_request: function(image, msg, xhr) {
1786
            return image.image;
1787
        },
1788

    
1789
        parse: function (resp, xhr) {
1790
            var parsed = _.map(resp.images, _.bind(this.parse_meta, this));
1791
            parsed = this.fill_owners(parsed);
1792
            return parsed;
1793
        },
1794

    
1795
        fill_owners: function(images) {
1796
            // do translate uuid->displayname if needed
1797
            // store display name in owner attribute for compatibility
1798
            var uuids = [];
1799

    
1800
            var images = _.map(images, function(img, index) {
1801
                if (synnefo.config.translate_uuids) {
1802
                    uuids.push(img['owner']);
1803
                }
1804
                img['owner_uuid'] = img['owner'];
1805
                return img;
1806
            });
1807
            
1808
            if (uuids.length > 0) {
1809
                var handle_results = function(data) {
1810
                    _.each(images, function (img) {
1811
                        img['owner'] = data.uuid_catalog[img['owner_uuid']];
1812
                    });
1813
                }
1814
                // notice the async false
1815
                var uuid_map = this.translate_uuids(uuids, false, 
1816
                                                    handle_results)
1817
            }
1818
            return images;
1819
        },
1820

    
1821
        translate_uuids: function(uuids, async, cb) {
1822
            var url = synnefo.config.user_catalog_url;
1823
            var data = JSON.stringify({'uuids': uuids});
1824
          
1825
            // post to user_catalogs api
1826
            snf.api.sync('create', undefined, {
1827
                url: url,
1828
                data: data,
1829
                async: async,
1830
                success:  cb
1831
            });
1832
        },
1833

    
1834
        get_meta_key: function(img, key) {
1835
            if (img.metadata && img.metadata && img.metadata[key]) {
1836
                return _.escape(img.metadata[key]);
1837
            }
1838
            return undefined;
1839
        },
1840

    
1841
        comparator: function(img) {
1842
            return -img.get_sort_order("sortorder") || 1000 * img.id;
1843
        },
1844

    
1845
        parse_meta: function(img) {
1846
            _.each(this.meta_keys_as_attrs, _.bind(function(key){
1847
                if (img[key]) { return };
1848
                img[key] = this.get_meta_key(img, key) || "";
1849
            }, this));
1850
            return img;
1851
        },
1852

    
1853
        active: function() {
1854
            return this.filter(function(img){return img.get('status') != "DELETED"});
1855
        },
1856

    
1857
        predefined: function() {
1858
            return _.filter(this.active(), function(i) { return !i.get("serverRef")});
1859
        },
1860
        
1861
        fetch_for_type: function(type, complete, error) {
1862
            this.fetch({update:true, 
1863
                        success: complete, 
1864
                        error: error, 
1865
                        skip_api_error: true });
1866
        },
1867
        
1868
        get_images_for_type: function(type) {
1869
            if (this['get_{0}_images'.format(type)]) {
1870
                return this['get_{0}_images'.format(type)]();
1871
            }
1872

    
1873
            return this.active();
1874
        },
1875

    
1876
        update_images_for_type: function(type, onStart, onComplete, onError, force_load) {
1877
            var load = false;
1878
            error = onError || function() {};
1879
            function complete(collection) { 
1880
                onComplete(collection.get_images_for_type(type)); 
1881
            }
1882
            
1883
            // do we need to fetch/update current collection entries
1884
            if (load) {
1885
                onStart();
1886
                this.fetch_for_type(type, complete, error);
1887
            } else {
1888
                // fallback to complete
1889
                complete(this);
1890
            }
1891
        }
1892
    })
1893

    
1894
    models.Flavors = models.Collection.extend({
1895
        model: models.Flavor,
1896
        path: 'flavors',
1897
        details: true,
1898
        noUpdate: true,
1899
        supportIncUpdates: false,
1900
        // update collection model with id passed
1901
        // making a direct call to the flavor
1902
        // api url
1903
        update_unknown_id: function(id, callback) {
1904
            var url = getUrl.call(this) + "/" + id;
1905
            this.api_call(this.path + "/" + id, "read", {_options:{async:false, skip_api_error:true}}, undefined, 
1906
            _.bind(function() {
1907
                this.add({id:id, cpu:"Unknown", ram:"Unknown", disk:"Unknown", name: "Unknown", status:"DELETED"})
1908
            }, this), _.bind(function(flv) {
1909
                if (!flv.flavor.status) { flv.flavor.status = "DELETED" };
1910
                this.add(flv.flavor);
1911
            }, this));
1912
        },
1913

    
1914
        parse: function (resp, xhr) {
1915
            return _.map(resp.flavors, function(o) {
1916
              o.cpu = o['vcpus'];
1917
              o.disk_template = o['SNF:disk_template'];
1918
              return o
1919
            });
1920
        },
1921

    
1922
        comparator: function(flv) {
1923
            return flv.get("disk") * flv.get("cpu") * flv.get("ram");
1924
        },
1925
          
1926
        unavailable_values_for_quotas: function(quotas, flavors, extra) {
1927
            var flavors = flavors || this.active();
1928
            var index = {cpu:[], disk:[], ram:[]};
1929
            var extra = extra == undefined ? {cpu:0, disk:0, ram:0} : extra;
1930
            
1931
            _.each(flavors, function(el) {
1932

    
1933
                var disk_available = quotas['disk'] + extra.disk;
1934
                var disk_size = el.get_disk_size();
1935
                if (index.disk.indexOf(disk_size) == -1) {
1936
                  var disk = el.disk_to_bytes();
1937
                  if (disk > disk_available) {
1938
                    index.disk.push(disk_size);
1939
                  }
1940
                }
1941
                
1942
                var ram_available = quotas['ram'] + extra.ram * 1024 * 1024;
1943
                var ram_size = el.get_ram_size();
1944
                if (index.ram.indexOf(ram_size) == -1) {
1945
                  var ram = el.ram_to_bytes();
1946
                  if (ram > ram_available) {
1947
                    index.ram.push(el.get('ram'))
1948
                  }
1949
                }
1950

    
1951
                var cpu = el.get('cpu');
1952
                var cpu_available = quotas['cpu'] + extra.cpu;
1953
                if (index.cpu.indexOf(cpu) == -1) {
1954
                  if (cpu > cpu_available) {
1955
                    index.cpu.push(el.get('cpu'))
1956
                  }
1957
                }
1958
            });
1959
            return index;
1960
        },
1961

    
1962
        unavailable_values_for_image: function(img, flavors) {
1963
            var flavors = flavors || this.active();
1964
            var size = img.get_size();
1965
            
1966
            var index = {cpu:[], disk:[], ram:[]};
1967

    
1968
            _.each(this.active(), function(el) {
1969
                var img_size = size;
1970
                var flv_size = el.get_disk_size();
1971
                if (flv_size < img_size) {
1972
                    if (index.disk.indexOf(flv_size) == -1) {
1973
                        index.disk.push(flv_size);
1974
                    }
1975
                };
1976
            });
1977
            
1978
            return index;
1979
        },
1980

    
1981
        get_flavor: function(cpu, mem, disk, disk_template, filter_list) {
1982
            if (!filter_list) { filter_list = this.models };
1983
            
1984
            return this.select(function(flv){
1985
                if (flv.get("cpu") == cpu + "" &&
1986
                   flv.get("ram") == mem + "" &&
1987
                   flv.get("disk") == disk + "" &&
1988
                   flv.get("disk_template") == disk_template &&
1989
                   filter_list.indexOf(flv) > -1) { return true; }
1990
            })[0];
1991
        },
1992
        
1993
        get_data: function(lst) {
1994
            var data = {'cpu': [], 'mem':[], 'disk':[], 'disk_template':[]};
1995

    
1996
            _.each(lst, function(flv) {
1997
                if (data.cpu.indexOf(flv.get("cpu")) == -1) {
1998
                    data.cpu.push(flv.get("cpu"));
1999
                }
2000
                if (data.mem.indexOf(flv.get("ram")) == -1) {
2001
                    data.mem.push(flv.get("ram"));
2002
                }
2003
                if (data.disk.indexOf(flv.get("disk")) == -1) {
2004
                    data.disk.push(flv.get("disk"));
2005
                }
2006
                if (data.disk_template.indexOf(flv.get("disk_template")) == -1) {
2007
                    data.disk_template.push(flv.get("disk_template"));
2008
                }
2009
            })
2010
            
2011
            return data;
2012
        },
2013

    
2014
        active: function() {
2015
            return this.filter(function(flv){return flv.get('status') != "DELETED"});
2016
        }
2017
            
2018
    })
2019

    
2020
    models.VMS = models.Collection.extend({
2021
        model: models.VM,
2022
        path: 'servers',
2023
        details: true,
2024
        copy_image_meta: true,
2025

    
2026
        parse: function (resp, xhr) {
2027
            var data = resp;
2028
            if (!resp) { return [] };
2029
            data = _.filter(_.map(resp.servers, 
2030
                                  _.bind(this.parse_vm_api_data, this)), 
2031
                                  function(v){return v});
2032
            return data;
2033
        },
2034

    
2035
        parse_vm_api_data: function(data) {
2036
            // do not add non existing DELETED entries
2037
            if (data.status && data.status == "DELETED") {
2038
                if (!this.get(data.id)) {
2039
                    return false;
2040
                }
2041
            }
2042
            
2043
            if ('SNF:task_state' in data) { 
2044
                data['task_state'] = data['SNF:task_state'];
2045
                if (data['task_state']) {
2046
                    var status = models.VM.TASK_STATE_STATUS_MAP[data['task_state']];
2047
                    if (status) { data['status'] = status }
2048
                }
2049
            }
2050

    
2051
            // OS attribute
2052
            if (this.has_meta(data)) {
2053
                data['OS'] = data.metadata.OS || snf.config.unknown_os;
2054
            }
2055
            
2056
            if (!data.diagnostics) {
2057
                data.diagnostics = [];
2058
            }
2059

    
2060
            // network metadata
2061
            data['firewalls'] = {};
2062
            data['fqdn'] = data['SNF:fqdn'];
2063

    
2064
            // if vm has no metadata, no metadata object
2065
            // is in json response, reset it to force
2066
            // value update
2067
            if (!data['metadata']) {
2068
                data['metadata'] = {};
2069
            }
2070
            
2071
            // v2.0 API returns objects
2072
            data.image_obj = data.image;
2073
            data.image = data.image_obj.id;
2074
            data.flavor_obj = data.flavor;
2075
            data.flavor = data.flavor_obj.id;
2076

    
2077
            return data;
2078
        },
2079

    
2080
        get_reboot_required: function() {
2081
            return this.filter(function(vm){return vm.get("reboot_required") == true})
2082
        },
2083

    
2084
        has_pending_actions: function() {
2085
            return this.filter(function(vm){return vm.pending_action}).length > 0;
2086
        },
2087

    
2088
        reset_pending_actions: function() {
2089
            this.each(function(vm) {
2090
                vm.clear_pending_action();
2091
            })
2092
        },
2093

    
2094
        do_all_pending_actions: function(success, error) {
2095
            this.each(function(vm) {
2096
                if (vm.has_pending_action()) {
2097
                    vm.call(vm.pending_action, success, error);
2098
                    vm.clear_pending_action();
2099
                }
2100
            })
2101
        },
2102
        
2103
        do_all_reboots: function(success, error) {
2104
            this.each(function(vm) {
2105
                if (vm.get("reboot_required")) {
2106
                    vm.call("reboot", success, error);
2107
                }
2108
            });
2109
        },
2110

    
2111
        reset_reboot_required: function() {
2112
            this.each(function(vm) {
2113
                vm.set({'reboot_required': undefined});
2114
            })
2115
        },
2116
        
2117
        stop_stats_update: function(exclude) {
2118
            var exclude = exclude || [];
2119
            this.each(function(vm) {
2120
                if (exclude.indexOf(vm) > -1) {
2121
                    return;
2122
                }
2123
                vm.stop_stats_update();
2124
            })
2125
        },
2126
        
2127
        has_meta: function(vm_data) {
2128
            return vm_data.metadata && vm_data.metadata
2129
        },
2130

    
2131
        has_addresses: function(vm_data) {
2132
            return vm_data.metadata && vm_data.metadata
2133
        },
2134

    
2135
        create: function (name, image, flavor, meta, extra, callback) {
2136

    
2137
            if (this.copy_image_meta) {
2138
                if (synnefo.config.vm_image_common_metadata) {
2139
                    _.each(synnefo.config.vm_image_common_metadata, 
2140
                        function(key){
2141
                            if (image.get_meta(key)) {
2142
                                meta[key] = image.get_meta(key);
2143
                            }
2144
                    });
2145
                }
2146

    
2147
                if (image.get("OS")) {
2148
                    meta['OS'] = image.get("OS");
2149
                }
2150
            }
2151
            
2152
            opts = {name: name, imageRef: image.id, flavorRef: flavor.id, 
2153
                    metadata:meta}
2154
            opts = _.extend(opts, extra);
2155
            
2156
            var cb = function(data) {
2157
              synnefo.storage.quotas.get('cyclades.vm').increase();
2158
              callback(data);
2159
            }
2160

    
2161
            this.api_call(this.path, "create", {'server': opts}, undefined, 
2162
                          undefined, cb, {critical: true});
2163
        },
2164

    
2165
        load_missing_images: function(callback) {
2166
          var missing_ids = [];
2167
          var resolved = 0;
2168

    
2169
          // fill missing_ids
2170
          this.each(function(el) {
2171
            var imgid = el.get("image");
2172
            var existing = synnefo.storage.images.get(imgid);
2173
            if (!existing && missing_ids.indexOf(imgid) == -1) {
2174
              missing_ids.push(imgid);
2175
            }
2176
          });
2177
          var check = function() {
2178
            // once all missing ids where resolved continue calling the 
2179
            // callback
2180
            resolved++;
2181
            if (resolved == missing_ids.length) {
2182
              callback(missing_ids)
2183
            }
2184
          }
2185
          if (missing_ids.length == 0) {
2186
            callback(missing_ids);
2187
            return;
2188
          }
2189
          // start resolving missing image ids
2190
          _(missing_ids).each(function(imgid){
2191
            synnefo.storage.images.update_unknown_id(imgid, check);
2192
          });
2193
        },
2194

    
2195
        get_connectable: function() {
2196
            return storage.vms.filter(function(vm){
2197
                return !vm.in_error_state() && !vm.is_building();
2198
            });
2199
        }
2200
    })
2201
    
2202
    models.PublicKey = models.Model.extend({
2203
        path: 'keys',
2204
        api_type: 'userdata',
2205
        detail: false,
2206
        model_actions: {
2207
          'remove': [['name'], function() {
2208
            return true;
2209
          }]
2210
        },
2211

    
2212
        get_public_key: function() {
2213
            return cryptico.publicKeyFromString(this.get("content"));
2214
        },
2215

    
2216
        get_filename: function() {
2217
            return "{0}.pub".format(this.get("name"));
2218
        },
2219

    
2220
        identify_type: function() {
2221
            try {
2222
                var cont = snf.util.validatePublicKey(this.get("content"));
2223
                var type = cont.split(" ")[0];
2224
                return synnefo.util.publicKeyTypesMap[type];
2225
            } catch (err) { return false };
2226
        },
2227

    
2228
        rename: function(new_name) {
2229
          //this.set({'name': new_name});
2230
          this.sync("update", this, {
2231
            critical: true,
2232
            data: {'name': new_name}, 
2233
            success: _.bind(function(){
2234
              snf.api.trigger("call");
2235
            }, this)
2236
          });
2237
        },
2238

    
2239
        do_remove: function() {
2240
          this.actions.reset_pending();
2241
          this.remove(function() {
2242
            synnefo.storage.keys.fetch();
2243
          });
2244
        }
2245
    })
2246
    
2247
    models._ActionsModel = models.Model.extend({
2248
      defaults: { pending: null },
2249
      actions: [],
2250
      status: {
2251
        INACTIVE: 0,
2252
        PENDING: 1,
2253
        CALLED: 2
2254
      },
2255

    
2256
      initialize: function(attrs, opts) {
2257
        models._ActionsModel.__super__.initialize.call(this, attrs);
2258
        this.actions = opts.actions;
2259
        this.model = opts.model;
2260
        this.bind("change", function() {
2261
          this.set({'pending': this.get_pending()});
2262
        }, this);
2263
        this.clear();
2264
      },
2265
      
2266
      _in_status: function(st) {
2267
        var actions = null;
2268
        _.each(this.attributes, function(status, action){
2269
          if (status == st) {
2270
            if (!actions) {
2271
              actions = []
2272
            }
2273
            actions.push(action);
2274
          }
2275
        });
2276
        return actions;
2277
      },
2278

    
2279
      get_pending: function() {
2280
        return this._in_status(this.status.PENDING);
2281
      },
2282

    
2283
      unset_pending_action: function(action) {
2284
        var data = {};
2285
        data[action] = this.status.INACTIVE;
2286
        this.set(data);
2287
        this.trigger("unset-pending", action);
2288
      },
2289

    
2290
      set_pending_action: function(action, reset_pending) {
2291
        reset_pending = reset_pending === undefined ? true : reset_pending;
2292
        var data = {};
2293
        data[action] = this.status.PENDING;
2294
        if (reset_pending) {
2295
          this.reset_pending();
2296
        }
2297
        this.set(data);
2298
        this.trigger("set-pending", action);
2299
      },
2300
      
2301
      reset_pending: function() {
2302
        var data = {};
2303
        _.each(this.actions, function(action) {
2304
          data[action] = this.status.INACTIVE;
2305
        }, this);
2306
        this.set(data);
2307
        this.trigger("reset-pending");
2308
      }
2309
    });
2310

    
2311
    models.PublicPool = models.Model.extend({});
2312
    models.PublicPools = models.Collection.extend({
2313
      model: models.PublicPool,
2314
      path: 'os-floating-ip-pools',
2315
      api_type: 'compute',
2316
      noUpdate: true,
2317

    
2318
      parse: function(data) {
2319
        return _.map(data.floating_ip_pools, function(pool) {
2320
          pool.id = pool.name;
2321
          return pool;
2322
        });
2323
      }
2324
    });
2325

    
2326
    models.PublicKeys = models.Collection.extend({
2327
        model: models.PublicKey,
2328
        details: false,
2329
        path: 'keys',
2330
        api_type: 'userdata',
2331
        noUpdate: true,
2332
        updateEntries: true,
2333

    
2334
        generate_new: function(success, error) {
2335
            snf.api.sync('create', undefined, {
2336
                url: getUrl.call(this, this.base_url) + "/generate", 
2337
                success: success, 
2338
                error: error,
2339
                skip_api_error: true
2340
            });
2341
        },
2342
        
2343
        add_crypto_key: function(key, success, error, options) {
2344
            var options = options || {};
2345
            var m = new models.PublicKey();
2346

    
2347
            // guess a name
2348
            var name_tpl = "my generated public key";
2349
            var name = name_tpl;
2350
            var name_count = 1;
2351
            
2352
            while(this.filter(function(m){ return m.get("name") == name }).length > 0) {
2353
                name = name_tpl + " " + name_count;
2354
                name_count++;
2355
            }
2356
            
2357
            m.set({name: name});
2358
            m.set({content: key});
2359
            
2360
            options.success = function () { return success(m) };
2361
            options.errror = error;
2362
            options.skip_api_error = true;
2363
            
2364
            this.create(m.attributes, options);
2365
        }
2366
    });
2367

    
2368
  
2369
    models.Quota = models.Model.extend({
2370

    
2371
        initialize: function() {
2372
            models.Quota.__super__.initialize.apply(this, arguments);
2373
            this.bind("change", this.check, this);
2374
            this.check();
2375
        },
2376
        
2377
        check: function() {
2378
            var usage, limit;
2379
            usage = this.get('usage');
2380
            limit = this.get('limit');
2381
            if (usage >= limit) {
2382
                this.trigger("available");
2383
            } else {
2384
                this.trigger("unavailable");
2385
            }
2386
        },
2387

    
2388
        increase: function(val) {
2389
            if (val === undefined) { val = 1};
2390
            this.set({'usage': this.get('usage') + val})
2391
        },
2392

    
2393
        decrease: function(val) {
2394
            if (val === undefined) { val = 1};
2395
            this.set({'usage': this.get('usage') - val})
2396
        },
2397

    
2398
        can_consume: function() {
2399
            var usage, limit;
2400
            usage = this.get('usage');
2401
            limit = this.get('limit');
2402
            if (usage >= limit) {
2403
                return false
2404
            } else {
2405
                return true
2406
            }
2407
        },
2408
        
2409
        is_bytes: function() {
2410
            return this.get('resource').get('unit') == 'bytes';
2411
        },
2412
        
2413
        get_available: function(active) {
2414
            suffix = '';
2415
            if (active) { suffix = '_active'}
2416
            var value = this.get('limit'+suffix) - this.get('usage'+suffix);
2417
            if (active) {
2418
              if (this.get('available') <= value) {
2419
                value = this.get('available');
2420
              }
2421
            }
2422
            if (value < 0) { return value }
2423
            return value
2424
        },
2425

    
2426
        get_readable: function(key, active) {
2427
            var value;
2428
            if (key == 'available') {
2429
                value = this.get_available(active);
2430
            } else {
2431
                value = this.get(key)
2432
            }
2433
            if (value <= 0) { value = 0 }
2434
            if (!this.is_bytes()) {
2435
              return value + "";
2436
            }
2437
            return snf.util.readablizeBytes(value);
2438
        }
2439
    });
2440

    
2441
    models.Quotas = models.Collection.extend({
2442
        model: models.Quota,
2443
        api_type: 'accounts',
2444
        path: 'quotas',
2445
        parse: function(resp) {
2446
            filtered = _.map(resp.system, function(value, key) {
2447
                var available = (value.limit - value.usage) || 0;
2448
                var available_active = available;
2449
                var keysplit = key.split(".");
2450
                var limit_active = value.limit;
2451
                var usage_active = value.usage;
2452
                keysplit[keysplit.length-1] = "total_" + keysplit[keysplit.length-1];
2453
                var activekey = keysplit.join(".");
2454
                var exists = resp.system[activekey];
2455
                if (exists) {
2456
                    available_active = exists.limit - exists.usage;
2457
                    limit_active = exists.limit;
2458
                    usage_active = exists.usage;
2459
                }
2460
                return _.extend(value, {'name': key, 'id': key, 
2461
                          'available': available,
2462
                          'available_active': available_active,
2463
                          'limit_active': limit_active,
2464
                          'usage_active': usage_active,
2465
                          'resource': snf.storage.resources.get(key)});
2466
            });
2467
            return filtered;
2468
        },
2469
        
2470
        get_by_id: function(k) {
2471
          return this.filter(function(q) { return q.get('name') == k})[0]
2472
        },
2473

    
2474
        get_available_for_vm: function(options) {
2475
          var quotas = synnefo.storage.quotas;
2476
          var key = 'available';
2477
          var available_quota = {};
2478
          _.each(['cyclades.ram', 'cyclades.cpu', 'cyclades.disk'], 
2479
            function (key) {
2480
              var value = quotas.get(key).get_available(true);
2481
              available_quota[key.replace('cyclades.', '')] = value;
2482
          });
2483
          return available_quota;
2484
        }
2485
    })
2486

    
2487
    models.Resource = models.Model.extend({
2488
        api_type: 'accounts',
2489
        path: 'resources'
2490
    });
2491

    
2492
    models.Resources = models.Collection.extend({
2493
        api_type: 'accounts',
2494
        path: 'resources',
2495
        model: models.Network,
2496

    
2497
        parse: function(resp) {
2498
            return _.map(resp, function(value, key) {
2499
                return _.extend(value, {'name': key, 'id': key});
2500
            })
2501
        }
2502
    });
2503
    
2504
    // storage initialization
2505
    snf.storage.images = new models.Images();
2506
    snf.storage.flavors = new models.Flavors();
2507
    snf.storage.vms = new models.VMS();
2508
    snf.storage.keys = new models.PublicKeys();
2509
    snf.storage.resources = new models.Resources();
2510
    snf.storage.quotas = new models.Quotas();
2511
    snf.storage.public_pools = new models.PublicPools();
2512

    
2513
})(this);