Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (79.1 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
        return baseurl + "/" + this.path;
58
    }
59

    
60
    var NIC_REGEX = /^nic-([0-9]+)-([0-9]+)$/
61
    
62
    // i18n
63
    BUILDING_MESSAGES = window.BUILDING_MESSAGES || {'INIT': 'init', 'COPY': '{0}, {1}, {2}', 'FINAL': 'final'};
64

    
65
    // Base object for all our models
66
    models.Model = bb.Model.extend({
67
        sync: snf.api.sync,
68
        api: snf.api,
69
        api_type: 'compute',
70
        has_status: false,
71

    
72
        initialize: function() {
73
            if (this.has_status) {
74
                this.bind("change:status", this.handle_remove);
75
                this.handle_remove();
76
            }
77
            
78
            this.api_call = _.bind(this.api.call, this);
79
            models.Model.__super__.initialize.apply(this, arguments);
80
        },
81

    
82
        handle_remove: function() {
83
            if (this.get("status") == 'DELETED') {
84
                if (this.collection) {
85
                    try { this.clear_pending_action();} catch (err) {};
86
                    try { this.reset_pending_actions();} catch (err) {};
87
                    try { this.stop_stats_update();} catch (err) {};
88
                    this.collection.remove(this.id);
89
                }
90
            }
91
        },
92
        
93
        // custom set method to allow submodels to use
94
        // set_<attr> methods for handling the value of each
95
        // attribute and overriding the default set method
96
        // for specific parameters
97
        set: function(params, options) {
98
            _.each(params, _.bind(function(value, key){
99
                if (this["set_" + key]) {
100
                    params[key] = this["set_" + key](value);
101
                }
102
            }, this))
103
            var ret = bb.Model.prototype.set.call(this, params, options);
104
            return ret;
105
        },
106

    
107
        url: function(options) {
108
            return getUrl.call(this, this.base_url) + "/" + this.id;
109
        },
110

    
111
        api_path: function(options) {
112
            return this.path + "/" + this.id;
113
        },
114

    
115
        parse: function(resp, xhr) {
116
        },
117

    
118
        remove: function(complete, error, success) {
119
            this.api_call(this.api_path(), "delete", undefined, complete, error, success);
120
        },
121

    
122
        changedKeys: function() {
123
            return _.keys(this.changedAttributes() || {});
124
        },
125
            
126
        // return list of changed attributes that included in passed list
127
        // argument
128
        getKeysChanged: function(keys) {
129
            return _.intersection(keys, this.changedKeys());
130
        },
131
        
132
        // boolean check of keys changed
133
        keysChanged: function(keys) {
134
            return this.getKeysChanged(keys).length > 0;
135
        },
136

    
137
        // check if any of the passed attribues has changed
138
        hasOnlyChange: function(keys) {
139
            var ret = false;
140
            _.each(keys, _.bind(function(key) {
141
                if (this.changedKeys().length == 1 && this.changedKeys().indexOf(key) > -1) { ret = true};
142
            }, this));
143
            return ret;
144
        }
145

    
146
    })
147
    
148
    // Base object for all our model collections
149
    models.Collection = bb.Collection.extend({
150
        sync: snf.api.sync,
151
        api: snf.api,
152
        api_type: 'compute',
153
        supportIncUpdates: true,
154

    
155
        initialize: function() {
156
            models.Collection.__super__.initialize.apply(this, arguments);
157
            this.api_call = _.bind(this.api.call, this);
158
        },
159

    
160
        url: function(options, method) {
161
            return getUrl.call(this, this.base_url) + (
162
                    options.details || this.details && method != 'create' ? '/detail' : '');
163
        },
164

    
165
        fetch: function(options) {
166
            if (!options) { options = {} };
167
            // default to update
168
            if (!this.noUpdate) {
169
                if (options.update === undefined) { options.update = true };
170
                if (!options.removeMissing && options.refresh) { options.removeMissing = true };
171
            } else {
172
                if (options.refresh === undefined) {
173
                    options.refresh = true;
174
                }
175
            }
176
            // custom event foreach fetch
177
            return bb.Collection.prototype.fetch.call(this, options)
178
        },
179

    
180
        create: function(model, options) {
181
            var coll = this;
182
            options || (options = {});
183
            model = this._prepareModel(model, options);
184
            if (!model) return false;
185
            var success = options.success;
186
            options.success = function(nextModel, resp, xhr) {
187
                if (success) success(nextModel, resp, xhr);
188
            };
189
            model.save(null, options);
190
            return model;
191
        },
192

    
193
        get_fetcher: function(interval, increase, fast, increase_after_calls, max, initial_call, params) {
194
            var fetch_params = params || {};
195
            var handler_options = {};
196

    
197
            fetch_params.skips_timeouts = true;
198
            handler_options.interval = interval;
199
            handler_options.increase = increase;
200
            handler_options.fast = fast;
201
            handler_options.increase_after_calls = increase_after_calls;
202
            handler_options.max= max;
203
            handler_options.id = "collection id";
204

    
205
            var last_ajax = undefined;
206
            var callback = _.bind(function() {
207
                // clone to avoid referenced objects
208
                var params = _.clone(fetch_params);
209
                updater._ajax = last_ajax;
210
                
211
                // wait for previous request to finish
212
                if (last_ajax && last_ajax.readyState < 4 && last_ajax.statusText != "timeout") {
213
                    // opera readystate for 304 responses is 0
214
                    if (!($.browser.opera && last_ajax.readyState == 0 && last_ajax.status == 304)) {
215
                        return;
216
                    }
217
                }
218
                
219
                last_ajax = this.fetch(params);
220
            }, this);
221
            handler_options.callback = callback;
222

    
223
            var updater = new snf.api.updateHandler(_.clone(_.extend(handler_options, fetch_params)));
224
            snf.api.bind("call", _.throttle(_.bind(function(){ updater.faster(true)}, this)), 1000);
225
            return updater;
226
        }
227
    });
228
    
229
    // Image model
230
    models.Image = models.Model.extend({
231
        path: 'images',
232
        
233
        get_size: function() {
234
            return parseInt(this.get('metadata') ? this.get('metadata').values.size : -1)
235
        },
236

    
237
        get_description: function(escape) {
238
            if (escape == undefined) { escape = true };
239
            if (escape) { return this.escape('description') || "No description available"}
240
            return this.get('description') || "No description available."
241
        },
242

    
243
        get_meta: function(key) {
244
            if (this.get('metadata') && this.get('metadata').values) {
245
                if (!this.get('metadata').values[key]) { return null }
246
                return _.escape(this.get('metadata').values[key]);
247
            } else {
248
                return null;
249
            }
250
        },
251

    
252
        get_meta_keys: function() {
253
            if (this.get('metadata') && this.get('metadata').values) {
254
                return _.keys(this.get('metadata').values);
255
            } else {
256
                return [];
257
            }
258
        },
259

    
260
        get_owner: function() {
261
            return this.get('owner') || _.keys(synnefo.config.system_images_owners)[0];
262
        },
263

    
264
        get_owner_uuid: function() {
265
            return this.get('owner_uuid');
266
        },
267

    
268
        is_system_image: function() {
269
          var owner = this.get_owner();
270
          return _.include(_.keys(synnefo.config.system_images_owners), owner)
271
        },
272

    
273
        owned_by: function(user) {
274
          if (!user) { user = synnefo.user }
275
          return user.username == this.get('owner_uuid');
276
        },
277

    
278
        display_owner: function() {
279
            var owner = this.get_owner();
280
            if (_.include(_.keys(synnefo.config.system_images_owners), owner)) {
281
                return synnefo.config.system_images_owners[owner];
282
            } else {
283
                return owner;
284
            }
285
        },
286
    
287
        get_readable_size: function() {
288
            if (this.is_deleted()) {
289
                return synnefo.config.image_deleted_size_title || '(none)';
290
            }
291
            return this.get_size() > 0 ? util.readablizeBytes(this.get_size() * 1024 * 1024) : '(none)';
292
        },
293

    
294
        get_os: function() {
295
            return this.get_meta('OS');
296
        },
297

    
298
        get_gui: function() {
299
            return this.get_meta('GUI');
300
        },
301

    
302
        get_created_users: function() {
303
            try {
304
              var users = this.get_meta('users').split(" ");
305
            } catch (err) { users = null }
306
            if (!users) { users = [synnefo.config.os_created_users[this.get_os()] || "root"]}
307
            return users;
308
        },
309

    
310
        get_sort_order: function() {
311
            return parseInt(this.get('metadata') ? this.get('metadata').values.sortorder : -1)
312
        },
313

    
314
        get_vm: function() {
315
            var vm_id = this.get("serverRef");
316
            var vm = undefined;
317
            vm = storage.vms.get(vm_id);
318
            return vm;
319
        },
320

    
321
        is_public: function() {
322
            return this.get('is_public') == undefined ? true : this.get('is_public');
323
        },
324

    
325
        is_deleted: function() {
326
            return this.get('status') == "DELETED"
327
        },
328
        
329
        ssh_keys_paths: function() {
330
            return _.map(this.get_created_users(), function(username) {
331
                prepend = '';
332
                if (username != 'root') {
333
                    prepend = '/home'
334
                }
335
                return {'user': username, 'path': '{1}/{0}/.ssh/authorized_keys'.format(username, 
336
                                                             prepend)};
337
            });
338
        },
339

    
340
        _supports_ssh: function() {
341
            if (synnefo.config.support_ssh_os_list.indexOf(this.get_os()) > -1) {
342
                return true;
343
            }
344
            if (this.get_meta('osfamily') == 'linux') {
345
              return true;
346
            }
347
            return false;
348
        },
349

    
350
        supports: function(feature) {
351
            if (feature == "ssh") {
352
                return this._supports_ssh()
353
            }
354
            return false;
355
        },
356

    
357
        personality_data_for_keys: function(keys) {
358
            return _.map(this.ssh_keys_paths(), function(pathinfo) {
359
                var contents = '';
360
                _.each(keys, function(key){
361
                    contents = contents + key.get("content") + "\n"
362
                });
363
                contents = $.base64.encode(contents);
364

    
365
                return {
366
                    path: pathinfo.path,
367
                    contents: contents,
368
                    mode: 0600,
369
                    owner: pathinfo.user,
370
                    group: pathinfo.user
371
                }
372
            });
373
        }
374
    });
375

    
376
    // Flavor model
377
    models.Flavor = models.Model.extend({
378
        path: 'flavors',
379

    
380
        details_string: function() {
381
            return "{0} CPU, {1}MB, {2}GB".format(this.get('cpu'), this.get('ram'), this.get('disk'));
382
        },
383

    
384
        get_disk_size: function() {
385
            return parseInt(this.get("disk") * 1000)
386
        },
387

    
388
        get_disk_template_info: function() {
389
            var info = snf.config.flavors_disk_templates_info[this.get("disk_template")];
390
            if (!info) {
391
                info = { name: this.get("disk_template"), description:'' };
392
            }
393
            return info
394
        }
395

    
396
    });
397
    
398
    models.ParamsList = function(){this.initialize.apply(this, arguments)};
399
    _.extend(models.ParamsList.prototype, bb.Events, {
400

    
401
        initialize: function(parent, param_name) {
402
            this.parent = parent;
403
            this.actions = {};
404
            this.param_name = param_name;
405
            this.length = 0;
406
        },
407
        
408
        has_action: function(action) {
409
            return this.actions[action] ? true : false;
410
        },
411
            
412
        _parse_params: function(arguments) {
413
            if (arguments.length <= 1) {
414
                return [];
415
            }
416

    
417
            var args = _.toArray(arguments);
418
            return args.splice(1);
419
        },
420

    
421
        contains: function(action, params) {
422
            params = this._parse_params(arguments);
423
            var has_action = this.has_action(action);
424
            if (!has_action) { return false };
425

    
426
            var paramsEqual = false;
427
            _.each(this.actions[action], function(action_params) {
428
                if (_.isEqual(action_params, params)) {
429
                    paramsEqual = true;
430
                }
431
            });
432
                
433
            return paramsEqual;
434
        },
435
        
436
        is_empty: function() {
437
            return _.isEmpty(this.actions);
438
        },
439

    
440
        add: function(action, params) {
441
            params = this._parse_params(arguments);
442
            if (this.contains.apply(this, arguments)) { return this };
443
            var isnew = false
444
            if (!this.has_action(action)) {
445
                this.actions[action] = [];
446
                isnew = true;
447
            };
448

    
449
            this.actions[action].push(params);
450
            this.parent.trigger("change:" + this.param_name, this.parent, this);
451
            if (isnew) {
452
                this.trigger("add", action, params);
453
            } else {
454
                this.trigger("change", action, params);
455
            }
456
            return this;
457
        },
458
        
459
        remove_all: function(action) {
460
            if (this.has_action(action)) {
461
                delete this.actions[action];
462
                this.parent.trigger("change:" + this.param_name, this.parent, this);
463
                this.trigger("remove", action);
464
            }
465
            return this;
466
        },
467

    
468
        reset: function() {
469
            this.actions = {};
470
            this.parent.trigger("change:" + this.param_name, this.parent, this);
471
            this.trigger("reset");
472
            this.trigger("remove");
473
        },
474

    
475
        remove: function(action, params) {
476
            params = this._parse_params(arguments);
477
            if (!this.has_action(action)) { return this };
478
            var index = -1;
479
            _.each(this.actions[action], _.bind(function(action_params) {
480
                if (_.isEqual(action_params, params)) {
481
                    index = this.actions[action].indexOf(action_params);
482
                }
483
            }, this));
484
            
485
            if (index > -1) {
486
                this.actions[action].splice(index, 1);
487
                if (_.isEmpty(this.actions[action])) {
488
                    delete this.actions[action];
489
                }
490
                this.parent.trigger("change:" + this.param_name, this.parent, this);
491
                this.trigger("remove", action, params);
492
            }
493
        }
494

    
495
    });
496

    
497
    // Image model
498
    models.Network = models.Model.extend({
499
        path: 'networks',
500
        has_status: true,
501
        defaults: {'connecting':0},
502
        
503
        initialize: function() {
504
            var ret = models.Network.__super__.initialize.apply(this, arguments);
505
            this.set({"actions": new models.ParamsList(this, "actions")});
506
            this.update_state();
507
            this.bind("change:nics", _.bind(synnefo.storage.nics.update_net_nics, synnefo.storage.nics));
508
            this.bind("change:status", _.bind(this.update_state, this));
509
            return ret;
510
        },
511
        
512
        is_deleted: function() {
513
          return this.get('status') == 'DELETED';
514
        },
515

    
516
        toJSON: function() {
517
            var attrs = _.clone(this.attributes);
518
            attrs.actions = _.clone(this.get("actions").actions);
519
            return attrs;
520
        },
521
        
522
        set_state: function(val) {
523
            if (val == "PENDING" && this.get("state") == "DESTORY") {
524
                return "DESTROY";
525
            }
526
            return val;
527
        },
528

    
529
        update_state: function() {
530
            if (this.get("connecting") > 0) {
531
                this.set({state: "CONNECTING"});
532
                return
533
            }
534
            
535
            if (this.get_nics(function(nic){ return nic.get("removing") == 1}).length > 0) {
536
                this.set({state: "DISCONNECTING"});
537
                return
538
            }   
539
            
540
            if (this.contains_firewalling_nics() > 0) {
541
                this.set({state: "FIREWALLING"});
542
                return
543
            }   
544
            
545
            if (this.get("state") == "DESTROY") { 
546
                this.set({"destroyed":1});
547
            }
548
            
549
            this.set({state:this.get('status')});
550
        },
551

    
552
        is_public: function() {
553
            return this.get("public");
554
        },
555

    
556
        decrease_connecting: function() {
557
            var conn = this.get("connecting");
558
            if (!conn) { conn = 0 };
559
            if (conn > 0) {
560
                conn--;
561
            }
562
            this.set({"connecting": conn});
563
            this.update_state();
564
        },
565

    
566
        increase_connecting: function() {
567
            var conn = this.get("connecting");
568
            if (!conn) { conn = 0 };
569
            conn++;
570
            this.set({"connecting": conn});
571
            this.update_state();
572
        },
573

    
574
        connected_to: function(vm) {
575
            return this.get('linked_to').indexOf(""+vm.id) > -1;
576
        },
577

    
578
        connected_with_nic_id: function(nic_id) {
579
            return _.keys(this.get('nics')).indexOf(nic_id) > -1;
580
        },
581

    
582
        get_nics: function(filter) {
583
            var nics = synnefo.storage.nics.filter(function(nic) {
584
                return nic.get('network_id') == this.id;
585
            }, this);
586

    
587
            if (filter) {
588
                return _.filter(nics, filter);
589
            }
590
            return nics;
591
        },
592

    
593
        contains_firewalling_nics: function() {
594
            return this.get_nics(function(n){return n.get('pending_firewall')}).length
595
        },
596

    
597
        call: function(action, params, success, error) {
598
            if (action == "destroy") {
599
                var previous_state = this.get('state');
600
                var previous_status = this.get('status');
601

    
602
                this.set({state:"DESTROY"});
603

    
604
                var _success = _.bind(function() {
605
                    if (success) { success() };
606
                }, this);
607
                var _error = _.bind(function() {
608
                    this.set({state: previous_state, status: previous_status})
609
                    if (error) { error() };
610
                }, this);
611

    
612
                this.remove(undefined, _error, _success);
613
            }
614
            
615
            if (action == "disconnect") {
616
                if (this.get("state") == "DESTROY") {
617
                    return;
618
                }
619
                
620
                _.each(params, _.bind(function(nic_id) {
621
                    var nic = snf.storage.nics.get(nic_id);
622
                    this.get("actions").remove("disconnect", nic_id);
623
                    if (nic) {
624
                        this.remove_nic(nic, success, error);
625
                    }
626
                }, this));
627
            }
628
        },
629

    
630
        add_vm: function (vm, callback, error, options) {
631
            var payload = {add:{serverRef:"" + vm.id}};
632
            payload._options = options || {};
633
            return this.api_call(this.api_path() + "/action", "create", 
634
                                 payload,
635
                                 undefined,
636
                                 error,
637
                                 _.bind(function(){
638
                                     //this.vms.add_pending(vm.id);
639
                                     this.increase_connecting();
640
                                     if (callback) {callback()}
641
                                 },this), error);
642
        },
643

    
644
        remove_nic: function (nic, callback, error, options) {
645
            var payload = {remove:{attachment:"" + nic.get("attachment_id")}};
646
            payload._options = options || {};
647
            return this.api_call(this.api_path() + "/action", "create", 
648
                                 payload,
649
                                 undefined,
650
                                 error,
651
                                 _.bind(function(){
652
                                     nic.set({"removing": 1});
653
                                     nic.get_network().update_state();
654
                                     //this.vms.add_pending_for_remove(vm.id);
655
                                     if (callback) {callback()}
656
                                 },this), error);
657
        },
658

    
659
        rename: function(name, callback) {
660
            return this.api_call(this.api_path(), "update", {
661
                network:{name:name}, 
662
                _options:{
663
                    critical: false, 
664
                    error_params:{
665
                        title: "Network action failed",
666
                        ns: "Networks",
667
                        extra_details: {"Network id": this.id}
668
                    }
669
                }}, callback);
670
        },
671

    
672
        get_connectable_vms: function() {
673
            return storage.vms.filter(function(vm){
674
                return !vm.in_error_state() && !vm.is_building();
675
            })
676
        },
677

    
678
        state_message: function() {
679
            if (this.get("state") == "ACTIVE" && !this.is_public()) {
680
                if (this.get("cidr") && this.get("dhcp") == true) {
681
                    return this.get("cidr");
682
                } else {
683
                    return "Private network";
684
                }
685
            }
686
            if (this.get("state") == "ACTIVE" && this.is_public()) {
687
                  return "Public network";
688
            }
689

    
690
            return models.Network.STATES[this.get("state")];
691
        },
692

    
693
        in_progress: function() {
694
            return models.Network.STATES_TRANSITIONS[this.get("state")] != undefined;
695
        },
696

    
697
        do_all_pending_actions: function(success, error) {
698
          var params, actions, action_params;
699
          actions = _.clone(this.get("actions").actions);
700
            _.each(actions, _.bind(function(params, action) {
701
                action_params = _.map(actions[action], function(a){ return _.clone(a)});
702
                _.each(action_params, _.bind(function(params) {
703
                    this.call(action, params, success, error);
704
                }, this));
705
            }, this));
706
            this.get("actions").reset();
707
        }
708
    });
709
    
710
    models.Network.STATES = {
711
        'ACTIVE': 'Private network',
712
        'CONNECTING': 'Connecting...',
713
        'DISCONNECTING': 'Disconnecting...',
714
        'FIREWALLING': 'Firewall update...',
715
        'DESTROY': 'Destroying...',
716
        'PENDING': 'Pending...',
717
        'ERROR': 'Error'
718
    }
719

    
720
    models.Network.STATES_TRANSITIONS = {
721
        'CONNECTING': ['ACTIVE'],
722
        'DISCONNECTING': ['ACTIVE'],
723
        'PENDING': ['ACTIVE'],
724
        'FIREWALLING': ['ACTIVE']
725
    }
726

    
727
    // Virtualmachine model
728
    models.VM = models.Model.extend({
729

    
730
        path: 'servers',
731
        has_status: true,
732
        initialize: function(params) {
733
            
734
            this.pending_firewalls = {};
735
            
736
            models.VM.__super__.initialize.apply(this, arguments);
737

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

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

    
770
            this.bind("change:nics", _.bind(synnefo.storage.nics.update_vm_nics, synnefo.storage.nics));
771
        },
772

    
773
        status: function(st) {
774
            if (!st) { return this.get("status")}
775
            return this.set({status:st});
776
        },
777

    
778
        set_status: function(st) {
779
            var new_state = this.state_for_api_status(st);
780
            var transition = false;
781

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

    
808
        has_diagnostics: function() {
809
            return this.get("diagnostics") && this.get("diagnostics").length;
810
        },
811

    
812
        get_progress_info: function() {
813
            // details about progress message
814
            // contains a list of diagnostic messages
815
            return this.get("status_messages");
816
        },
817

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

    
833
            var msg = messages[0];
834
            if (msg) {
835
              var message = msg.message;
836
              var message_tpl = snf.config.diagnostic_messages_tpls[msg.source];
837

    
838
              if (message_tpl) {
839
                  message = message_tpl.replace('MESSAGE', msg.message);
840
              }
841
              return message;
842
            }
843
            
844
            // no message to display, but vm in build state, display
845
            // finalizing message.
846
            if (this.is_building() == 'BUILD') {
847
                return synnefo.config.BUILDING_MESSAGES['FINAL'];
848
            }
849
            return null;
850
        },
851

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

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

    
913
            // copy finished display FINAL message or identify status message
914
            // from diagnostics.
915
            if (progress >= 100) {
916
                if (!this.has_diagnostics()) {
917
                        callback(BUILDING_MESSAGES['FINAL']);
918
                } else {
919
                        var d = this.get("diagnostics");
920
                        var msg = this.status_message_from_diagnostics(d);
921
                        if (msg) {
922
                              callback(msg);
923
                        }
924
                }
925
            }
926
        },
927

    
928
        get_copy_details: function(human, image, callback) {
929
            var human = human || false;
930
            var image = image || this.get_image(_.bind(function(image){
931
                var progress = this.get('progress');
932
                var size = image.get_size();
933
                var size_copied = (size * progress / 100).toFixed(2);
934
                
935
                if (human) {
936
                    size = util.readablizeBytes(size*1024*1024);
937
                    size_copied = util.readablizeBytes(size_copied*1024*1024);
938
                }
939

    
940
                callback({'progress': progress, 'size': size, 'copy': size_copied})
941
            }, this));
942
        },
943

    
944
        start_stats_update: function(force_if_empty) {
945
            var prev_state = this.do_update_stats;
946

    
947
            this.do_update_stats = true;
948
            
949
            // fetcher initialized ??
950
            if (!this.stats_fetcher) {
951
                this.init_stats_intervals();
952
            }
953

    
954

    
955
            // fetcher running ???
956
            if (!this.stats_fetcher.running || !prev_state) {
957
                this.stats_fetcher.start();
958
            }
959

    
960
            if (force_if_empty && this.get("stats") == undefined) {
961
                this.update_stats(true);
962
            }
963
        },
964

    
965
        stop_stats_update: function(stop_calls) {
966
            this.do_update_stats = false;
967

    
968
            if (stop_calls) {
969
                this.stats_fetcher.stop();
970
            }
971
        },
972

    
973
        // clear and reinitialize update interval
974
        init_stats_intervals: function (interval) {
975
            this.stats_fetcher = this.get_stats_fetcher(this.stats_update_interval);
976
            this.stats_fetcher.start();
977
        },
978
        
979
        get_stats_fetcher: function(timeout) {
980
            var cb = _.bind(function(data){
981
                this.update_stats();
982
            }, this);
983
            var fetcher = new snf.api.updateHandler({'callback': cb, interval: timeout, id:'stats'});
984
            return fetcher;
985
        },
986

    
987
        // do the api call
988
        update_stats: function(force) {
989
            // do not update stats if flag not set
990
            if ((!this.do_update_stats && !force) || this.updating_stats) {
991
                return;
992
            }
993

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

    
1011
        get_stats_image: function(stat, type) {
1012
        },
1013
        
1014
        _set_stats: function(stats) {
1015
            var silent = silent === undefined ? false : silent;
1016
            // unavailable stats while building
1017
            if (this.get("status") == "BUILD") { 
1018
                this.stats_available = false;
1019
            } else { this.stats_available = true; }
1020

    
1021
            if (this.get("status") == "DESTROY") { this.stats_available = false; }
1022
            
1023
            this.set({stats: stats}, {silent:true});
1024
            this.trigger("stats:update", stats);
1025
        },
1026

    
1027
        unbind: function() {
1028
            models.VM.__super__.unbind.apply(this, arguments);
1029
        },
1030

    
1031
        handle_stats_error: function() {
1032
            stats = {};
1033
            _.each(['cpuBar', 'cpuTimeSeries', 'netBar', 'netTimeSeries'], function(k) {
1034
                stats[k] = false;
1035
            });
1036

    
1037
            this.set({'stats': stats});
1038
        },
1039

    
1040
        // this method gets executed after a successful vm stats api call
1041
        handle_stats_update: function(data) {
1042
            var self = this;
1043
            // avoid browser caching
1044
            
1045
            if (data.stats && _.size(data.stats) > 0) {
1046
                var ts = $.now();
1047
                var stats = data.stats;
1048
                var images_loaded = 0;
1049
                var images = {};
1050

    
1051
                function check_images_loaded() {
1052
                    images_loaded++;
1053

    
1054
                    if (images_loaded == 4) {
1055
                        self._set_stats(images);
1056
                    }
1057
                }
1058
                _.each(['cpuBar', 'cpuTimeSeries', 'netBar', 'netTimeSeries'], function(k) {
1059
                    
1060
                    stats[k] = stats[k] + "?_=" + ts;
1061
                    
1062
                    var stat = k.slice(0,3);
1063
                    var type = k.slice(3,6) == "Bar" ? "bar" : "time";
1064
                    var img = $("<img />");
1065
                    var val = stats[k];
1066
                    
1067
                    // load stat image to a temporary dom element
1068
                    // update model stats on image load/error events
1069
                    img.load(function() {
1070
                        images[k] = val;
1071
                        check_images_loaded();
1072
                    });
1073

    
1074
                    img.error(function() {
1075
                        images[stat + type] = false;
1076
                        check_images_loaded();
1077
                    });
1078

    
1079
                    img.attr({'src': stats[k]});
1080
                })
1081
                data.stats = stats;
1082
            }
1083

    
1084
            // do we need to change the interval ??
1085
            if (data.stats.refresh * 1000 != this.stats_update_interval) {
1086
                this.stats_update_interval = data.stats.refresh * 1000;
1087
                this.stats_fetcher.interval = this.stats_update_interval;
1088
                this.stats_fetcher.maximum_interval = this.stats_update_interval;
1089
                this.stats_fetcher.stop();
1090
                this.stats_fetcher.start(false);
1091
            }
1092
        },
1093

    
1094
        // helper method that sets the do_update_stats
1095
        // in the future this method could also make an api call
1096
        // immediaetly if needed
1097
        enable_stats_update: function() {
1098
            this.do_update_stats = true;
1099
        },
1100
        
1101
        handle_destroy: function() {
1102
            this.stats_fetcher.stop();
1103
        },
1104

    
1105
        require_reboot: function() {
1106
            if (this.is_active()) {
1107
                this.set({'reboot_required': true});
1108
            }
1109
        },
1110
        
1111
        set_pending_action: function(data) {
1112
            this.pending_action = data;
1113
            return data;
1114
        },
1115

    
1116
        // machine has pending action
1117
        update_pending_action: function(action, force) {
1118
            this.set({pending_action: action});
1119
        },
1120

    
1121
        clear_pending_action: function() {
1122
            this.set({pending_action: undefined});
1123
        },
1124

    
1125
        has_pending_action: function() {
1126
            return this.get("pending_action") ? this.get("pending_action") : false;
1127
        },
1128
        
1129
        // machine is active
1130
        is_active: function() {
1131
            return models.VM.ACTIVE_STATES.indexOf(this.state()) > -1;
1132
        },
1133
        
1134
        // machine is building 
1135
        is_building: function() {
1136
            return models.VM.BUILDING_STATES.indexOf(this.state()) > -1;
1137
        },
1138
        
1139
        in_error_state: function() {
1140
            return this.state() === "ERROR"
1141
        },
1142

    
1143
        // user can connect to machine
1144
        is_connectable: function() {
1145
            // check if ips exist
1146
            if (!this.get_addresses().ip4 && !this.get_addresses().ip6) {
1147
                return false;
1148
            }
1149
            return models.VM.CONNECT_STATES.indexOf(this.state()) > -1;
1150
        },
1151
        
1152
        remove_meta: function(key, complete, error) {
1153
            var url = this.api_path() + "/meta/" + key;
1154
            this.api_call(url, "delete", undefined, complete, error);
1155
        },
1156

    
1157
        save_meta: function(meta, complete, error) {
1158
            var url = this.api_path() + "/meta/" + meta.key;
1159
            var payload = {meta:{}};
1160
            payload.meta[meta.key] = meta.value;
1161
            payload._options = {
1162
                critical:false, 
1163
                error_params: {
1164
                    title: "Machine metadata error",
1165
                    extra_details: {"Machine id": this.id}
1166
            }};
1167

    
1168
            this.api_call(url, "update", payload, complete, error);
1169
        },
1170

    
1171

    
1172
        // update/get the state of the machine
1173
        state: function() {
1174
            var args = slice.call(arguments);
1175
                
1176
            // TODO: it might not be a good idea to set the state in set_state method
1177
            if (args.length > 0 && models.VM.STATES.indexOf(args[0]) > -1) {
1178
                this.set({'state': args[0]});
1179
            }
1180

    
1181
            return this.get('state');
1182
        },
1183
        
1184
        // get the state that the api status corresponds to
1185
        state_for_api_status: function(status) {
1186
            return this.state_transition(this.state(), status);
1187
        },
1188
        
1189
        // vm state equals vm api status
1190
        state_is_status: function(state) {
1191
            return models.VM.STATUSES.indexOf(state) != -1;
1192
        },
1193
        
1194
        // get transition state for the corresponging api status
1195
        state_transition: function(state, new_status) {
1196
            var statuses = models.VM.STATES_TRANSITIONS[state];
1197
            if (statuses) {
1198
                if (statuses.indexOf(new_status) > -1) {
1199
                    return new_status;
1200
                } else {
1201
                    return state;
1202
                }
1203
            } else {
1204
                return new_status;
1205
            }
1206
        },
1207
        
1208
        // the current vm state is a transition state
1209
        in_transition: function() {
1210
            return models.VM.TRANSITION_STATES.indexOf(this.state()) > -1 || 
1211
                models.VM.TRANSITION_STATES.indexOf(this.get('status')) > -1;
1212
        },
1213
        
1214
        // get image object
1215
        get_image: function(callback) {
1216
            if (callback == undefined) { callback = function(){} }
1217
            var image = storage.images.get(this.get('imageRef'));
1218
            if (!image) {
1219
                storage.images.update_unknown_id(this.get('imageRef'), callback);
1220
                return;
1221
            }
1222
            callback(image);
1223
            return image;
1224
        },
1225
        
1226
        // get flavor object
1227
        get_flavor: function() {
1228
            var flv = storage.flavors.get(this.get('flavorRef'));
1229
            if (!flv) {
1230
                storage.flavors.update_unknown_id(this.get('flavorRef'));
1231
                flv = storage.flavors.get(this.get('flavorRef'));
1232
            }
1233
            return flv;
1234
        },
1235

    
1236
        get_meta: function(key, deflt) {
1237
            if (this.get('metadata') && this.get('metadata').values) {
1238
                if (!this.get('metadata').values[key]) { return deflt }
1239
                return _.escape(this.get('metadata').values[key]);
1240
            } else {
1241
                return deflt;
1242
            }
1243
        },
1244

    
1245
        get_meta_keys: function() {
1246
            if (this.get('metadata') && this.get('metadata').values) {
1247
                return _.keys(this.get('metadata').values);
1248
            } else {
1249
                return [];
1250
            }
1251
        },
1252
        
1253
        // get metadata OS value
1254
        get_os: function() {
1255
            var image = this.get_image();
1256
            return this.get_meta('OS') || (image ? 
1257
                                            image.get_os() || "okeanos" : "okeanos");
1258
        },
1259

    
1260
        get_gui: function() {
1261
            return this.get_meta('GUI');
1262
        },
1263
        
1264
        connected_to: function(net) {
1265
            return this.get('linked_to').indexOf(net.id) > -1;
1266
        },
1267

    
1268
        connected_with_nic_id: function(nic_id) {
1269
            return _.keys(this.get('nics')).indexOf(nic_id) > -1;
1270
        },
1271

    
1272
        get_nics: function(filter) {
1273
            ret = synnefo.storage.nics.filter(function(nic) {
1274
                return parseInt(nic.get('vm_id')) == this.id;
1275
            }, this);
1276

    
1277
            if (filter) {
1278
                return _.filter(ret, filter);
1279
            }
1280

    
1281
            return ret;
1282
        },
1283

    
1284
        get_net_nics: function(net_id) {
1285
            return this.get_nics(function(n){return n.get('network_id') == net_id});
1286
        },
1287

    
1288
        get_public_nic: function() {
1289
            return this.get_nics(function(n){ return n.get_network().is_public() === true })[0];
1290
        },
1291

    
1292
        get_hostname: function() {
1293
          var hostname = this.get_meta('hostname');
1294
          if (!hostname) {
1295
            if (synnefo.config.vm_hostname_format) {
1296
              hostname = synnefo.config.vm_hostname_format.format(this.id);
1297
            } else {
1298
              hostname = this.get_public_nic().get('ipv4');
1299
            }
1300
          }
1301
          return hostname;
1302
        },
1303

    
1304
        get_nic: function(net_id) {
1305
        },
1306

    
1307
        has_firewall: function() {
1308
            var nic = this.get_public_nic();
1309
            if (nic) {
1310
                var profile = nic.get('firewallProfile'); 
1311
                return ['ENABLED', 'PROTECTED'].indexOf(profile) > -1;
1312
            }
1313
            return false;
1314
        },
1315

    
1316
        get_firewall_profile: function() {
1317
            var nic = this.get_public_nic();
1318
            if (nic) {
1319
                return nic.get('firewallProfile');
1320
            }
1321
            return null;
1322
        },
1323

    
1324
        get_addresses: function() {
1325
            var pnic = this.get_public_nic();
1326
            if (!pnic) { return {'ip4': undefined, 'ip6': undefined }};
1327
            return {'ip4': pnic.get('ipv4'), 'ip6': pnic.get('ipv6')};
1328
        },
1329
    
1330
        // get actions that the user can execute
1331
        // depending on the vm state/status
1332
        get_available_actions: function() {
1333
            return models.VM.AVAILABLE_ACTIONS[this.state()];
1334
        },
1335

    
1336
        set_profile: function(profile, net_id) {
1337
        },
1338
        
1339
        // call rename api
1340
        rename: function(new_name) {
1341
            //this.set({'name': new_name});
1342
            this.sync("update", this, {
1343
                critical: true,
1344
                data: {
1345
                    'server': {
1346
                        'name': new_name
1347
                    }
1348
                }, 
1349
                // do the rename after the method succeeds
1350
                success: _.bind(function(){
1351
                    //this.set({name: new_name});
1352
                    snf.api.trigger("call");
1353
                }, this)
1354
            });
1355
        },
1356
        
1357
        get_console_url: function(data) {
1358
            var url_params = {
1359
                machine: this.get("name"),
1360
                host_ip: this.get_addresses().ip4,
1361
                host_ip_v6: this.get_addresses().ip6,
1362
                host: data.host,
1363
                port: data.port,
1364
                password: data.password
1365
            }
1366
            return '/machines/console?' + $.param(url_params);
1367
        },
1368

    
1369
        // action helper
1370
        call: function(action_name, success, error, params) {
1371
            var id_param = [this.id];
1372
            
1373
            params = params || {};
1374
            success = success || function() {};
1375
            error = error || function() {};
1376

    
1377
            var self = this;
1378

    
1379
            switch(action_name) {
1380
                case 'start':
1381
                    this.__make_api_call(this.get_action_url(), // vm actions url
1382
                                         "create", // create so that sync later uses POST to make the call
1383
                                         {start:{}}, // payload
1384
                                         function() {
1385
                                             // set state after successful call
1386
                                             self.state("START"); 
1387
                                             success.apply(this, arguments);
1388
                                             snf.api.trigger("call");
1389
                                         },  
1390
                                         error, 'start', params);
1391
                    break;
1392
                case 'reboot':
1393
                    this.__make_api_call(this.get_action_url(), // vm actions url
1394
                                         "create", // create so that sync later uses POST to make the call
1395
                                         {reboot:{type:"HARD"}}, // payload
1396
                                         function() {
1397
                                             // set state after successful call
1398
                                             self.state("REBOOT"); 
1399
                                             success.apply(this, arguments)
1400
                                             snf.api.trigger("call");
1401
                                             self.set({'reboot_required': false});
1402
                                         },
1403
                                         error, 'reboot', params);
1404
                    break;
1405
                case 'shutdown':
1406
                    this.__make_api_call(this.get_action_url(), // vm actions url
1407
                                         "create", // create so that sync later uses POST to make the call
1408
                                         {shutdown:{}}, // payload
1409
                                         function() {
1410
                                             // set state after successful call
1411
                                             self.state("SHUTDOWN"); 
1412
                                             success.apply(this, arguments)
1413
                                             snf.api.trigger("call");
1414
                                         },  
1415
                                         error, 'shutdown', params);
1416
                    break;
1417
                case 'console':
1418
                    this.__make_api_call(this.url() + "/action", "create", {'console': {'type':'vnc'}}, function(data) {
1419
                        var cons_data = data.console;
1420
                        success.apply(this, [cons_data]);
1421
                    }, undefined, 'console', params)
1422
                    break;
1423
                case 'destroy':
1424
                    this.__make_api_call(this.url(), // vm actions url
1425
                                         "delete", // create so that sync later uses POST to make the call
1426
                                         undefined, // payload
1427
                                         function() {
1428
                                             // set state after successful call
1429
                                             self.state('DESTROY');
1430
                                             success.apply(this, arguments)
1431
                                         },  
1432
                                         error, 'destroy', params);
1433
                    break;
1434
                default:
1435
                    throw "Invalid VM action ("+action_name+")";
1436
            }
1437
        },
1438
        
1439
        __make_api_call: function(url, method, data, success, error, action, extra_params) {
1440
            var self = this;
1441
            error = error || function(){};
1442
            success = success || function(){};
1443

    
1444
            var params = {
1445
                url: url,
1446
                data: data,
1447
                success: function(){ self.handle_action_succeed.apply(self, arguments); success.apply(this, arguments)},
1448
                error: function(){ self.handle_action_fail.apply(self, arguments); error.apply(this, arguments)},
1449
                error_params: { ns: "Machines actions", 
1450
                                title: "'" + this.get("name") + "'" + " " + action + " failed", 
1451
                                extra_details: { 'Machine ID': this.id, 'URL': url, 'Action': action || "undefined" },
1452
                                allow_reload: false
1453
                              },
1454
                display: false,
1455
                critical: false
1456
            }
1457
            _.extend(params, extra_params)
1458
            this.sync(method, this, params);
1459
        },
1460

    
1461
        handle_action_succeed: function() {
1462
            this.trigger("action:success", arguments);
1463
        },
1464
        
1465
        reset_action_error: function() {
1466
            this.action_error = false;
1467
            this.trigger("action:fail:reset", this.action_error);
1468
        },
1469

    
1470
        handle_action_fail: function() {
1471
            this.action_error = arguments;
1472
            this.trigger("action:fail", arguments);
1473
        },
1474

    
1475
        get_action_url: function(name) {
1476
            return this.url() + "/action";
1477
        },
1478

    
1479
        get_diagnostics_url: function() {
1480
            return this.url() + "/diagnostics";
1481
        },
1482

    
1483
        get_connection_info: function(host_os, success, error) {
1484
            var url = "/machines/connect";
1485
            params = {
1486
                ip_address: this.get_public_nic().get('ipv4'),
1487
                hostname: this.get_hostname(),
1488
                os: this.get_os(),
1489
                host_os: host_os,
1490
                srv: this.id
1491
            }
1492

    
1493
            url = url + "?" + $.param(params);
1494

    
1495
            var ajax = snf.api.sync("read", undefined, { url: url, 
1496
                                                         error:error, 
1497
                                                         success:success, 
1498
                                                         handles_error:1});
1499
        }
1500
    })
1501
    
1502
    models.VM.ACTIONS = [
1503
        'start',
1504
        'shutdown',
1505
        'reboot',
1506
        'console',
1507
        'destroy'
1508
    ]
1509

    
1510
    models.VM.AVAILABLE_ACTIONS = {
1511
        'UNKNWON'       : ['destroy'],
1512
        'BUILD'         : ['destroy'],
1513
        'REBOOT'        : ['shutdown', 'destroy', 'console'],
1514
        'STOPPED'       : ['start', 'destroy'],
1515
        'ACTIVE'        : ['shutdown', 'destroy', 'reboot', 'console'],
1516
        'ERROR'         : ['destroy'],
1517
        'DELETED'        : [],
1518
        'DESTROY'       : [],
1519
        'BUILD_INIT'    : ['destroy'],
1520
        'BUILD_COPY'    : ['destroy'],
1521
        'BUILD_FINAL'   : ['destroy'],
1522
        'SHUTDOWN'      : ['destroy'],
1523
        'START'         : [],
1524
        'CONNECT'       : [],
1525
        'DISCONNECT'    : []
1526
    }
1527

    
1528
    // api status values
1529
    models.VM.STATUSES = [
1530
        'UNKNWON',
1531
        'BUILD',
1532
        'REBOOT',
1533
        'STOPPED',
1534
        'ACTIVE',
1535
        'ERROR',
1536
        'DELETED'
1537
    ]
1538

    
1539
    // api status values
1540
    models.VM.CONNECT_STATES = [
1541
        'ACTIVE',
1542
        'REBOOT',
1543
        'SHUTDOWN'
1544
    ]
1545

    
1546
    // vm states
1547
    models.VM.STATES = models.VM.STATUSES.concat([
1548
        'DESTROY',
1549
        'BUILD_INIT',
1550
        'BUILD_COPY',
1551
        'BUILD_FINAL',
1552
        'SHUTDOWN',
1553
        'START',
1554
        'CONNECT',
1555
        'DISCONNECT',
1556
        'FIREWALL'
1557
    ]);
1558
    
1559
    models.VM.STATES_TRANSITIONS = {
1560
        'DESTROY' : ['DELETED'],
1561
        'SHUTDOWN': ['ERROR', 'STOPPED', 'DESTROY'],
1562
        'STOPPED': ['ERROR', 'ACTIVE', 'DESTROY'],
1563
        'ACTIVE': ['ERROR', 'STOPPED', 'REBOOT', 'SHUTDOWN', 'DESTROY'],
1564
        'START': ['ERROR', 'ACTIVE', 'DESTROY'],
1565
        'REBOOT': ['ERROR', 'ACTIVE', 'STOPPED', 'DESTROY'],
1566
        'BUILD': ['ERROR', 'ACTIVE', 'DESTROY'],
1567
        'BUILD_COPY': ['ERROR', 'ACTIVE', 'BUILD_FINAL', 'DESTROY'],
1568
        'BUILD_FINAL': ['ERROR', 'ACTIVE', 'DESTROY'],
1569
        'BUILD_INIT': ['ERROR', 'ACTIVE', 'BUILD_COPY', 'BUILD_FINAL', 'DESTROY']
1570
    }
1571

    
1572
    models.VM.TRANSITION_STATES = [
1573
        'DESTROY',
1574
        'SHUTDOWN',
1575
        'START',
1576
        'REBOOT',
1577
        'BUILD'
1578
    ]
1579

    
1580
    models.VM.ACTIVE_STATES = [
1581
        'BUILD', 'REBOOT', 'ACTIVE',
1582
        'BUILD_INIT', 'BUILD_COPY', 'BUILD_FINAL',
1583
        'SHUTDOWN', 'CONNECT', 'DISCONNECT'
1584
    ]
1585

    
1586
    models.VM.BUILDING_STATES = [
1587
        'BUILD', 'BUILD_INIT', 'BUILD_COPY', 'BUILD_FINAL'
1588
    ]
1589

    
1590
    models.Networks = models.Collection.extend({
1591
        model: models.Network,
1592
        path: 'networks',
1593
        details: true,
1594
        //noUpdate: true,
1595
        defaults: {'nics':[],'linked_to':[]},
1596
        
1597
        parse: function (resp, xhr) {
1598
            // FIXME: depricated global var
1599
            if (!resp) { return []};
1600
            var data = _.filter(_.map(resp.networks.values, _.bind(this.parse_net_api_data, this)),
1601
                               function(e){ return e });
1602
            return data;
1603
        },
1604

    
1605
        add: function() {
1606
            ret = models.Networks.__super__.add.apply(this, arguments);
1607
            // update nics after each network addition
1608
            ret.each(function(r){
1609
                synnefo.storage.nics.update_net_nics(r);
1610
            });
1611
        },
1612

    
1613
        reset_pending_actions: function() {
1614
            this.each(function(net) {
1615
                net.get("actions").reset();
1616
            });
1617
        },
1618

    
1619
        do_all_pending_actions: function() {
1620
            this.each(function(net) {
1621
                net.do_all_pending_actions();
1622
            })
1623
        },
1624

    
1625
        parse_net_api_data: function(data) {
1626
            // append nic metadata
1627
            // net.get('nics') contains a list of vm/index objects 
1628
            // e.g. {'vm_id':12231, 'index':1}
1629
            // net.get('linked_to') contains a list of vms the network is 
1630
            // connected to e.g. [1001, 1002]
1631
            if (data.attachments && data.attachments.values) {
1632
                data['nics'] = {};
1633
                data['linked_to'] = [];
1634
                _.each(data.attachments.values, function(nic_id){
1635
                  
1636
                  var vm_id = NIC_REGEX.exec(nic_id)[1];
1637
                  var nic_index = parseInt(NIC_REGEX.exec(nic_id)[2]);
1638

    
1639
                  if (vm_id !== undefined && nic_index !== undefined) {
1640
                      data['nics'][nic_id] = {
1641
                          'vm_id': vm_id, 
1642
                          'index': nic_index, 
1643
                          'id': nic_id
1644
                      };
1645
                      if (data['linked_to'].indexOf(vm_id) == -1) {
1646
                        data['linked_to'].push(vm_id);
1647
                      }
1648
                  }
1649
                });
1650
            }
1651

    
1652
            if (data.status == "DELETED" && !this.get(parseInt(data.id))) {
1653
              return false;
1654
            }
1655
            return data;
1656
        },
1657

    
1658
        create: function (name, type, cidr, dhcp, callback) {
1659
            var params = {
1660
                network:{
1661
                    name:name
1662
                }
1663
            };
1664

    
1665
            if (type) {
1666
                params.network.type = type;
1667
            }
1668
            if (cidr) {
1669
                params.network.cidr = cidr;
1670
            }
1671
            if (dhcp) {
1672
                params.network.dhcp = dhcp;
1673
            }
1674

    
1675
            if (dhcp === false) {
1676
                params.network.dhcp = false;
1677
            }
1678
            
1679
            return this.api_call(this.path, "create", params, callback);
1680
        },
1681

    
1682
        get_public: function(){
1683
          return this.filter(function(n){return n.get('public')});
1684
        }
1685
    })
1686

    
1687
    models.Images = models.Collection.extend({
1688
        model: models.Image,
1689
        path: 'images',
1690
        details: true,
1691
        noUpdate: true,
1692
        supportIncUpdates: false,
1693
        meta_keys_as_attrs: ["OS", "description", "kernel", "size", "GUI"],
1694
        meta_labels: {},
1695
        read_method: 'read',
1696

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

    
1742
        _read_image_from_request: function(image, msg, xhr) {
1743
            return image.image;
1744
        },
1745

    
1746
        parse: function (resp, xhr) {
1747
            var parsed = _.map(resp.images.values, _.bind(this.parse_meta, this));
1748
            parsed = this.fill_owners(parsed);
1749
            return parsed;
1750
        },
1751

    
1752
        fill_owners: function(images) {
1753
            // do translate uuid->displayname if needed
1754
            // store display name in owner attribute for compatibility
1755
            var uuids = [];
1756

    
1757
            var images = _.map(images, function(img, index) {
1758
                if (synnefo.config.translate_uuids) {
1759
                    uuids.push(img['owner']);
1760
                }
1761
                img['owner_uuid'] = img['owner'];
1762
                return img;
1763
            });
1764
            
1765
            if (uuids.length > 0) {
1766
                var handle_results = function(data) {
1767
                    _.each(images, function (img) {
1768
                        img['owner'] = data.uuid_catalog[img['owner_uuid']];
1769
                    });
1770
                }
1771
                // notice the async false
1772
                var uuid_map = this.translate_uuids(uuids, false, 
1773
                                                    handle_results)
1774
            }
1775
            return images;
1776
        },
1777

    
1778
        translate_uuids: function(uuids, async, cb) {
1779
            var url = synnefo.config.user_catalog_url;
1780
            var data = JSON.stringify({'uuids': uuids});
1781
          
1782
            // post to user_catalogs api
1783
            snf.api.sync('create', undefined, {
1784
                url: url,
1785
                data: data,
1786
                async: async,
1787
                success:  cb
1788
            });
1789
        },
1790

    
1791
        get_meta_key: function(img, key) {
1792
            if (img.metadata && img.metadata.values && img.metadata.values[key]) {
1793
                return _.escape(img.metadata.values[key]);
1794
            }
1795
            return undefined;
1796
        },
1797

    
1798
        comparator: function(img) {
1799
            return -img.get_sort_order("sortorder") || 1000 * img.id;
1800
        },
1801

    
1802
        parse_meta: function(img) {
1803
            _.each(this.meta_keys_as_attrs, _.bind(function(key){
1804
                if (img[key]) { return };
1805
                img[key] = this.get_meta_key(img, key) || "";
1806
            }, this));
1807
            return img;
1808
        },
1809

    
1810
        active: function() {
1811
            return this.filter(function(img){return img.get('status') != "DELETED"});
1812
        },
1813

    
1814
        predefined: function() {
1815
            return _.filter(this.active(), function(i) { return !i.get("serverRef")});
1816
        },
1817
        
1818
        fetch_for_type: function(type, complete, error) {
1819
            this.fetch({update:true, 
1820
                        success: complete, 
1821
                        error: error, 
1822
                        skip_api_error: true });
1823
        },
1824
        
1825
        get_images_for_type: function(type) {
1826
            if (this['get_{0}_images'.format(type)]) {
1827
                return this['get_{0}_images'.format(type)]();
1828
            }
1829

    
1830
            return this.active();
1831
        },
1832

    
1833
        update_images_for_type: function(type, onStart, onComplete, onError, force_load) {
1834
            var load = false;
1835
            error = onError || function() {};
1836
            function complete(collection) { 
1837
                onComplete(collection.get_images_for_type(type)); 
1838
            }
1839
            
1840
            // do we need to fetch/update current collection entries
1841
            if (load) {
1842
                onStart();
1843
                this.fetch_for_type(type, complete, error);
1844
            } else {
1845
                // fallback to complete
1846
                complete(this);
1847
            }
1848
        }
1849
    })
1850

    
1851
    models.Flavors = models.Collection.extend({
1852
        model: models.Flavor,
1853
        path: 'flavors',
1854
        details: true,
1855
        noUpdate: true,
1856
        supportIncUpdates: false,
1857
        // update collection model with id passed
1858
        // making a direct call to the flavor
1859
        // api url
1860
        update_unknown_id: function(id, callback) {
1861
            var url = getUrl.call(this) + "/" + id;
1862
            this.api_call(this.path + "/" + id, "read", {_options:{async:false, skip_api_error:true}}, undefined, 
1863
            _.bind(function() {
1864
                this.add({id:id, cpu:"Unknown", ram:"Unknown", disk:"Unknown", name: "Unknown", status:"DELETED"})
1865
            }, this), _.bind(function(flv) {
1866
                if (!flv.flavor.status) { flv.flavor.status = "DELETED" };
1867
                this.add(flv.flavor);
1868
            }, this));
1869
        },
1870

    
1871
        parse: function (resp, xhr) {
1872
            return _.map(resp.flavors.values, function(o) { o.disk_template = o['SNF:disk_template']; return o});
1873
        },
1874

    
1875
        comparator: function(flv) {
1876
            return flv.get("disk") * flv.get("cpu") * flv.get("ram");
1877
        },
1878

    
1879
        unavailable_values_for_image: function(img, flavors) {
1880
            var flavors = flavors || this.active();
1881
            var size = img.get_size();
1882
            
1883
            var index = {cpu:[], disk:[], ram:[]};
1884

    
1885
            _.each(this.active(), function(el) {
1886
                var img_size = size;
1887
                var flv_size = el.get_disk_size();
1888
                if (flv_size < img_size) {
1889
                    if (index.disk.indexOf(flv_size) == -1) {
1890
                        index.disk.push(flv_size);
1891
                    }
1892
                };
1893
            });
1894
            
1895
            return index;
1896
        },
1897

    
1898
        get_flavor: function(cpu, mem, disk, disk_template, filter_list) {
1899
            if (!filter_list) { filter_list = this.models };
1900
            
1901
            return this.select(function(flv){
1902
                if (flv.get("cpu") == cpu + "" &&
1903
                   flv.get("ram") == mem + "" &&
1904
                   flv.get("disk") == disk + "" &&
1905
                   flv.get("disk_template") == disk_template &&
1906
                   filter_list.indexOf(flv) > -1) { return true; }
1907
            })[0];
1908
        },
1909
        
1910
        get_data: function(lst) {
1911
            var data = {'cpu': [], 'mem':[], 'disk':[]};
1912

    
1913
            _.each(lst, function(flv) {
1914
                if (data.cpu.indexOf(flv.get("cpu")) == -1) {
1915
                    data.cpu.push(flv.get("cpu"));
1916
                }
1917
                if (data.mem.indexOf(flv.get("ram")) == -1) {
1918
                    data.mem.push(flv.get("ram"));
1919
                }
1920
                if (data.disk.indexOf(flv.get("disk")) == -1) {
1921
                    data.disk.push(flv.get("disk"));
1922
                }
1923
            })
1924
            
1925
            return data;
1926
        },
1927

    
1928
        active: function() {
1929
            return this.filter(function(flv){return flv.get('status') != "DELETED"});
1930
        }
1931
            
1932
    })
1933

    
1934
    models.VMS = models.Collection.extend({
1935
        model: models.VM,
1936
        path: 'servers',
1937
        details: true,
1938
        copy_image_meta: true,
1939

    
1940
        parse: function (resp, xhr) {
1941
            var data = resp;
1942
            if (!resp) { return [] };
1943
            data = _.filter(_.map(resp.servers.values, _.bind(this.parse_vm_api_data, this)), function(v){return v});
1944
            return data;
1945
        },
1946

    
1947
        parse_vm_api_data: function(data) {
1948
            // do not add non existing DELETED entries
1949
            if (data.status && data.status == "DELETED") {
1950
                if (!this.get(data.id)) {
1951
                    return false;
1952
                }
1953
            }
1954

    
1955
            // OS attribute
1956
            if (this.has_meta(data)) {
1957
                data['OS'] = data.metadata.values.OS || "unknown";
1958
            }
1959
            
1960
            if (!data.diagnostics) {
1961
                data.diagnostics = [];
1962
            }
1963

    
1964
            // network metadata
1965
            data['firewalls'] = {};
1966
            data['nics'] = {};
1967
            data['linked_to'] = [];
1968

    
1969
            if (data['attachments'] && data['attachments'].values) {
1970
                var nics = data['attachments'].values;
1971
                _.each(nics, function(nic) {
1972
                    var net_id = nic.network_id;
1973
                    var index = parseInt(NIC_REGEX.exec(nic.id)[2]);
1974
                    if (data['linked_to'].indexOf(net_id) == -1) {
1975
                        data['linked_to'].push(net_id);
1976
                    }
1977

    
1978
                    data['nics'][nic.id] = nic;
1979
                })
1980
            }
1981
            
1982
            // if vm has no metadata, no metadata object
1983
            // is in json response, reset it to force
1984
            // value update
1985
            if (!data['metadata']) {
1986
                data['metadata'] = {values:{}};
1987
            }
1988

    
1989
            return data;
1990
        },
1991

    
1992
        add: function() {
1993
            ret = models.VMS.__super__.add.apply(this, arguments);
1994
            ret.each(function(r){
1995
                synnefo.storage.nics.update_vm_nics(r);
1996
            });
1997
        },
1998
        
1999
        get_reboot_required: function() {
2000
            return this.filter(function(vm){return vm.get("reboot_required") == true})
2001
        },
2002

    
2003
        has_pending_actions: function() {
2004
            return this.filter(function(vm){return vm.pending_action}).length > 0;
2005
        },
2006

    
2007
        reset_pending_actions: function() {
2008
            this.each(function(vm) {
2009
                vm.clear_pending_action();
2010
            })
2011
        },
2012

    
2013
        do_all_pending_actions: function(success, error) {
2014
            this.each(function(vm) {
2015
                if (vm.has_pending_action()) {
2016
                    vm.call(vm.pending_action, success, error);
2017
                    vm.clear_pending_action();
2018
                }
2019
            })
2020
        },
2021
        
2022
        do_all_reboots: function(success, error) {
2023
            this.each(function(vm) {
2024
                if (vm.get("reboot_required")) {
2025
                    vm.call("reboot", success, error);
2026
                }
2027
            });
2028
        },
2029

    
2030
        reset_reboot_required: function() {
2031
            this.each(function(vm) {
2032
                vm.set({'reboot_required': undefined});
2033
            })
2034
        },
2035
        
2036
        stop_stats_update: function(exclude) {
2037
            var exclude = exclude || [];
2038
            this.each(function(vm) {
2039
                if (exclude.indexOf(vm) > -1) {
2040
                    return;
2041
                }
2042
                vm.stop_stats_update();
2043
            })
2044
        },
2045
        
2046
        has_meta: function(vm_data) {
2047
            return vm_data.metadata && vm_data.metadata.values
2048
        },
2049

    
2050
        has_addresses: function(vm_data) {
2051
            return vm_data.metadata && vm_data.metadata.values
2052
        },
2053

    
2054
        create: function (name, image, flavor, meta, extra, callback) {
2055

    
2056
            if (this.copy_image_meta) {
2057
                if (synnefo.config.vm_image_common_metadata) {
2058
                    _.each(synnefo.config.vm_image_common_metadata, 
2059
                        function(key){
2060
                            if (image.get_meta(key)) {
2061
                                meta[key] = image.get_meta(key);
2062
                            }
2063
                    });
2064
                }
2065

    
2066
                if (image.get("OS")) {
2067
                    meta['OS'] = image.get("OS");
2068
                }
2069
            }
2070
            
2071
            opts = {name: name, imageRef: image.id, flavorRef: flavor.id, metadata:meta}
2072
            opts = _.extend(opts, extra);
2073

    
2074
            this.api_call(this.path, "create", {'server': opts}, undefined, undefined, callback, {critical: true});
2075
        }
2076

    
2077
    })
2078
    
2079
    models.NIC = models.Model.extend({
2080
        
2081
        initialize: function() {
2082
            models.NIC.__super__.initialize.apply(this, arguments);
2083
            this.pending_for_firewall = false;
2084
            this.bind("change:firewallProfile", _.bind(this.check_firewall, this));
2085
            this.bind("change:pending_firewall", function(nic) {
2086
                nic.get_network().update_state();
2087
            });
2088
            this.get_vm().bind("remove", function(){
2089
                try {
2090
                    this.collection.remove(this);
2091
                } catch (err) {};
2092
            }, this);
2093
            this.get_network().bind("remove", function(){
2094
                try {
2095
                    this.collection.remove(this);
2096
                } catch (err) {};
2097
            }, this);
2098

    
2099
        },
2100

    
2101
        get_vm: function() {
2102
            return synnefo.storage.vms.get(parseInt(this.get('vm_id')));
2103
        },
2104

    
2105
        get_network: function() {
2106
            return synnefo.storage.networks.get(this.get('network_id'));
2107
        },
2108

    
2109
        get_v6_address: function() {
2110
            return this.get("ipv6");
2111
        },
2112

    
2113
        get_v4_address: function() {
2114
            return this.get("ipv4");
2115
        },
2116

    
2117
        set_firewall: function(value, callback, error, options) {
2118
            var net_id = this.get('network_id');
2119
            var self = this;
2120

    
2121
            // api call data
2122
            var payload = {"firewallProfile":{"profile":value}};
2123
            payload._options = _.extend({critical: false}, options);
2124
            
2125
            this.set({'pending_firewall': value});
2126
            this.set({'pending_firewall_sending': true});
2127
            this.set({'pending_firewall_from': this.get('firewallProfile')});
2128

    
2129
            var success_cb = function() {
2130
                if (callback) {
2131
                    callback();
2132
                }
2133
                self.set({'pending_firewall_sending': false});
2134
            };
2135

    
2136
            var error_cb = function() {
2137
                self.reset_pending_firewall();
2138
            }
2139
            
2140
            this.get_vm().api_call(this.get_vm().api_path() + "/action", "create", payload, success_cb, error_cb);
2141
        },
2142

    
2143
        reset_pending_firewall: function() {
2144
            this.set({'pending_firewall': false});
2145
            this.set({'pending_firewall': false});
2146
        },
2147

    
2148
        check_firewall: function() {
2149
            var firewall = this.get('firewallProfile');
2150
            var pending = this.get('pending_firewall');
2151
            var previous = this.get('pending_firewall_from');
2152
            if (previous != firewall) { this.get_vm().require_reboot() };
2153
            this.reset_pending_firewall();
2154
        }
2155
        
2156
    });
2157

    
2158
    models.NICs = models.Collection.extend({
2159
        model: models.NIC,
2160
        
2161
        add_or_update: function(nic_id, data, vm) {
2162
            var params = _.clone(data);
2163
            var vm;
2164
            params.attachment_id = params.id;
2165
            params.id = params.id + '-' + params.network_id;
2166
            params.vm_id = parseInt(NIC_REGEX.exec(nic_id)[1]);
2167

    
2168
            if (!this.get(params.id)) {
2169
                this.add(params);
2170
                var nic = this.get(params.id);
2171
                vm = nic.get_vm();
2172
                nic.get_network().decrease_connecting();
2173
                nic.bind("remove", function() {
2174
                    nic.set({"removing": 0});
2175
                    if (this.get_network()) {
2176
                        // network might got removed before nic
2177
                        nic.get_network().update_state();
2178
                    }
2179
                });
2180

    
2181
            } else {
2182
                this.get(params.id).set(params);
2183
                vm = this.get(params.id).get_vm();
2184
            }
2185
            
2186
            // vm nics changed, trigger vm update
2187
            if (vm) { vm.trigger("change", vm)};
2188
        },
2189
        
2190
        reset_nics: function(nics, filter_attr, filter_val) {
2191
            var nics_to_check = this.filter(function(nic) {
2192
                return nic.get(filter_attr) == filter_val;
2193
            });
2194
            
2195
            _.each(nics_to_check, function(nic) {
2196
                if (nics.indexOf(nic.get('id')) == -1) {
2197
                    this.remove(nic);
2198
                } else {
2199
                }
2200
            }, this);
2201
        },
2202

    
2203
        update_vm_nics: function(vm) {
2204
            var nics = vm.get('nics');
2205
            this.reset_nics(_.map(nics, function(nic, key){
2206
                return key + "-" + nic.network_id;
2207
            }), 'vm_id', vm.id);
2208

    
2209
            _.each(nics, function(val, key) {
2210
                var net = synnefo.storage.networks.get(val.network_id);
2211
                if (net && net.connected_with_nic_id(key) && vm.connected_with_nic_id(key)) {
2212
                    this.add_or_update(key, vm.get('nics')[key], vm);
2213
                }
2214
            }, this);
2215
        },
2216

    
2217
        update_net_nics: function(net) {
2218
            var nics = net.get('nics');
2219
            this.reset_nics(_.map(nics, function(nic, key){
2220
                return key + "-" + net.get('id');
2221
            }), 'network_id', net.id);
2222

    
2223
            _.each(nics, function(val, key) {
2224
                var vm = synnefo.storage.vms.get(val.vm_id);
2225
                if (vm && net.connected_with_nic_id(key) && vm.connected_with_nic_id(key)) {
2226
                    this.add_or_update(key, vm.get('nics')[key], vm);
2227
                }
2228
            }, this);
2229
        }
2230
    });
2231

    
2232
    models.PublicKey = models.Model.extend({
2233
        path: 'keys',
2234
        base_url: '/ui/userdata',
2235
        details: false,
2236
        noUpdate: true,
2237

    
2238

    
2239
        get_public_key: function() {
2240
            return cryptico.publicKeyFromString(this.get("content"));
2241
        },
2242

    
2243
        get_filename: function() {
2244
            return "{0}.pub".format(this.get("name"));
2245
        },
2246

    
2247
        identify_type: function() {
2248
            try {
2249
                var cont = snf.util.validatePublicKey(this.get("content"));
2250
                var type = cont.split(" ")[0];
2251
                return synnefo.util.publicKeyTypesMap[type];
2252
            } catch (err) { return false };
2253
        }
2254

    
2255
    })
2256
    
2257
    models.PublicKeys = models.Collection.extend({
2258
        model: models.PublicKey,
2259
        details: false,
2260
        path: 'keys',
2261
        base_url: '/ui/userdata',
2262
        noUpdate: true,
2263

    
2264
        generate_new: function(success, error) {
2265
            snf.api.sync('create', undefined, {
2266
                url: getUrl.call(this, this.base_url) + "/generate", 
2267
                success: success, 
2268
                error: error,
2269
                skip_api_error: true
2270
            });
2271
        },
2272

    
2273
        add_crypto_key: function(key, success, error, options) {
2274
            var options = options || {};
2275
            var m = new models.PublicKey();
2276

    
2277
            // guess a name
2278
            var name_tpl = "my generated public key";
2279
            var name = name_tpl;
2280
            var name_count = 1;
2281
            
2282
            while(this.filter(function(m){ return m.get("name") == name }).length > 0) {
2283
                name = name_tpl + " " + name_count;
2284
                name_count++;
2285
            }
2286
            
2287
            m.set({name: name});
2288
            m.set({content: key});
2289
            
2290
            options.success = function () { return success(m) };
2291
            options.errror = error;
2292
            options.skip_api_error = true;
2293
            
2294
            this.create(m.attributes, options);
2295
        }
2296
    })
2297
    
2298
    // storage initialization
2299
    snf.storage.images = new models.Images();
2300
    snf.storage.flavors = new models.Flavors();
2301
    snf.storage.networks = new models.Networks();
2302
    snf.storage.vms = new models.VMS();
2303
    snf.storage.keys = new models.PublicKeys();
2304
    snf.storage.nics = new models.NICs();
2305

    
2306
    //snf.storage.vms.fetch({update:true});
2307
    //snf.storage.images.fetch({update:true});
2308
    //snf.storage.flavors.fetch({update:true});
2309

    
2310
})(this);