Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (81.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.get_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_ram_size: function() {
389
            return parseInt(this.get("ram"))
390
        },
391

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

    
400
        disk_to_bytes: function() {
401
            return parseInt(this.get("disk")) * 1024 * 1024 * 1024;
402
        },
403

    
404
        ram_to_bytes: function() {
405
            return parseInt(this.get("ram")) * 1024 * 1024;
406
        },
407

    
408
    });
409
    
410
    models.ParamsList = function(){this.initialize.apply(this, arguments)};
411
    _.extend(models.ParamsList.prototype, bb.Events, {
412

    
413
        initialize: function(parent, param_name) {
414
            this.parent = parent;
415
            this.actions = {};
416
            this.param_name = param_name;
417
            this.length = 0;
418
        },
419
        
420
        has_action: function(action) {
421
            return this.actions[action] ? true : false;
422
        },
423
            
424
        _parse_params: function(arguments) {
425
            if (arguments.length <= 1) {
426
                return [];
427
            }
428

    
429
            var args = _.toArray(arguments);
430
            return args.splice(1);
431
        },
432

    
433
        contains: function(action, params) {
434
            params = this._parse_params(arguments);
435
            var has_action = this.has_action(action);
436
            if (!has_action) { return false };
437

    
438
            var paramsEqual = false;
439
            _.each(this.actions[action], function(action_params) {
440
                if (_.isEqual(action_params, params)) {
441
                    paramsEqual = true;
442
                }
443
            });
444
                
445
            return paramsEqual;
446
        },
447
        
448
        is_empty: function() {
449
            return _.isEmpty(this.actions);
450
        },
451

    
452
        add: function(action, params) {
453
            params = this._parse_params(arguments);
454
            if (this.contains.apply(this, arguments)) { return this };
455
            var isnew = false
456
            if (!this.has_action(action)) {
457
                this.actions[action] = [];
458
                isnew = true;
459
            };
460

    
461
            this.actions[action].push(params);
462
            this.parent.trigger("change:" + this.param_name, this.parent, this);
463
            if (isnew) {
464
                this.trigger("add", action, params);
465
            } else {
466
                this.trigger("change", action, params);
467
            }
468
            return this;
469
        },
470
        
471
        remove_all: function(action) {
472
            if (this.has_action(action)) {
473
                delete this.actions[action];
474
                this.parent.trigger("change:" + this.param_name, this.parent, this);
475
                this.trigger("remove", action);
476
            }
477
            return this;
478
        },
479

    
480
        reset: function() {
481
            this.actions = {};
482
            this.parent.trigger("change:" + this.param_name, this.parent, this);
483
            this.trigger("reset");
484
            this.trigger("remove");
485
        },
486

    
487
        remove: function(action, params) {
488
            params = this._parse_params(arguments);
489
            if (!this.has_action(action)) { return this };
490
            var index = -1;
491
            _.each(this.actions[action], _.bind(function(action_params) {
492
                if (_.isEqual(action_params, params)) {
493
                    index = this.actions[action].indexOf(action_params);
494
                }
495
            }, this));
496
            
497
            if (index > -1) {
498
                this.actions[action].splice(index, 1);
499
                if (_.isEmpty(this.actions[action])) {
500
                    delete this.actions[action];
501
                }
502
                this.parent.trigger("change:" + this.param_name, this.parent, this);
503
                this.trigger("remove", action, params);
504
            }
505
        }
506

    
507
    });
508

    
509
    // Image model
510
    models.Network = models.Model.extend({
511
        path: 'networks',
512
        has_status: true,
513
        defaults: {'connecting':0},
514
        
515
        initialize: function() {
516
            var ret = models.Network.__super__.initialize.apply(this, arguments);
517
            this.set({"actions": new models.ParamsList(this, "actions")});
518
            this.update_state();
519
            this.bind("change:nics", _.bind(synnefo.storage.nics.update_net_nics, synnefo.storage.nics));
520
            this.bind("change:status", _.bind(this.update_state, this));
521
            return ret;
522
        },
523
        
524
        is_deleted: function() {
525
          return this.get('status') == 'DELETED';
526
        },
527

    
528
        toJSON: function() {
529
            var attrs = _.clone(this.attributes);
530
            attrs.actions = _.clone(this.get("actions").actions);
531
            return attrs;
532
        },
533
        
534
        set_state: function(val) {
535
            if (val == "PENDING" && this.get("state") == "DESTORY") {
536
                return "DESTROY";
537
            }
538
            return val;
539
        },
540

    
541
        update_state: function() {
542
            if (this.get("connecting") > 0) {
543
                this.set({state: "CONNECTING"});
544
                return
545
            }
546
            
547
            if (this.get_nics(function(nic){ return nic.get("removing") == 1}).length > 0) {
548
                this.set({state: "DISCONNECTING"});
549
                return
550
            }   
551
            
552
            if (this.contains_firewalling_nics() > 0) {
553
                this.set({state: "FIREWALLING"});
554
                return
555
            }   
556
            
557
            if (this.get("state") == "DESTROY") { 
558
                this.set({"destroyed":1});
559
            }
560
            
561
            this.set({state:this.get('status')});
562
        },
563

    
564
        is_public: function() {
565
            return this.get("public");
566
        },
567

    
568
        decrease_connecting: function() {
569
            var conn = this.get("connecting");
570
            if (!conn) { conn = 0 };
571
            if (conn > 0) {
572
                conn--;
573
            }
574
            this.set({"connecting": conn});
575
            this.update_state();
576
        },
577

    
578
        increase_connecting: function() {
579
            var conn = this.get("connecting");
580
            if (!conn) { conn = 0 };
581
            conn++;
582
            this.set({"connecting": conn});
583
            this.update_state();
584
        },
585

    
586
        connected_to: function(vm) {
587
            return this.get('linked_to').indexOf(""+vm.id) > -1;
588
        },
589

    
590
        connected_with_nic_id: function(nic_id) {
591
            return _.keys(this.get('nics')).indexOf(nic_id) > -1;
592
        },
593

    
594
        get_nics: function(filter) {
595
            var nics = synnefo.storage.nics.filter(function(nic) {
596
                return nic.get('network_id') == this.id;
597
            }, this);
598

    
599
            if (filter) {
600
                return _.filter(nics, filter);
601
            }
602
            return nics;
603
        },
604

    
605
        contains_firewalling_nics: function() {
606
            return this.get_nics(function(n){return n.get('pending_firewall')}).length
607
        },
608

    
609
        call: function(action, params, success, error) {
610
            if (action == "destroy") {
611
                var previous_state = this.get('state');
612
                var previous_status = this.get('status');
613

    
614
                this.set({state:"DESTROY"});
615

    
616
                var _success = _.bind(function() {
617
                    if (success) { success() };
618
                }, this);
619
                var _error = _.bind(function() {
620
                    this.set({state: previous_state, status: previous_status})
621
                    if (error) { error() };
622
                }, this);
623

    
624
                this.remove(undefined, _error, _success);
625
            }
626
            
627
            if (action == "disconnect") {
628
                if (this.get("state") == "DESTROY") {
629
                    return;
630
                }
631
                
632
                _.each(params, _.bind(function(nic_id) {
633
                    var nic = snf.storage.nics.get(nic_id);
634
                    this.get("actions").remove("disconnect", nic_id);
635
                    if (nic) {
636
                        this.remove_nic(nic, success, error);
637
                    }
638
                }, this));
639
            }
640
        },
641

    
642
        add_vm: function (vm, callback, error, options) {
643
            var payload = {add:{serverRef:"" + vm.id}};
644
            payload._options = options || {};
645
            return this.api_call(this.api_path() + "/action", "create", 
646
                                 payload,
647
                                 undefined,
648
                                 error,
649
                                 _.bind(function(){
650
                                     //this.vms.add_pending(vm.id);
651
                                     this.increase_connecting();
652
                                     if (callback) {callback()}
653
                                 },this), error);
654
        },
655

    
656
        remove_nic: function (nic, callback, error, options) {
657
            var payload = {remove:{attachment:"" + nic.get("attachment_id")}};
658
            payload._options = options || {};
659
            return this.api_call(this.api_path() + "/action", "create", 
660
                                 payload,
661
                                 undefined,
662
                                 error,
663
                                 _.bind(function(){
664
                                     nic.set({"removing": 1});
665
                                     nic.get_network().update_state();
666
                                     //this.vms.add_pending_for_remove(vm.id);
667
                                     if (callback) {callback()}
668
                                 },this), error);
669
        },
670

    
671
        rename: function(name, callback) {
672
            return this.api_call(this.api_path(), "update", {
673
                network:{name:name}, 
674
                _options:{
675
                    critical: false, 
676
                    error_params:{
677
                        title: "Network action failed",
678
                        ns: "Networks",
679
                        extra_details: {"Network id": this.id}
680
                    }
681
                }}, callback);
682
        },
683

    
684
        get_connectable_vms: function() {
685
            return storage.vms.filter(function(vm){
686
                return !vm.in_error_state() && !vm.is_building();
687
            })
688
        },
689

    
690
        state_message: function() {
691
            if (this.get("state") == "ACTIVE" && !this.is_public()) {
692
                if (this.get("cidr") && this.get("dhcp") == true) {
693
                    return this.get("cidr");
694
                } else {
695
                    return "Private network";
696
                }
697
            }
698
            if (this.get("state") == "ACTIVE" && this.is_public()) {
699
                  return "Public network";
700
            }
701

    
702
            return models.Network.STATES[this.get("state")];
703
        },
704

    
705
        in_progress: function() {
706
            return models.Network.STATES_TRANSITIONS[this.get("state")] != undefined;
707
        },
708

    
709
        do_all_pending_actions: function(success, error) {
710
          var params, actions, action_params;
711
          actions = _.clone(this.get("actions").actions);
712
            _.each(actions, _.bind(function(params, action) {
713
                action_params = _.map(actions[action], function(a){ return _.clone(a)});
714
                _.each(action_params, _.bind(function(params) {
715
                    this.call(action, params, success, error);
716
                }, this));
717
            }, this));
718
            this.get("actions").reset();
719
        }
720
    });
721
    
722
    models.Network.STATES = {
723
        'ACTIVE': 'Private network',
724
        'CONNECTING': 'Connecting...',
725
        'DISCONNECTING': 'Disconnecting...',
726
        'FIREWALLING': 'Firewall update...',
727
        'DESTROY': 'Destroying...',
728
        'PENDING': 'Pending...',
729
        'ERROR': 'Error'
730
    }
731

    
732
    models.Network.STATES_TRANSITIONS = {
733
        'CONNECTING': ['ACTIVE'],
734
        'DISCONNECTING': ['ACTIVE'],
735
        'PENDING': ['ACTIVE'],
736
        'FIREWALLING': ['ACTIVE']
737
    }
738

    
739
    // Virtualmachine model
740
    models.VM = models.Model.extend({
741

    
742
        path: 'servers',
743
        has_status: true,
744
        initialize: function(params) {
745
            
746
            this.pending_firewalls = {};
747
            
748
            models.VM.__super__.initialize.apply(this, arguments);
749

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

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

    
782
            this.bind("change:nics", _.bind(synnefo.storage.nics.update_vm_nics, synnefo.storage.nics));
783
        },
784

    
785
        status: function(st) {
786
            if (!st) { return this.get("status")}
787
            return this.set({status:st});
788
        },
789

    
790
        set_status: function(st) {
791
            var new_state = this.state_for_api_status(st);
792
            var transition = false;
793

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

    
820
        has_diagnostics: function() {
821
            return this.get("diagnostics") && this.get("diagnostics").length;
822
        },
823

    
824
        get_progress_info: function() {
825
            // details about progress message
826
            // contains a list of diagnostic messages
827
            return this.get("status_messages");
828
        },
829

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

    
845
            var msg = messages[0];
846
            if (msg) {
847
              var message = msg.message;
848
              var message_tpl = snf.config.diagnostic_messages_tpls[msg.source];
849

    
850
              if (message_tpl) {
851
                  message = message_tpl.replace('MESSAGE', msg.message);
852
              }
853
              return message;
854
            }
855
            
856
            // no message to display, but vm in build state, display
857
            // finalizing message.
858
            if (this.is_building() == 'BUILD') {
859
                return synnefo.config.BUILDING_MESSAGES['FINAL'];
860
            }
861
            return null;
862
        },
863

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

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

    
925
            // copy finished display FINAL message or identify status message
926
            // from diagnostics.
927
            if (progress >= 100) {
928
                if (!this.has_diagnostics()) {
929
                        callback(BUILDING_MESSAGES['FINAL']);
930
                } else {
931
                        var d = this.get("diagnostics");
932
                        var msg = this.status_message_from_diagnostics(d);
933
                        if (msg) {
934
                              callback(msg);
935
                        }
936
                }
937
            }
938
        },
939

    
940
        get_copy_details: function(human, image, callback) {
941
            var human = human || false;
942
            var image = image || this.get_image(_.bind(function(image){
943
                var progress = this.get('progress');
944
                var size = image.get_size();
945
                var size_copied = (size * progress / 100).toFixed(2);
946
                
947
                if (human) {
948
                    size = util.readablizeBytes(size*1024*1024);
949
                    size_copied = util.readablizeBytes(size_copied*1024*1024);
950
                }
951

    
952
                callback({'progress': progress, 'size': size, 'copy': size_copied})
953
            }, this));
954
        },
955

    
956
        start_stats_update: function(force_if_empty) {
957
            var prev_state = this.do_update_stats;
958

    
959
            this.do_update_stats = true;
960
            
961
            // fetcher initialized ??
962
            if (!this.stats_fetcher) {
963
                this.init_stats_intervals();
964
            }
965

    
966

    
967
            // fetcher running ???
968
            if (!this.stats_fetcher.running || !prev_state) {
969
                this.stats_fetcher.start();
970
            }
971

    
972
            if (force_if_empty && this.get("stats") == undefined) {
973
                this.update_stats(true);
974
            }
975
        },
976

    
977
        stop_stats_update: function(stop_calls) {
978
            this.do_update_stats = false;
979

    
980
            if (stop_calls) {
981
                this.stats_fetcher.stop();
982
            }
983
        },
984

    
985
        // clear and reinitialize update interval
986
        init_stats_intervals: function (interval) {
987
            this.stats_fetcher = this.get_stats_fetcher(this.stats_update_interval);
988
            this.stats_fetcher.start();
989
        },
990
        
991
        get_stats_fetcher: function(timeout) {
992
            var cb = _.bind(function(data){
993
                this.update_stats();
994
            }, this);
995
            var fetcher = new snf.api.updateHandler({'callback': cb, interval: timeout, id:'stats'});
996
            return fetcher;
997
        },
998

    
999
        // do the api call
1000
        update_stats: function(force) {
1001
            // do not update stats if flag not set
1002
            if ((!this.do_update_stats && !force) || this.updating_stats) {
1003
                return;
1004
            }
1005

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

    
1023
        get_stats_image: function(stat, type) {
1024
        },
1025
        
1026
        _set_stats: function(stats) {
1027
            var silent = silent === undefined ? false : silent;
1028
            // unavailable stats while building
1029
            if (this.get("status") == "BUILD") { 
1030
                this.stats_available = false;
1031
            } else { this.stats_available = true; }
1032

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

    
1039
        unbind: function() {
1040
            models.VM.__super__.unbind.apply(this, arguments);
1041
        },
1042

    
1043
        handle_stats_error: function() {
1044
            stats = {};
1045
            _.each(['cpuBar', 'cpuTimeSeries', 'netBar', 'netTimeSeries'], function(k) {
1046
                stats[k] = false;
1047
            });
1048

    
1049
            this.set({'stats': stats});
1050
        },
1051

    
1052
        // this method gets executed after a successful vm stats api call
1053
        handle_stats_update: function(data) {
1054
            var self = this;
1055
            // avoid browser caching
1056
            
1057
            if (data.stats && _.size(data.stats) > 0) {
1058
                var ts = $.now();
1059
                var stats = data.stats;
1060
                var images_loaded = 0;
1061
                var images = {};
1062

    
1063
                function check_images_loaded() {
1064
                    images_loaded++;
1065

    
1066
                    if (images_loaded == 4) {
1067
                        self._set_stats(images);
1068
                    }
1069
                }
1070
                _.each(['cpuBar', 'cpuTimeSeries', 'netBar', 'netTimeSeries'], function(k) {
1071
                    
1072
                    stats[k] = stats[k] + "?_=" + ts;
1073
                    
1074
                    var stat = k.slice(0,3);
1075
                    var type = k.slice(3,6) == "Bar" ? "bar" : "time";
1076
                    var img = $("<img />");
1077
                    var val = stats[k];
1078
                    
1079
                    // load stat image to a temporary dom element
1080
                    // update model stats on image load/error events
1081
                    img.load(function() {
1082
                        images[k] = val;
1083
                        check_images_loaded();
1084
                    });
1085

    
1086
                    img.error(function() {
1087
                        images[stat + type] = false;
1088
                        check_images_loaded();
1089
                    });
1090

    
1091
                    img.attr({'src': stats[k]});
1092
                })
1093
                data.stats = stats;
1094
            }
1095

    
1096
            // do we need to change the interval ??
1097
            if (data.stats.refresh * 1000 != this.stats_update_interval) {
1098
                this.stats_update_interval = data.stats.refresh * 1000;
1099
                this.stats_fetcher.interval = this.stats_update_interval;
1100
                this.stats_fetcher.maximum_interval = this.stats_update_interval;
1101
                this.stats_fetcher.stop();
1102
                this.stats_fetcher.start(false);
1103
            }
1104
        },
1105

    
1106
        // helper method that sets the do_update_stats
1107
        // in the future this method could also make an api call
1108
        // immediaetly if needed
1109
        enable_stats_update: function() {
1110
            this.do_update_stats = true;
1111
        },
1112
        
1113
        handle_destroy: function() {
1114
            this.stats_fetcher.stop();
1115
        },
1116

    
1117
        require_reboot: function() {
1118
            if (this.is_active()) {
1119
                this.set({'reboot_required': true});
1120
            }
1121
        },
1122
        
1123
        set_pending_action: function(data) {
1124
            this.pending_action = data;
1125
            return data;
1126
        },
1127

    
1128
        // machine has pending action
1129
        update_pending_action: function(action, force) {
1130
            this.set({pending_action: action});
1131
        },
1132

    
1133
        clear_pending_action: function() {
1134
            this.set({pending_action: undefined});
1135
        },
1136

    
1137
        has_pending_action: function() {
1138
            return this.get("pending_action") ? this.get("pending_action") : false;
1139
        },
1140
        
1141
        // machine is active
1142
        is_active: function() {
1143
            return models.VM.ACTIVE_STATES.indexOf(this.state()) > -1;
1144
        },
1145
        
1146
        // machine is building 
1147
        is_building: function() {
1148
            return models.VM.BUILDING_STATES.indexOf(this.state()) > -1;
1149
        },
1150
        
1151
        in_error_state: function() {
1152
            return this.state() === "ERROR"
1153
        },
1154

    
1155
        // user can connect to machine
1156
        is_connectable: function() {
1157
            // check if ips exist
1158
            if (!this.get_addresses().ip4 && !this.get_addresses().ip6) {
1159
                return false;
1160
            }
1161
            return models.VM.CONNECT_STATES.indexOf(this.state()) > -1;
1162
        },
1163
        
1164
        remove_meta: function(key, complete, error) {
1165
            var url = this.api_path() + "/meta/" + key;
1166
            this.api_call(url, "delete", undefined, complete, error);
1167
        },
1168

    
1169
        save_meta: function(meta, complete, error) {
1170
            var url = this.api_path() + "/meta/" + meta.key;
1171
            var payload = {meta:{}};
1172
            payload.meta[meta.key] = meta.value;
1173
            payload._options = {
1174
                critical:false, 
1175
                error_params: {
1176
                    title: "Machine metadata error",
1177
                    extra_details: {"Machine id": this.id}
1178
            }};
1179

    
1180
            this.api_call(url, "update", payload, complete, error);
1181
        },
1182

    
1183

    
1184
        // update/get the state of the machine
1185
        state: function() {
1186
            var args = slice.call(arguments);
1187
                
1188
            // TODO: it might not be a good idea to set the state in set_state method
1189
            if (args.length > 0 && models.VM.STATES.indexOf(args[0]) > -1) {
1190
                this.set({'state': args[0]});
1191
            }
1192

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

    
1248
        get_meta: function(key, deflt) {
1249
            if (this.get('metadata') && this.get('metadata').values) {
1250
                if (!this.get('metadata').values[key]) { return deflt }
1251
                return _.escape(this.get('metadata').values[key]);
1252
            } else {
1253
                return deflt;
1254
            }
1255
        },
1256

    
1257
        get_meta_keys: function() {
1258
            if (this.get('metadata') && this.get('metadata').values) {
1259
                return _.keys(this.get('metadata').values);
1260
            } else {
1261
                return [];
1262
            }
1263
        },
1264
        
1265
        // get metadata OS value
1266
        get_os: function() {
1267
            var image = this.get_image();
1268
            return this.get_meta('OS') || (image ? 
1269
                                            image.get_os() || "okeanos" : "okeanos");
1270
        },
1271

    
1272
        get_gui: function() {
1273
            return this.get_meta('GUI');
1274
        },
1275
        
1276
        connected_to: function(net) {
1277
            return this.get('linked_to').indexOf(net.id) > -1;
1278
        },
1279

    
1280
        connected_with_nic_id: function(nic_id) {
1281
            return _.keys(this.get('nics')).indexOf(nic_id) > -1;
1282
        },
1283

    
1284
        get_nics: function(filter) {
1285
            ret = synnefo.storage.nics.filter(function(nic) {
1286
                return parseInt(nic.get('vm_id')) == this.id;
1287
            }, this);
1288

    
1289
            if (filter) {
1290
                return _.filter(ret, filter);
1291
            }
1292

    
1293
            return ret;
1294
        },
1295

    
1296
        get_net_nics: function(net_id) {
1297
            return this.get_nics(function(n){return n.get('network_id') == net_id});
1298
        },
1299

    
1300
        get_public_nic: function() {
1301
            return this.get_nics(function(n){ return n.get_network().is_public() === true })[0];
1302
        },
1303

    
1304
        get_hostname: function() {
1305
          var hostname = this.get_meta('hostname');
1306
          if (!hostname) {
1307
            if (synnefo.config.vm_hostname_format) {
1308
              hostname = synnefo.config.vm_hostname_format.format(this.id);
1309
            } else {
1310
              hostname = this.get_public_nic().get('ipv4');
1311
            }
1312
          }
1313
          return hostname;
1314
        },
1315

    
1316
        get_nic: function(net_id) {
1317
        },
1318

    
1319
        has_firewall: function() {
1320
            var nic = this.get_public_nic();
1321
            if (nic) {
1322
                var profile = nic.get('firewallProfile'); 
1323
                return ['ENABLED', 'PROTECTED'].indexOf(profile) > -1;
1324
            }
1325
            return false;
1326
        },
1327

    
1328
        get_firewall_profile: function() {
1329
            var nic = this.get_public_nic();
1330
            if (nic) {
1331
                return nic.get('firewallProfile');
1332
            }
1333
            return null;
1334
        },
1335

    
1336
        get_addresses: function() {
1337
            var pnic = this.get_public_nic();
1338
            if (!pnic) { return {'ip4': undefined, 'ip6': undefined }};
1339
            return {'ip4': pnic.get('ipv4'), 'ip6': pnic.get('ipv6')};
1340
        },
1341
    
1342
        // get actions that the user can execute
1343
        // depending on the vm state/status
1344
        get_available_actions: function() {
1345
            return models.VM.AVAILABLE_ACTIONS[this.state()];
1346
        },
1347

    
1348
        set_profile: function(profile, net_id) {
1349
        },
1350
        
1351
        // call rename api
1352
        rename: function(new_name) {
1353
            //this.set({'name': new_name});
1354
            this.sync("update", this, {
1355
                critical: true,
1356
                data: {
1357
                    'server': {
1358
                        'name': new_name
1359
                    }
1360
                }, 
1361
                // do the rename after the method succeeds
1362
                success: _.bind(function(){
1363
                    //this.set({name: new_name});
1364
                    snf.api.trigger("call");
1365
                }, this)
1366
            });
1367
        },
1368
        
1369
        get_console_url: function(data) {
1370
            var url_params = {
1371
                machine: this.get("name"),
1372
                host_ip: this.get_addresses().ip4,
1373
                host_ip_v6: this.get_addresses().ip6,
1374
                host: data.host,
1375
                port: data.port,
1376
                password: data.password
1377
            }
1378
            return '/machines/console?' + $.param(url_params);
1379
        },
1380

    
1381
        // action helper
1382
        call: function(action_name, success, error, params) {
1383
            var id_param = [this.id];
1384
            
1385
            params = params || {};
1386
            success = success || function() {};
1387
            error = error || function() {};
1388

    
1389
            var self = this;
1390

    
1391
            switch(action_name) {
1392
                case 'start':
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
                                         {start:{}}, // payload
1396
                                         function() {
1397
                                             // set state after successful call
1398
                                             self.state("START"); 
1399
                                             success.apply(this, arguments);
1400
                                             snf.api.trigger("call");
1401
                                         },  
1402
                                         error, 'start', params);
1403
                    break;
1404
                case 'reboot':
1405
                    this.__make_api_call(this.get_action_url(), // vm actions url
1406
                                         "create", // create so that sync later uses POST to make the call
1407
                                         {reboot:{type:"HARD"}}, // payload
1408
                                         function() {
1409
                                             // set state after successful call
1410
                                             self.state("REBOOT"); 
1411
                                             success.apply(this, arguments)
1412
                                             snf.api.trigger("call");
1413
                                             self.set({'reboot_required': false});
1414
                                         },
1415
                                         error, 'reboot', params);
1416
                    break;
1417
                case 'shutdown':
1418
                    this.__make_api_call(this.get_action_url(), // vm actions url
1419
                                         "create", // create so that sync later uses POST to make the call
1420
                                         {shutdown:{}}, // payload
1421
                                         function() {
1422
                                             // set state after successful call
1423
                                             self.state("SHUTDOWN"); 
1424
                                             success.apply(this, arguments)
1425
                                             snf.api.trigger("call");
1426
                                         },  
1427
                                         error, 'shutdown', params);
1428
                    break;
1429
                case 'console':
1430
                    this.__make_api_call(this.url() + "/action", "create", {'console': {'type':'vnc'}}, function(data) {
1431
                        var cons_data = data.console;
1432
                        success.apply(this, [cons_data]);
1433
                    }, undefined, 'console', params)
1434
                    break;
1435
                case 'destroy':
1436
                    this.__make_api_call(this.url(), // vm actions url
1437
                                         "delete", // create so that sync later uses POST to make the call
1438
                                         undefined, // payload
1439
                                         function() {
1440
                                             // set state after successful call
1441
                                             self.state('DESTROY');
1442
                                             success.apply(this, arguments)
1443
                                         },  
1444
                                         error, 'destroy', params);
1445
                    break;
1446
                default:
1447
                    throw "Invalid VM action ("+action_name+")";
1448
            }
1449
        },
1450
        
1451
        __make_api_call: function(url, method, data, success, error, action, extra_params) {
1452
            var self = this;
1453
            error = error || function(){};
1454
            success = success || function(){};
1455

    
1456
            var params = {
1457
                url: url,
1458
                data: data,
1459
                success: function(){ self.handle_action_succeed.apply(self, arguments); success.apply(this, arguments)},
1460
                error: function(){ self.handle_action_fail.apply(self, arguments); error.apply(this, arguments)},
1461
                error_params: { ns: "Machines actions", 
1462
                                title: "'" + this.get("name") + "'" + " " + action + " failed", 
1463
                                extra_details: { 'Machine ID': this.id, 'URL': url, 'Action': action || "undefined" },
1464
                                allow_reload: false
1465
                              },
1466
                display: false,
1467
                critical: false
1468
            }
1469
            _.extend(params, extra_params)
1470
            this.sync(method, this, params);
1471
        },
1472

    
1473
        handle_action_succeed: function() {
1474
            this.trigger("action:success", arguments);
1475
        },
1476
        
1477
        reset_action_error: function() {
1478
            this.action_error = false;
1479
            this.trigger("action:fail:reset", this.action_error);
1480
        },
1481

    
1482
        handle_action_fail: function() {
1483
            this.action_error = arguments;
1484
            this.trigger("action:fail", arguments);
1485
        },
1486

    
1487
        get_action_url: function(name) {
1488
            return this.url() + "/action";
1489
        },
1490

    
1491
        get_diagnostics_url: function() {
1492
            return this.url() + "/diagnostics";
1493
        },
1494

    
1495
        get_connection_info: function(host_os, success, error) {
1496
            var url = "/machines/connect";
1497
            params = {
1498
                ip_address: this.get_public_nic().get('ipv4'),
1499
                hostname: this.get_hostname(),
1500
                os: this.get_os(),
1501
                host_os: host_os,
1502
                srv: this.id
1503
            }
1504

    
1505
            url = url + "?" + $.param(params);
1506

    
1507
            var ajax = snf.api.sync("read", undefined, { url: url, 
1508
                                                         error:error, 
1509
                                                         success:success, 
1510
                                                         handles_error:1});
1511
        }
1512
    })
1513
    
1514
    models.VM.ACTIONS = [
1515
        'start',
1516
        'shutdown',
1517
        'reboot',
1518
        'console',
1519
        'destroy'
1520
    ]
1521

    
1522
    models.VM.AVAILABLE_ACTIONS = {
1523
        'UNKNWON'       : ['destroy'],
1524
        'BUILD'         : ['destroy'],
1525
        'REBOOT'        : ['shutdown', 'destroy', 'console'],
1526
        'STOPPED'       : ['start', 'destroy'],
1527
        'ACTIVE'        : ['shutdown', 'destroy', 'reboot', 'console'],
1528
        'ERROR'         : ['destroy'],
1529
        'DELETED'        : [],
1530
        'DESTROY'       : [],
1531
        'BUILD_INIT'    : ['destroy'],
1532
        'BUILD_COPY'    : ['destroy'],
1533
        'BUILD_FINAL'   : ['destroy'],
1534
        'SHUTDOWN'      : ['destroy'],
1535
        'START'         : [],
1536
        'CONNECT'       : [],
1537
        'DISCONNECT'    : []
1538
    }
1539

    
1540
    // api status values
1541
    models.VM.STATUSES = [
1542
        'UNKNWON',
1543
        'BUILD',
1544
        'REBOOT',
1545
        'STOPPED',
1546
        'ACTIVE',
1547
        'ERROR',
1548
        'DELETED'
1549
    ]
1550

    
1551
    // api status values
1552
    models.VM.CONNECT_STATES = [
1553
        'ACTIVE',
1554
        'REBOOT',
1555
        'SHUTDOWN'
1556
    ]
1557

    
1558
    // vm states
1559
    models.VM.STATES = models.VM.STATUSES.concat([
1560
        'DESTROY',
1561
        'BUILD_INIT',
1562
        'BUILD_COPY',
1563
        'BUILD_FINAL',
1564
        'SHUTDOWN',
1565
        'START',
1566
        'CONNECT',
1567
        'DISCONNECT',
1568
        'FIREWALL'
1569
    ]);
1570
    
1571
    models.VM.STATES_TRANSITIONS = {
1572
        'DESTROY' : ['DELETED'],
1573
        'SHUTDOWN': ['ERROR', 'STOPPED', 'DESTROY'],
1574
        'STOPPED': ['ERROR', 'ACTIVE', 'DESTROY'],
1575
        'ACTIVE': ['ERROR', 'STOPPED', 'REBOOT', 'SHUTDOWN', 'DESTROY'],
1576
        'START': ['ERROR', 'ACTIVE', 'DESTROY'],
1577
        'REBOOT': ['ERROR', 'ACTIVE', 'STOPPED', 'DESTROY'],
1578
        'BUILD': ['ERROR', 'ACTIVE', 'DESTROY'],
1579
        'BUILD_COPY': ['ERROR', 'ACTIVE', 'BUILD_FINAL', 'DESTROY'],
1580
        'BUILD_FINAL': ['ERROR', 'ACTIVE', 'DESTROY'],
1581
        'BUILD_INIT': ['ERROR', 'ACTIVE', 'BUILD_COPY', 'BUILD_FINAL', 'DESTROY']
1582
    }
1583

    
1584
    models.VM.TRANSITION_STATES = [
1585
        'DESTROY',
1586
        'SHUTDOWN',
1587
        'START',
1588
        'REBOOT',
1589
        'BUILD'
1590
    ]
1591

    
1592
    models.VM.ACTIVE_STATES = [
1593
        'BUILD', 'REBOOT', 'ACTIVE',
1594
        'BUILD_INIT', 'BUILD_COPY', 'BUILD_FINAL',
1595
        'SHUTDOWN', 'CONNECT', 'DISCONNECT'
1596
    ]
1597

    
1598
    models.VM.BUILDING_STATES = [
1599
        'BUILD', 'BUILD_INIT', 'BUILD_COPY', 'BUILD_FINAL'
1600
    ]
1601

    
1602
    models.Networks = models.Collection.extend({
1603
        model: models.Network,
1604
        path: 'networks',
1605
        details: true,
1606
        //noUpdate: true,
1607
        defaults: {'nics':[],'linked_to':[]},
1608
        
1609
        parse: function (resp, xhr) {
1610
            // FIXME: depricated global var
1611
            if (!resp) { return []};
1612
            var data = _.filter(_.map(resp.networks.values, _.bind(this.parse_net_api_data, this)),
1613
                               function(e){ return e });
1614
            return data;
1615
        },
1616

    
1617
        add: function() {
1618
            ret = models.Networks.__super__.add.apply(this, arguments);
1619
            // update nics after each network addition
1620
            ret.each(function(r){
1621
                synnefo.storage.nics.update_net_nics(r);
1622
            });
1623
        },
1624

    
1625
        reset_pending_actions: function() {
1626
            this.each(function(net) {
1627
                net.get("actions").reset();
1628
            });
1629
        },
1630

    
1631
        do_all_pending_actions: function() {
1632
            this.each(function(net) {
1633
                net.do_all_pending_actions();
1634
            })
1635
        },
1636

    
1637
        parse_net_api_data: function(data) {
1638
            // append nic metadata
1639
            // net.get('nics') contains a list of vm/index objects 
1640
            // e.g. {'vm_id':12231, 'index':1}
1641
            // net.get('linked_to') contains a list of vms the network is 
1642
            // connected to e.g. [1001, 1002]
1643
            if (data.attachments && data.attachments.values) {
1644
                data['nics'] = {};
1645
                data['linked_to'] = [];
1646
                _.each(data.attachments.values, function(nic_id){
1647
                  
1648
                  var vm_id = NIC_REGEX.exec(nic_id)[1];
1649
                  var nic_index = parseInt(NIC_REGEX.exec(nic_id)[2]);
1650

    
1651
                  if (vm_id !== undefined && nic_index !== undefined) {
1652
                      data['nics'][nic_id] = {
1653
                          'vm_id': vm_id, 
1654
                          'index': nic_index, 
1655
                          'id': nic_id
1656
                      };
1657
                      if (data['linked_to'].indexOf(vm_id) == -1) {
1658
                        data['linked_to'].push(vm_id);
1659
                      }
1660
                  }
1661
                });
1662
            }
1663

    
1664
            if (data.status == "DELETED" && !this.get(parseInt(data.id))) {
1665
              return false;
1666
            }
1667
            return data;
1668
        },
1669

    
1670
        create: function (name, type, cidr, dhcp, callback) {
1671
            var params = {
1672
                network:{
1673
                    name:name
1674
                }
1675
            };
1676

    
1677
            if (type) {
1678
                params.network.type = type;
1679
            }
1680
            if (cidr) {
1681
                params.network.cidr = cidr;
1682
            }
1683
            if (dhcp) {
1684
                params.network.dhcp = dhcp;
1685
            }
1686

    
1687
            if (dhcp === false) {
1688
                params.network.dhcp = false;
1689
            }
1690
            
1691
            return this.api_call(this.path, "create", params, callback);
1692
        },
1693

    
1694
        get_public: function(){
1695
          return this.filter(function(n){return n.get('public')});
1696
        }
1697
    })
1698

    
1699
    models.Images = models.Collection.extend({
1700
        model: models.Image,
1701
        path: 'images',
1702
        details: true,
1703
        noUpdate: true,
1704
        supportIncUpdates: false,
1705
        meta_keys_as_attrs: ["OS", "description", "kernel", "size", "GUI"],
1706
        meta_labels: {},
1707
        read_method: 'read',
1708

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

    
1754
        _read_image_from_request: function(image, msg, xhr) {
1755
            return image.image;
1756
        },
1757

    
1758
        parse: function (resp, xhr) {
1759
            var parsed = _.map(resp.images.values, _.bind(this.parse_meta, this));
1760
            parsed = this.fill_owners(parsed);
1761
            return parsed;
1762
        },
1763

    
1764
        fill_owners: function(images) {
1765
            // do translate uuid->displayname if needed
1766
            // store display name in owner attribute for compatibility
1767
            var uuids = [];
1768

    
1769
            var images = _.map(images, function(img, index) {
1770
                if (synnefo.config.translate_uuids) {
1771
                    uuids.push(img['owner']);
1772
                }
1773
                img['owner_uuid'] = img['owner'];
1774
                return img;
1775
            });
1776
            
1777
            if (uuids.length > 0) {
1778
                var handle_results = function(data) {
1779
                    _.each(images, function (img) {
1780
                        img['owner'] = data.uuid_catalog[img['owner_uuid']];
1781
                    });
1782
                }
1783
                // notice the async false
1784
                var uuid_map = this.translate_uuids(uuids, false, 
1785
                                                    handle_results)
1786
            }
1787
            return images;
1788
        },
1789

    
1790
        translate_uuids: function(uuids, async, cb) {
1791
            var url = synnefo.config.user_catalog_url;
1792
            var data = JSON.stringify({'uuids': uuids});
1793
          
1794
            // post to user_catalogs api
1795
            snf.api.sync('create', undefined, {
1796
                url: url,
1797
                data: data,
1798
                async: async,
1799
                success:  cb
1800
            });
1801
        },
1802

    
1803
        get_meta_key: function(img, key) {
1804
            if (img.metadata && img.metadata.values && img.metadata.values[key]) {
1805
                return _.escape(img.metadata.values[key]);
1806
            }
1807
            return undefined;
1808
        },
1809

    
1810
        comparator: function(img) {
1811
            return -img.get_sort_order("sortorder") || 1000 * img.id;
1812
        },
1813

    
1814
        parse_meta: function(img) {
1815
            _.each(this.meta_keys_as_attrs, _.bind(function(key){
1816
                if (img[key]) { return };
1817
                img[key] = this.get_meta_key(img, key) || "";
1818
            }, this));
1819
            return img;
1820
        },
1821

    
1822
        active: function() {
1823
            return this.filter(function(img){return img.get('status') != "DELETED"});
1824
        },
1825

    
1826
        predefined: function() {
1827
            return _.filter(this.active(), function(i) { return !i.get("serverRef")});
1828
        },
1829
        
1830
        fetch_for_type: function(type, complete, error) {
1831
            this.fetch({update:true, 
1832
                        success: complete, 
1833
                        error: error, 
1834
                        skip_api_error: true });
1835
        },
1836
        
1837
        get_images_for_type: function(type) {
1838
            if (this['get_{0}_images'.format(type)]) {
1839
                return this['get_{0}_images'.format(type)]();
1840
            }
1841

    
1842
            return this.active();
1843
        },
1844

    
1845
        update_images_for_type: function(type, onStart, onComplete, onError, force_load) {
1846
            var load = false;
1847
            error = onError || function() {};
1848
            function complete(collection) { 
1849
                onComplete(collection.get_images_for_type(type)); 
1850
            }
1851
            
1852
            // do we need to fetch/update current collection entries
1853
            if (load) {
1854
                onStart();
1855
                this.fetch_for_type(type, complete, error);
1856
            } else {
1857
                // fallback to complete
1858
                complete(this);
1859
            }
1860
        }
1861
    })
1862

    
1863
    models.Flavors = models.Collection.extend({
1864
        model: models.Flavor,
1865
        path: 'flavors',
1866
        details: true,
1867
        noUpdate: true,
1868
        supportIncUpdates: false,
1869
        // update collection model with id passed
1870
        // making a direct call to the flavor
1871
        // api url
1872
        update_unknown_id: function(id, callback) {
1873
            var url = getUrl.call(this) + "/" + id;
1874
            this.api_call(this.path + "/" + id, "read", {_options:{async:false, skip_api_error:true}}, undefined, 
1875
            _.bind(function() {
1876
                this.add({id:id, cpu:"Unknown", ram:"Unknown", disk:"Unknown", name: "Unknown", status:"DELETED"})
1877
            }, this), _.bind(function(flv) {
1878
                if (!flv.flavor.status) { flv.flavor.status = "DELETED" };
1879
                this.add(flv.flavor);
1880
            }, this));
1881
        },
1882

    
1883
        parse: function (resp, xhr) {
1884
            return _.map(resp.flavors.values, function(o) { o.disk_template = o['SNF:disk_template']; return o});
1885
        },
1886

    
1887
        comparator: function(flv) {
1888
            return flv.get("disk") * flv.get("cpu") * flv.get("ram");
1889
        },
1890

    
1891
        unavailable_values_for_quotas: function(quotas, flavors) {
1892
            var flavors = flavors || this.active();
1893
            var index = {cpu:[], disk:[], ram:[]};
1894
            
1895
            _.each(flavors, function(el) {
1896

    
1897
                var disk_available = quotas['disk'];
1898
                var disk_size = el.get_disk_size();
1899
                if (index.disk.indexOf(disk_size) == -1) {
1900
                  var disk = el.disk_to_bytes();
1901
                  if (disk > disk_available) {
1902
                    index.disk.push(disk_size);
1903
                  }
1904
                }
1905

    
1906
                var ram_available = quotas['ram'];
1907
                var ram_size = el.get_ram_size();
1908
                if (index.ram.indexOf(disk_size) == -1) {
1909
                  var ram = el.ram_to_bytes();
1910
                  if (ram > ram_available) {
1911
                    index.ram.push(el.get('ram'))
1912
                  }
1913
                }
1914

    
1915
                var cpu = el.get('cpu');
1916
                var cpu_available = quotas['cpu'];
1917
                if (index.ram.indexOf(cpu) == -1) {
1918
                  if (cpu > cpu_available) {
1919
                    index.cpu.push(el.get('cpu'))
1920
                  }
1921
                }
1922
            });
1923
            return index;
1924
        },
1925

    
1926
        unavailable_values_for_image: function(img, flavors) {
1927
            var flavors = flavors || this.active();
1928
            var size = img.get_size();
1929
            
1930
            var index = {cpu:[], disk:[], ram:[]};
1931

    
1932
            _.each(this.active(), function(el) {
1933
                var img_size = size;
1934
                var flv_size = el.get_disk_size();
1935
                if (flv_size < img_size) {
1936
                    if (index.disk.indexOf(flv_size) == -1) {
1937
                        index.disk.push(flv_size);
1938
                    }
1939
                };
1940
            });
1941
            
1942
            return index;
1943
        },
1944

    
1945
        get_flavor: function(cpu, mem, disk, disk_template, filter_list) {
1946
            if (!filter_list) { filter_list = this.models };
1947
            
1948
            return this.select(function(flv){
1949
                if (flv.get("cpu") == cpu + "" &&
1950
                   flv.get("ram") == mem + "" &&
1951
                   flv.get("disk") == disk + "" &&
1952
                   flv.get("disk_template") == disk_template &&
1953
                   filter_list.indexOf(flv) > -1) { return true; }
1954
            })[0];
1955
        },
1956
        
1957
        get_data: function(lst) {
1958
            var data = {'cpu': [], 'mem':[], 'disk':[]};
1959

    
1960
            _.each(lst, function(flv) {
1961
                if (data.cpu.indexOf(flv.get("cpu")) == -1) {
1962
                    data.cpu.push(flv.get("cpu"));
1963
                }
1964
                if (data.mem.indexOf(flv.get("ram")) == -1) {
1965
                    data.mem.push(flv.get("ram"));
1966
                }
1967
                if (data.disk.indexOf(flv.get("disk")) == -1) {
1968
                    data.disk.push(flv.get("disk"));
1969
                }
1970
            })
1971
            
1972
            return data;
1973
        },
1974

    
1975
        active: function() {
1976
            return this.filter(function(flv){return flv.get('status') != "DELETED"});
1977
        }
1978
            
1979
    })
1980

    
1981
    models.VMS = models.Collection.extend({
1982
        model: models.VM,
1983
        path: 'servers',
1984
        details: true,
1985
        copy_image_meta: true,
1986

    
1987
        parse: function (resp, xhr) {
1988
            var data = resp;
1989
            if (!resp) { return [] };
1990
            data = _.filter(_.map(resp.servers.values, _.bind(this.parse_vm_api_data, this)), function(v){return v});
1991
            return data;
1992
        },
1993

    
1994
        parse_vm_api_data: function(data) {
1995
            // do not add non existing DELETED entries
1996
            if (data.status && data.status == "DELETED") {
1997
                if (!this.get(data.id)) {
1998
                    return false;
1999
                }
2000
            }
2001

    
2002
            // OS attribute
2003
            if (this.has_meta(data)) {
2004
                data['OS'] = data.metadata.values.OS || "okeanos";
2005
            }
2006
            
2007
            if (!data.diagnostics) {
2008
                data.diagnostics = [];
2009
            }
2010

    
2011
            // network metadata
2012
            data['firewalls'] = {};
2013
            data['nics'] = {};
2014
            data['linked_to'] = [];
2015

    
2016
            if (data['attachments'] && data['attachments'].values) {
2017
                var nics = data['attachments'].values;
2018
                _.each(nics, function(nic) {
2019
                    var net_id = nic.network_id;
2020
                    var index = parseInt(NIC_REGEX.exec(nic.id)[2]);
2021
                    if (data['linked_to'].indexOf(net_id) == -1) {
2022
                        data['linked_to'].push(net_id);
2023
                    }
2024

    
2025
                    data['nics'][nic.id] = nic;
2026
                })
2027
            }
2028
            
2029
            // if vm has no metadata, no metadata object
2030
            // is in json response, reset it to force
2031
            // value update
2032
            if (!data['metadata']) {
2033
                data['metadata'] = {values:{}};
2034
            }
2035

    
2036
            return data;
2037
        },
2038

    
2039
        add: function() {
2040
            ret = models.VMS.__super__.add.apply(this, arguments);
2041
            ret.each(function(r){
2042
                synnefo.storage.nics.update_vm_nics(r);
2043
            });
2044
        },
2045
        
2046
        get_reboot_required: function() {
2047
            return this.filter(function(vm){return vm.get("reboot_required") == true})
2048
        },
2049

    
2050
        has_pending_actions: function() {
2051
            return this.filter(function(vm){return vm.pending_action}).length > 0;
2052
        },
2053

    
2054
        reset_pending_actions: function() {
2055
            this.each(function(vm) {
2056
                vm.clear_pending_action();
2057
            })
2058
        },
2059

    
2060
        do_all_pending_actions: function(success, error) {
2061
            this.each(function(vm) {
2062
                if (vm.has_pending_action()) {
2063
                    vm.call(vm.pending_action, success, error);
2064
                    vm.clear_pending_action();
2065
                }
2066
            })
2067
        },
2068
        
2069
        do_all_reboots: function(success, error) {
2070
            this.each(function(vm) {
2071
                if (vm.get("reboot_required")) {
2072
                    vm.call("reboot", success, error);
2073
                }
2074
            });
2075
        },
2076

    
2077
        reset_reboot_required: function() {
2078
            this.each(function(vm) {
2079
                vm.set({'reboot_required': undefined});
2080
            })
2081
        },
2082
        
2083
        stop_stats_update: function(exclude) {
2084
            var exclude = exclude || [];
2085
            this.each(function(vm) {
2086
                if (exclude.indexOf(vm) > -1) {
2087
                    return;
2088
                }
2089
                vm.stop_stats_update();
2090
            })
2091
        },
2092
        
2093
        has_meta: function(vm_data) {
2094
            return vm_data.metadata && vm_data.metadata.values
2095
        },
2096

    
2097
        has_addresses: function(vm_data) {
2098
            return vm_data.metadata && vm_data.metadata.values
2099
        },
2100

    
2101
        create: function (name, image, flavor, meta, extra, callback) {
2102

    
2103
            if (this.copy_image_meta) {
2104
                if (synnefo.config.vm_image_common_metadata) {
2105
                    _.each(synnefo.config.vm_image_common_metadata, 
2106
                        function(key){
2107
                            if (image.get_meta(key)) {
2108
                                meta[key] = image.get_meta(key);
2109
                            }
2110
                    });
2111
                }
2112

    
2113
                if (image.get("OS")) {
2114
                    meta['OS'] = image.get("OS");
2115
                }
2116
            }
2117
            
2118
            opts = {name: name, imageRef: image.id, flavorRef: flavor.id, metadata:meta}
2119
            opts = _.extend(opts, extra);
2120

    
2121
            this.api_call(this.path, "create", {'server': opts}, undefined, undefined, callback, {critical: true});
2122
        },
2123

    
2124
        load_missing_images: function(callback) {
2125
          var missing_ids = [];
2126
          this.each(function(el) {
2127
            var imgid = el.get("imageRef");
2128
            var existing = synnefo.storage.images.get(imgid);
2129
            if (!existing && missing_ids.indexOf(imgid) == -1) {
2130
                missing_ids.push(imgid);
2131
                synnefo.storage.images.update_unknown_id(imgid, function(){});
2132
            }
2133
          });
2134
          callback(missing_ids);
2135
        }
2136

    
2137
    })
2138
    
2139
    models.NIC = models.Model.extend({
2140
        
2141
        initialize: function() {
2142
            models.NIC.__super__.initialize.apply(this, arguments);
2143
            this.pending_for_firewall = false;
2144
            this.bind("change:firewallProfile", _.bind(this.check_firewall, this));
2145
            this.bind("change:pending_firewall", function(nic) {
2146
                nic.get_network().update_state();
2147
            });
2148
            this.get_vm().bind("remove", function(){
2149
                try {
2150
                    this.collection.remove(this);
2151
                } catch (err) {};
2152
            }, this);
2153
            this.get_network().bind("remove", function(){
2154
                try {
2155
                    this.collection.remove(this);
2156
                } catch (err) {};
2157
            }, this);
2158

    
2159
        },
2160

    
2161
        get_vm: function() {
2162
            return synnefo.storage.vms.get(parseInt(this.get('vm_id')));
2163
        },
2164

    
2165
        get_network: function() {
2166
            return synnefo.storage.networks.get(this.get('network_id'));
2167
        },
2168

    
2169
        get_v6_address: function() {
2170
            return this.get("ipv6");
2171
        },
2172

    
2173
        get_v4_address: function() {
2174
            return this.get("ipv4");
2175
        },
2176

    
2177
        set_firewall: function(value, callback, error, options) {
2178
            var net_id = this.get('network_id');
2179
            var self = this;
2180

    
2181
            // api call data
2182
            var payload = {"firewallProfile":{"profile":value}};
2183
            payload._options = _.extend({critical: false}, options);
2184
            
2185
            this.set({'pending_firewall': value});
2186
            this.set({'pending_firewall_sending': true});
2187
            this.set({'pending_firewall_from': this.get('firewallProfile')});
2188

    
2189
            var success_cb = function() {
2190
                if (callback) {
2191
                    callback();
2192
                }
2193
                self.set({'pending_firewall_sending': false});
2194
            };
2195

    
2196
            var error_cb = function() {
2197
                self.reset_pending_firewall();
2198
            }
2199
            
2200
            this.get_vm().api_call(this.get_vm().api_path() + "/action", "create", payload, success_cb, error_cb);
2201
        },
2202

    
2203
        reset_pending_firewall: function() {
2204
            this.set({'pending_firewall': false});
2205
            this.set({'pending_firewall': false});
2206
        },
2207

    
2208
        check_firewall: function() {
2209
            var firewall = this.get('firewallProfile');
2210
            var pending = this.get('pending_firewall');
2211
            var previous = this.get('pending_firewall_from');
2212
            if (previous != firewall) { this.get_vm().require_reboot() };
2213
            this.reset_pending_firewall();
2214
        }
2215
        
2216
    });
2217

    
2218
    models.NICs = models.Collection.extend({
2219
        model: models.NIC,
2220
        
2221
        add_or_update: function(nic_id, data, vm) {
2222
            var params = _.clone(data);
2223
            var vm;
2224
            params.attachment_id = params.id;
2225
            params.id = params.id + '-' + params.network_id;
2226
            params.vm_id = parseInt(NIC_REGEX.exec(nic_id)[1]);
2227

    
2228
            if (!this.get(params.id)) {
2229
                this.add(params);
2230
                var nic = this.get(params.id);
2231
                vm = nic.get_vm();
2232
                nic.get_network().decrease_connecting();
2233
                nic.bind("remove", function() {
2234
                    nic.set({"removing": 0});
2235
                    if (this.get_network()) {
2236
                        // network might got removed before nic
2237
                        nic.get_network().update_state();
2238
                    }
2239
                });
2240

    
2241
            } else {
2242
                this.get(params.id).set(params);
2243
                vm = this.get(params.id).get_vm();
2244
            }
2245
            
2246
            // vm nics changed, trigger vm update
2247
            if (vm) { vm.trigger("change", vm)};
2248
        },
2249
        
2250
        reset_nics: function(nics, filter_attr, filter_val) {
2251
            var nics_to_check = this.filter(function(nic) {
2252
                return nic.get(filter_attr) == filter_val;
2253
            });
2254
            
2255
            _.each(nics_to_check, function(nic) {
2256
                if (nics.indexOf(nic.get('id')) == -1) {
2257
                    this.remove(nic);
2258
                } else {
2259
                }
2260
            }, this);
2261
        },
2262

    
2263
        update_vm_nics: function(vm) {
2264
            var nics = vm.get('nics');
2265
            this.reset_nics(_.map(nics, function(nic, key){
2266
                return key + "-" + nic.network_id;
2267
            }), 'vm_id', vm.id);
2268

    
2269
            _.each(nics, function(val, key) {
2270
                var net = synnefo.storage.networks.get(val.network_id);
2271
                if (net && net.connected_with_nic_id(key) && vm.connected_with_nic_id(key)) {
2272
                    this.add_or_update(key, vm.get('nics')[key], vm);
2273
                }
2274
            }, this);
2275
        },
2276

    
2277
        update_net_nics: function(net) {
2278
            var nics = net.get('nics');
2279
            this.reset_nics(_.map(nics, function(nic, key){
2280
                return key + "-" + net.get('id');
2281
            }), 'network_id', net.id);
2282

    
2283
            _.each(nics, function(val, key) {
2284
                var vm = synnefo.storage.vms.get(val.vm_id);
2285
                if (vm && net.connected_with_nic_id(key) && vm.connected_with_nic_id(key)) {
2286
                    this.add_or_update(key, vm.get('nics')[key], vm);
2287
                }
2288
            }, this);
2289
        }
2290
    });
2291

    
2292
    models.PublicKey = models.Model.extend({
2293
        path: 'keys',
2294
        base_url: '/ui/userdata',
2295
        details: false,
2296
        noUpdate: true,
2297

    
2298

    
2299
        get_public_key: function() {
2300
            return cryptico.publicKeyFromString(this.get("content"));
2301
        },
2302

    
2303
        get_filename: function() {
2304
            return "{0}.pub".format(this.get("name"));
2305
        },
2306

    
2307
        identify_type: function() {
2308
            try {
2309
                var cont = snf.util.validatePublicKey(this.get("content"));
2310
                var type = cont.split(" ")[0];
2311
                return synnefo.util.publicKeyTypesMap[type];
2312
            } catch (err) { return false };
2313
        }
2314

    
2315
    })
2316
    
2317
    models.PublicKeys = models.Collection.extend({
2318
        model: models.PublicKey,
2319
        details: false,
2320
        path: 'keys',
2321
        base_url: '/ui/userdata',
2322
        noUpdate: true,
2323

    
2324
        generate_new: function(success, error) {
2325
            snf.api.sync('create', undefined, {
2326
                url: getUrl.call(this, this.base_url) + "/generate", 
2327
                success: success, 
2328
                error: error,
2329
                skip_api_error: true
2330
            });
2331
        },
2332

    
2333
        add_crypto_key: function(key, success, error, options) {
2334
            var options = options || {};
2335
            var m = new models.PublicKey();
2336

    
2337
            // guess a name
2338
            var name_tpl = "my generated public key";
2339
            var name = name_tpl;
2340
            var name_count = 1;
2341
            
2342
            while(this.filter(function(m){ return m.get("name") == name }).length > 0) {
2343
                name = name_tpl + " " + name_count;
2344
                name_count++;
2345
            }
2346
            
2347
            m.set({name: name});
2348
            m.set({content: key});
2349
            
2350
            options.success = function () { return success(m) };
2351
            options.errror = error;
2352
            options.skip_api_error = true;
2353
            
2354
            this.create(m.attributes, options);
2355
        }
2356
    })
2357
    
2358
    // storage initialization
2359
    snf.storage.images = new models.Images();
2360
    snf.storage.flavors = new models.Flavors();
2361
    snf.storage.networks = new models.Networks();
2362
    snf.storage.vms = new models.VMS();
2363
    snf.storage.keys = new models.PublicKeys();
2364
    snf.storage.nics = new models.NICs();
2365

    
2366
    //snf.storage.vms.fetch({update:true});
2367
    //snf.storage.images.fetch({update:true});
2368
    //snf.storage.flavors.fetch({update:true});
2369

    
2370
})(this);