Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (84.9 kB)

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

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

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

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

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

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

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

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

    
111
        url: function(options) {
112
            return getUrl.call(this, this.base_url) + "/" + this.id;
113
        },
114

    
115
        api_path: function(options) {
116
            return this.path + "/" + this.id;
117
        },
118

    
119
        parse: function(resp, xhr) {
120
        },
121

    
122
        remove: function(complete, error, success) {
123
            this.api_call(this.api_path(), "delete", undefined, complete, error, success);
124
        },
125

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

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

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

    
159
        initialize: function() {
160
            models.Collection.__super__.initialize.apply(this, arguments);
161
            this.api_call = _.bind(this.api.call, this);
162
        },
163

    
164
        url: function(options, method) {
165
            return getUrl.call(this, this.base_url) + (
166
                    options.details || this.details && method != 'create' ? '/detail' : '');
167
        },
168

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

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

    
197
        get_fetcher: function(interval, increase, fast, increase_after_calls, max, initial_call, params) {
198
            var fetch_params = params || {};
199
            var handler_options = {};
200

    
201
            fetch_params.skips_timeouts = true;
202
            handler_options.interval = interval;
203
            handler_options.increase = increase;
204
            handler_options.fast = fast;
205
            handler_options.increase_after_calls = increase_after_calls;
206
            handler_options.max= max;
207
            handler_options.id = "collection id";
208

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

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

    
241
        get_description: function(escape) {
242
            if (escape == undefined) { escape = true };
243
            if (escape) { return this.escape('description') || "No description available"}
244
            return this.get('description') || "No description available."
245
        },
246

    
247
        get_meta: function(key) {
248
            if (this.get('metadata') && this.get('metadata').values) {
249
                if (!this.get('metadata').values[key]) { return null }
250
                return _.escape(this.get('metadata').values[key]);
251
            } else {
252
                return null;
253
            }
254
        },
255

    
256
        get_meta_keys: function() {
257
            if (this.get('metadata') && this.get('metadata').values) {
258
                return _.keys(this.get('metadata').values);
259
            } else {
260
                return [];
261
            }
262
        },
263

    
264
        get_owner: function() {
265
            return this.get('owner') || _.keys(synnefo.config.system_images_owners)[0];
266
        },
267

    
268
        get_owner_uuid: function() {
269
            return this.get('owner_uuid');
270
        },
271

    
272
        is_system_image: function() {
273
          var owner = this.get_owner();
274
          return _.include(_.keys(synnefo.config.system_images_owners), owner)
275
        },
276

    
277
        owned_by: function(user) {
278
          if (!user) { user = synnefo.user }
279
          return user.get_username() == this.get('owner_uuid');
280
        },
281

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

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

    
302
        get_gui: function() {
303
            return this.get_meta('GUI');
304
        },
305

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

    
314
        get_sort_order: function() {
315
            return parseInt(this.get('metadata') ? this.get('metadata').values.sortorder : -1)
316
        },
317

    
318
        get_vm: function() {
319
            var vm_id = this.get("serverRef");
320
            var vm = undefined;
321
            vm = storage.vms.get(vm_id);
322
            return vm;
323
        },
324

    
325
        is_public: function() {
326
            return this.get('is_public') == undefined ? true : this.get('is_public');
327
        },
328

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

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

    
354
        supports: function(feature) {
355
            if (feature == "ssh") {
356
                return this._supports_ssh()
357
            }
358
            return false;
359
        },
360

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

    
369
                return {
370
                    path: pathinfo.path,
371
                    contents: contents,
372
                    mode: 0600,
373
                    owner: pathinfo.user
374
                }
375
            });
376
        }
377
    });
378

    
379
    // Flavor model
380
    models.Flavor = models.Model.extend({
381
        path: 'flavors',
382

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

    
387
        get_disk_size: function() {
388
            return parseInt(this.get("disk") * 1000)
389
        },
390

    
391
        get_ram_size: function() {
392
            return parseInt(this.get("ram"))
393
        },
394

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

    
403
        disk_to_bytes: function() {
404
            return parseInt(this.get("disk")) * 1024 * 1024 * 1024;
405
        },
406

    
407
        ram_to_bytes: function() {
408
            return parseInt(this.get("ram")) * 1024 * 1024;
409
        },
410

    
411
    });
412
    
413
    models.ParamsList = function(){this.initialize.apply(this, arguments)};
414
    _.extend(models.ParamsList.prototype, bb.Events, {
415

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

    
432
            var args = _.toArray(arguments);
433
            return args.splice(1);
434
        },
435

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

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

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

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

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

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

    
510
    });
511

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

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

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

    
567
        is_public: function() {
568
            return this.get("public");
569
        },
570

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

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

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

    
593
        connected_with_nic_id: function(nic_id) {
594
            return _.keys(this.get('nics')).indexOf(nic_id) > -1;
595
        },
596

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

    
602
            if (filter) {
603
                return _.filter(nics, filter);
604
            }
605
            return nics;
606
        },
607

    
608
        contains_firewalling_nics: function() {
609
            return this.get_nics(function(n){return n.get('pending_firewall')}).length
610
        },
611

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

    
617
                this.set({state:"DESTROY"});
618

    
619
                var _success = _.bind(function() {
620
                    if (success) { success() };
621
                    synnefo.storage.quotas.get('cyclades.network.private').decrease();
622
                }, this);
623
                var _error = _.bind(function() {
624
                    this.set({state: previous_state, status: previous_status})
625
                    if (error) { error() };
626
                }, this);
627

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

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

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

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

    
688
        get_connectable_vms: function() {
689
            return storage.vms.filter(function(vm){
690
                return !vm.in_error_state() && !vm.is_building();
691
            })
692
        },
693

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

    
706
            return models.Network.STATES[this.get("state")];
707
        },
708

    
709
        in_progress: function() {
710
            return models.Network.STATES_TRANSITIONS[this.get("state")] != undefined;
711
        },
712

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

    
736
    models.Network.STATES_TRANSITIONS = {
737
        'CONNECTING': ['ACTIVE'],
738
        'DISCONNECTING': ['ACTIVE'],
739
        'PENDING': ['ACTIVE'],
740
        'FIREWALLING': ['ACTIVE']
741
    }
742

    
743
    // Virtualmachine model
744
    models.VM = models.Model.extend({
745

    
746
        path: 'servers',
747
        has_status: true,
748
        initialize: function(params) {
749
            
750
            this.pending_firewalls = {};
751
            
752
            models.VM.__super__.initialize.apply(this, arguments);
753

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

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

    
786
            this.bind("change:nics", _.bind(synnefo.storage.nics.update_vm_nics, synnefo.storage.nics));
787
        },
788

    
789
        status: function(st) {
790
            if (!st) { return this.get("status")}
791
            return this.set({status:st});
792
        },
793

    
794
        set_status: function(st) {
795
            var new_state = this.state_for_api_status(st);
796
            var transition = false;
797

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

    
824
        has_diagnostics: function() {
825
            return this.get("diagnostics") && this.get("diagnostics").length;
826
        },
827

    
828
        get_progress_info: function() {
829
            // details about progress message
830
            // contains a list of diagnostic messages
831
            return this.get("status_messages");
832
        },
833

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

    
849
            var msg = messages[0];
850
            if (msg) {
851
              var message = msg.message;
852
              var message_tpl = snf.config.diagnostic_messages_tpls[msg.source];
853

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

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

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

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

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

    
956
                callback({'progress': progress, 'size': size, 'copy': size_copied})
957
            }, this));
958
        },
959

    
960
        start_stats_update: function(force_if_empty) {
961
            var prev_state = this.do_update_stats;
962

    
963
            this.do_update_stats = true;
964
            
965
            // fetcher initialized ??
966
            if (!this.stats_fetcher) {
967
                this.init_stats_intervals();
968
            }
969

    
970

    
971
            // fetcher running ???
972
            if (!this.stats_fetcher.running || !prev_state) {
973
                this.stats_fetcher.start();
974
            }
975

    
976
            if (force_if_empty && this.get("stats") == undefined) {
977
                this.update_stats(true);
978
            }
979
        },
980

    
981
        stop_stats_update: function(stop_calls) {
982
            this.do_update_stats = false;
983

    
984
            if (stop_calls) {
985
                this.stats_fetcher.stop();
986
            }
987
        },
988

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

    
1003
        // do the api call
1004
        update_stats: function(force) {
1005
            // do not update stats if flag not set
1006
            if ((!this.do_update_stats && !force) || this.updating_stats) {
1007
                return;
1008
            }
1009

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

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

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

    
1043
        unbind: function() {
1044
            models.VM.__super__.unbind.apply(this, arguments);
1045
        },
1046

    
1047
        handle_stats_error: function() {
1048
            stats = {};
1049
            _.each(['cpuBar', 'cpuTimeSeries', 'netBar', 'netTimeSeries'], function(k) {
1050
                stats[k] = false;
1051
            });
1052

    
1053
            this.set({'stats': stats});
1054
        },
1055

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

    
1067
                function check_images_loaded() {
1068
                    images_loaded++;
1069

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

    
1090
                    img.error(function() {
1091
                        images[stat + type] = false;
1092
                        check_images_loaded();
1093
                    });
1094

    
1095
                    img.attr({'src': stats[k]});
1096
                })
1097
                data.stats = stats;
1098
            }
1099

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

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

    
1121
        require_reboot: function() {
1122
            if (this.is_active()) {
1123
                this.set({'reboot_required': true});
1124
            }
1125
        },
1126
        
1127
        set_pending_action: function(data) {
1128
            this.pending_action = data;
1129
            return data;
1130
        },
1131

    
1132
        // machine has pending action
1133
        update_pending_action: function(action, force) {
1134
            this.set({pending_action: action});
1135
        },
1136

    
1137
        clear_pending_action: function() {
1138
            this.set({pending_action: undefined});
1139
        },
1140

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

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

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

    
1184
            this.api_call(url, "update", payload, complete, error);
1185
        },
1186

    
1187

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

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

    
1252
        get_meta: function(key, deflt) {
1253
            if (this.get('metadata') && this.get('metadata').values) {
1254
                if (!this.get('metadata').values[key]) { return deflt }
1255
                return _.escape(this.get('metadata').values[key]);
1256
            } else {
1257
                return deflt;
1258
            }
1259
        },
1260

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

    
1276
        get_gui: function() {
1277
            return this.get_meta('GUI');
1278
        },
1279
        
1280
        connected_to: function(net) {
1281
            return this.get('linked_to').indexOf(net.id) > -1;
1282
        },
1283

    
1284
        connected_with_nic_id: function(nic_id) {
1285
            return _.keys(this.get('nics')).indexOf(nic_id) > -1;
1286
        },
1287

    
1288
        get_nics: function(filter) {
1289
            ret = synnefo.storage.nics.filter(function(nic) {
1290
                return parseInt(nic.get('vm_id')) == this.id;
1291
            }, this);
1292

    
1293
            if (filter) {
1294
                return _.filter(ret, filter);
1295
            }
1296

    
1297
            return ret;
1298
        },
1299

    
1300
        get_net_nics: function(net_id) {
1301
            return this.get_nics(function(n){return n.get('network_id') == net_id});
1302
        },
1303

    
1304
        get_public_nic: function() {
1305
            return this.get_nics(function(n){ return n.get_network().is_public() === true })[0];
1306
        },
1307

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

    
1320
        get_nic: function(net_id) {
1321
        },
1322

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

    
1332
        get_firewall_profile: function() {
1333
            var nic = this.get_public_nic();
1334
            if (nic) {
1335
                return nic.get('firewallProfile');
1336
            }
1337
            return null;
1338
        },
1339

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

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

    
1385
        // action helper
1386
        call: function(action_name, success, error, params) {
1387
            var id_param = [this.id];
1388
            
1389
            params = params || {};
1390
            success = success || function() {};
1391
            error = error || function() {};
1392

    
1393
            var self = this;
1394

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

    
1449
                                         },  
1450
                                         error, 'destroy', params);
1451
                    break;
1452
                default:
1453
                    throw "Invalid VM action ("+action_name+")";
1454
            }
1455
        },
1456
        
1457
        __make_api_call: function(url, method, data, success, error, action, extra_params) {
1458
            var self = this;
1459
            error = error || function(){};
1460
            success = success || function(){};
1461

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

    
1479
        handle_action_succeed: function() {
1480
            this.trigger("action:success", arguments);
1481
        },
1482
        
1483
        reset_action_error: function() {
1484
            this.action_error = false;
1485
            this.trigger("action:fail:reset", this.action_error);
1486
        },
1487

    
1488
        handle_action_fail: function() {
1489
            this.action_error = arguments;
1490
            this.trigger("action:fail", arguments);
1491
        },
1492

    
1493
        get_action_url: function(name) {
1494
            return this.url() + "/action";
1495
        },
1496

    
1497
        get_diagnostics_url: function() {
1498
            return this.url() + "/diagnostics";
1499
        },
1500

    
1501
        get_connection_info: function(host_os, success, error) {
1502
            var url = "/machines/connect";
1503
            params = {
1504
                ip_address: this.get_public_nic().get('ipv4'),
1505
                hostname: this.get_hostname(),
1506
                os: this.get_os(),
1507
                host_os: host_os,
1508
                srv: this.id
1509
            }
1510

    
1511
            url = url + "?" + $.param(params);
1512

    
1513
            var ajax = snf.api.sync("read", undefined, { url: url, 
1514
                                                         error:error, 
1515
                                                         success:success, 
1516
                                                         handles_error:1});
1517
        }
1518
    })
1519
    
1520
    models.VM.ACTIONS = [
1521
        'start',
1522
        'shutdown',
1523
        'reboot',
1524
        'console',
1525
        'destroy'
1526
    ]
1527

    
1528
    models.VM.AVAILABLE_ACTIONS = {
1529
        'UNKNWON'       : ['destroy'],
1530
        'BUILD'         : ['destroy'],
1531
        'REBOOT'        : ['shutdown', 'destroy', 'console'],
1532
        'STOPPED'       : ['start', 'destroy'],
1533
        'ACTIVE'        : ['shutdown', 'destroy', 'reboot', 'console'],
1534
        'ERROR'         : ['destroy'],
1535
        'DELETED'        : [],
1536
        'DESTROY'       : [],
1537
        'BUILD_INIT'    : ['destroy'],
1538
        'BUILD_COPY'    : ['destroy'],
1539
        'BUILD_FINAL'   : ['destroy'],
1540
        'SHUTDOWN'      : ['destroy'],
1541
        'START'         : [],
1542
        'CONNECT'       : [],
1543
        'DISCONNECT'    : []
1544
    }
1545

    
1546
    // api status values
1547
    models.VM.STATUSES = [
1548
        'UNKNWON',
1549
        'BUILD',
1550
        'REBOOT',
1551
        'STOPPED',
1552
        'ACTIVE',
1553
        'ERROR',
1554
        'DELETED'
1555
    ]
1556

    
1557
    // api status values
1558
    models.VM.CONNECT_STATES = [
1559
        'ACTIVE',
1560
        'REBOOT',
1561
        'SHUTDOWN'
1562
    ]
1563

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

    
1590
    models.VM.TRANSITION_STATES = [
1591
        'DESTROY',
1592
        'SHUTDOWN',
1593
        'START',
1594
        'REBOOT',
1595
        'BUILD'
1596
    ]
1597

    
1598
    models.VM.ACTIVE_STATES = [
1599
        'BUILD', 'REBOOT', 'ACTIVE',
1600
        'BUILD_INIT', 'BUILD_COPY', 'BUILD_FINAL',
1601
        'SHUTDOWN', 'CONNECT', 'DISCONNECT'
1602
    ]
1603

    
1604
    models.VM.BUILDING_STATES = [
1605
        'BUILD', 'BUILD_INIT', 'BUILD_COPY', 'BUILD_FINAL'
1606
    ]
1607

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

    
1623
        add: function() {
1624
            ret = models.Networks.__super__.add.apply(this, arguments);
1625
            // update nics after each network addition
1626
            ret.each(function(r){
1627
                synnefo.storage.nics.update_net_nics(r);
1628
            });
1629
        },
1630

    
1631
        reset_pending_actions: function() {
1632
            this.each(function(net) {
1633
                net.get("actions").reset();
1634
            });
1635
        },
1636

    
1637
        do_all_pending_actions: function() {
1638
            this.each(function(net) {
1639
                net.do_all_pending_actions();
1640
            })
1641
        },
1642

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

    
1657
                  if (vm_id !== undefined && nic_index !== undefined) {
1658
                      data['nics'][nic_id] = {
1659
                          'vm_id': vm_id, 
1660
                          'index': nic_index, 
1661
                          'id': nic_id
1662
                      };
1663
                      if (data['linked_to'].indexOf(vm_id) == -1) {
1664
                        data['linked_to'].push(vm_id);
1665
                      }
1666
                  }
1667
                });
1668
            }
1669

    
1670
            if (data.status == "DELETED" && !this.get(parseInt(data.id))) {
1671
              return false;
1672
            }
1673
            return data;
1674
        },
1675

    
1676
        create: function (name, type, cidr, dhcp, callback) {
1677
            var params = {
1678
                network:{
1679
                    name:name
1680
                }
1681
            };
1682

    
1683
            if (type) {
1684
                params.network.type = type;
1685
            }
1686
            if (cidr) {
1687
                params.network.cidr = cidr;
1688
            }
1689
            if (dhcp) {
1690
                params.network.dhcp = dhcp;
1691
            }
1692

    
1693
            if (dhcp === false) {
1694
                params.network.dhcp = false;
1695
            }
1696
            
1697
            var cb = function() {
1698
              callback();
1699
              synnefo.storage.quotas.get('cyclades.network.private').increase();
1700
            }
1701
            return this.api_call(this.path, "create", params, cb);
1702
        },
1703

    
1704
        get_public: function(){
1705
          return this.filter(function(n){return n.get('public')});
1706
        }
1707
    })
1708

    
1709
    models.Images = models.Collection.extend({
1710
        model: models.Image,
1711
        path: 'images',
1712
        details: true,
1713
        noUpdate: true,
1714
        supportIncUpdates: false,
1715
        meta_keys_as_attrs: ["OS", "description", "kernel", "size", "GUI"],
1716
        meta_labels: {},
1717
        read_method: 'read',
1718

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

    
1764
        _read_image_from_request: function(image, msg, xhr) {
1765
            return image.image;
1766
        },
1767

    
1768
        parse: function (resp, xhr) {
1769
            var parsed = _.map(resp.images.values, _.bind(this.parse_meta, this));
1770
            parsed = this.fill_owners(parsed);
1771
            return parsed;
1772
        },
1773

    
1774
        fill_owners: function(images) {
1775
            // do translate uuid->displayname if needed
1776
            // store display name in owner attribute for compatibility
1777
            var uuids = [];
1778

    
1779
            var images = _.map(images, function(img, index) {
1780
                if (synnefo.config.translate_uuids) {
1781
                    uuids.push(img['owner']);
1782
                }
1783
                img['owner_uuid'] = img['owner'];
1784
                return img;
1785
            });
1786
            
1787
            if (uuids.length > 0) {
1788
                var handle_results = function(data) {
1789
                    _.each(images, function (img) {
1790
                        img['owner'] = data.uuid_catalog[img['owner_uuid']];
1791
                    });
1792
                }
1793
                // notice the async false
1794
                var uuid_map = this.translate_uuids(uuids, false, 
1795
                                                    handle_results)
1796
            }
1797
            return images;
1798
        },
1799

    
1800
        translate_uuids: function(uuids, async, cb) {
1801
            var url = synnefo.config.user_catalog_url;
1802
            var data = JSON.stringify({'uuids': uuids});
1803
          
1804
            // post to user_catalogs api
1805
            snf.api.sync('create', undefined, {
1806
                url: url,
1807
                data: data,
1808
                async: async,
1809
                success:  cb
1810
            });
1811
        },
1812

    
1813
        get_meta_key: function(img, key) {
1814
            if (img.metadata && img.metadata.values && img.metadata.values[key]) {
1815
                return _.escape(img.metadata.values[key]);
1816
            }
1817
            return undefined;
1818
        },
1819

    
1820
        comparator: function(img) {
1821
            return -img.get_sort_order("sortorder") || 1000 * img.id;
1822
        },
1823

    
1824
        parse_meta: function(img) {
1825
            _.each(this.meta_keys_as_attrs, _.bind(function(key){
1826
                if (img[key]) { return };
1827
                img[key] = this.get_meta_key(img, key) || "";
1828
            }, this));
1829
            return img;
1830
        },
1831

    
1832
        active: function() {
1833
            return this.filter(function(img){return img.get('status') != "DELETED"});
1834
        },
1835

    
1836
        predefined: function() {
1837
            return _.filter(this.active(), function(i) { return !i.get("serverRef")});
1838
        },
1839
        
1840
        fetch_for_type: function(type, complete, error) {
1841
            this.fetch({update:true, 
1842
                        success: complete, 
1843
                        error: error, 
1844
                        skip_api_error: true });
1845
        },
1846
        
1847
        get_images_for_type: function(type) {
1848
            if (this['get_{0}_images'.format(type)]) {
1849
                return this['get_{0}_images'.format(type)]();
1850
            }
1851

    
1852
            return this.active();
1853
        },
1854

    
1855
        update_images_for_type: function(type, onStart, onComplete, onError, force_load) {
1856
            var load = false;
1857
            error = onError || function() {};
1858
            function complete(collection) { 
1859
                onComplete(collection.get_images_for_type(type)); 
1860
            }
1861
            
1862
            // do we need to fetch/update current collection entries
1863
            if (load) {
1864
                onStart();
1865
                this.fetch_for_type(type, complete, error);
1866
            } else {
1867
                // fallback to complete
1868
                complete(this);
1869
            }
1870
        }
1871
    })
1872

    
1873
    models.Flavors = models.Collection.extend({
1874
        model: models.Flavor,
1875
        path: 'flavors',
1876
        details: true,
1877
        noUpdate: true,
1878
        supportIncUpdates: false,
1879
        // update collection model with id passed
1880
        // making a direct call to the flavor
1881
        // api url
1882
        update_unknown_id: function(id, callback) {
1883
            var url = getUrl.call(this) + "/" + id;
1884
            this.api_call(this.path + "/" + id, "read", {_options:{async:false, skip_api_error:true}}, undefined, 
1885
            _.bind(function() {
1886
                this.add({id:id, cpu:"Unknown", ram:"Unknown", disk:"Unknown", name: "Unknown", status:"DELETED"})
1887
            }, this), _.bind(function(flv) {
1888
                if (!flv.flavor.status) { flv.flavor.status = "DELETED" };
1889
                this.add(flv.flavor);
1890
            }, this));
1891
        },
1892

    
1893
        parse: function (resp, xhr) {
1894
            return _.map(resp.flavors.values, function(o) { o.disk_template = o['SNF:disk_template']; return o});
1895
        },
1896

    
1897
        comparator: function(flv) {
1898
            return flv.get("disk") * flv.get("cpu") * flv.get("ram");
1899
        },
1900

    
1901
        unavailable_values_for_quotas: function(quotas, flavors) {
1902
            var flavors = flavors || this.active();
1903
            var index = {cpu:[], disk:[], ram:[]};
1904
            
1905
            _.each(flavors, function(el) {
1906

    
1907
                var disk_available = quotas['disk'];
1908
                var disk_size = el.get_disk_size();
1909
                if (index.disk.indexOf(disk_size) == -1) {
1910
                  var disk = el.disk_to_bytes();
1911
                  if (disk > disk_available) {
1912
                    index.disk.push(disk_size);
1913
                  }
1914
                }
1915

    
1916
                var ram_available = quotas['ram'];
1917
                var ram_size = el.get_ram_size();
1918
                if (index.ram.indexOf(ram_size) == -1) {
1919
                  var ram = el.ram_to_bytes();
1920
                  if (ram > ram_available) {
1921
                    index.ram.push(el.get('ram'))
1922
                  }
1923
                }
1924

    
1925
                var cpu = el.get('cpu');
1926
                var cpu_available = quotas['cpu'];
1927
                if (index.ram.indexOf(cpu) == -1) {
1928
                  if (cpu > cpu_available) {
1929
                    index.cpu.push(el.get('cpu'))
1930
                  }
1931
                }
1932
            });
1933
            return index;
1934
        },
1935

    
1936
        unavailable_values_for_image: function(img, flavors) {
1937
            var flavors = flavors || this.active();
1938
            var size = img.get_size();
1939
            
1940
            var index = {cpu:[], disk:[], ram:[]};
1941

    
1942
            _.each(this.active(), function(el) {
1943
                var img_size = size;
1944
                var flv_size = el.get_disk_size();
1945
                if (flv_size < img_size) {
1946
                    if (index.disk.indexOf(flv_size) == -1) {
1947
                        index.disk.push(flv_size);
1948
                    }
1949
                };
1950
            });
1951
            
1952
            return index;
1953
        },
1954

    
1955
        get_flavor: function(cpu, mem, disk, disk_template, filter_list) {
1956
            if (!filter_list) { filter_list = this.models };
1957
            
1958
            return this.select(function(flv){
1959
                if (flv.get("cpu") == cpu + "" &&
1960
                   flv.get("ram") == mem + "" &&
1961
                   flv.get("disk") == disk + "" &&
1962
                   flv.get("disk_template") == disk_template &&
1963
                   filter_list.indexOf(flv) > -1) { return true; }
1964
            })[0];
1965
        },
1966
        
1967
        get_data: function(lst) {
1968
            var data = {'cpu': [], 'mem':[], 'disk':[]};
1969

    
1970
            _.each(lst, function(flv) {
1971
                if (data.cpu.indexOf(flv.get("cpu")) == -1) {
1972
                    data.cpu.push(flv.get("cpu"));
1973
                }
1974
                if (data.mem.indexOf(flv.get("ram")) == -1) {
1975
                    data.mem.push(flv.get("ram"));
1976
                }
1977
                if (data.disk.indexOf(flv.get("disk")) == -1) {
1978
                    data.disk.push(flv.get("disk"));
1979
                }
1980
            })
1981
            
1982
            return data;
1983
        },
1984

    
1985
        active: function() {
1986
            return this.filter(function(flv){return flv.get('status') != "DELETED"});
1987
        }
1988
            
1989
    })
1990

    
1991
    models.VMS = models.Collection.extend({
1992
        model: models.VM,
1993
        path: 'servers',
1994
        details: true,
1995
        copy_image_meta: true,
1996

    
1997
        parse: function (resp, xhr) {
1998
            var data = resp;
1999
            if (!resp) { return [] };
2000
            data = _.filter(_.map(resp.servers.values, _.bind(this.parse_vm_api_data, this)), function(v){return v});
2001
            return data;
2002
        },
2003

    
2004
        parse_vm_api_data: function(data) {
2005
            // do not add non existing DELETED entries
2006
            if (data.status && data.status == "DELETED") {
2007
                if (!this.get(data.id)) {
2008
                    return false;
2009
                }
2010
            }
2011

    
2012
            // OS attribute
2013
            if (this.has_meta(data)) {
2014
                data['OS'] = data.metadata.values.OS || snf.config.unknown_os;
2015
            }
2016
            
2017
            if (!data.diagnostics) {
2018
                data.diagnostics = [];
2019
            }
2020

    
2021
            // network metadata
2022
            data['firewalls'] = {};
2023
            data['nics'] = {};
2024
            data['linked_to'] = [];
2025

    
2026
            if (data['attachments'] && data['attachments'].values) {
2027
                var nics = data['attachments'].values;
2028
                _.each(nics, function(nic) {
2029
                    var net_id = nic.network_id;
2030
                    var index = parseInt(NIC_REGEX.exec(nic.id)[2]);
2031
                    if (data['linked_to'].indexOf(net_id) == -1) {
2032
                        data['linked_to'].push(net_id);
2033
                    }
2034

    
2035
                    data['nics'][nic.id] = nic;
2036
                })
2037
            }
2038
            
2039
            // if vm has no metadata, no metadata object
2040
            // is in json response, reset it to force
2041
            // value update
2042
            if (!data['metadata']) {
2043
                data['metadata'] = {values:{}};
2044
            }
2045

    
2046
            return data;
2047
        },
2048

    
2049
        add: function() {
2050
            ret = models.VMS.__super__.add.apply(this, arguments);
2051
            ret.each(function(r){
2052
                synnefo.storage.nics.update_vm_nics(r);
2053
            });
2054
        },
2055
        
2056
        get_reboot_required: function() {
2057
            return this.filter(function(vm){return vm.get("reboot_required") == true})
2058
        },
2059

    
2060
        has_pending_actions: function() {
2061
            return this.filter(function(vm){return vm.pending_action}).length > 0;
2062
        },
2063

    
2064
        reset_pending_actions: function() {
2065
            this.each(function(vm) {
2066
                vm.clear_pending_action();
2067
            })
2068
        },
2069

    
2070
        do_all_pending_actions: function(success, error) {
2071
            this.each(function(vm) {
2072
                if (vm.has_pending_action()) {
2073
                    vm.call(vm.pending_action, success, error);
2074
                    vm.clear_pending_action();
2075
                }
2076
            })
2077
        },
2078
        
2079
        do_all_reboots: function(success, error) {
2080
            this.each(function(vm) {
2081
                if (vm.get("reboot_required")) {
2082
                    vm.call("reboot", success, error);
2083
                }
2084
            });
2085
        },
2086

    
2087
        reset_reboot_required: function() {
2088
            this.each(function(vm) {
2089
                vm.set({'reboot_required': undefined});
2090
            })
2091
        },
2092
        
2093
        stop_stats_update: function(exclude) {
2094
            var exclude = exclude || [];
2095
            this.each(function(vm) {
2096
                if (exclude.indexOf(vm) > -1) {
2097
                    return;
2098
                }
2099
                vm.stop_stats_update();
2100
            })
2101
        },
2102
        
2103
        has_meta: function(vm_data) {
2104
            return vm_data.metadata && vm_data.metadata.values
2105
        },
2106

    
2107
        has_addresses: function(vm_data) {
2108
            return vm_data.metadata && vm_data.metadata.values
2109
        },
2110

    
2111
        create: function (name, image, flavor, meta, extra, callback) {
2112

    
2113
            if (this.copy_image_meta) {
2114
                if (synnefo.config.vm_image_common_metadata) {
2115
                    _.each(synnefo.config.vm_image_common_metadata, 
2116
                        function(key){
2117
                            if (image.get_meta(key)) {
2118
                                meta[key] = image.get_meta(key);
2119
                            }
2120
                    });
2121
                }
2122

    
2123
                if (image.get("OS")) {
2124
                    meta['OS'] = image.get("OS");
2125
                }
2126
            }
2127
            
2128
            opts = {name: name, imageRef: image.id, flavorRef: flavor.id, 
2129
                    metadata:meta}
2130
            opts = _.extend(opts, extra);
2131
            
2132
            var cb = function(data) {
2133
              synnefo.storage.quotas.get('cyclades.vm').increase();
2134
              callback(data);
2135
            }
2136

    
2137
            this.api_call(this.path, "create", {'server': opts}, undefined, 
2138
                          undefined, cb, {critical: true});
2139
        },
2140

    
2141
        load_missing_images: function(callback) {
2142
          var missing_ids = [];
2143
          var resolved = 0;
2144

    
2145
          // fill missing_ids
2146
          this.each(function(el) {
2147
            var imgid = el.get("imageRef");
2148
            var existing = synnefo.storage.images.get(imgid);
2149
            if (!existing && missing_ids.indexOf(imgid) == -1) {
2150
              missing_ids.push(imgid);
2151
            }
2152
          });
2153
          var check = function() {
2154
            // once all missing ids where resolved continue calling the 
2155
            // callback
2156
            resolved++;
2157
            if (resolved == missing_ids.length) {
2158
              callback(missing_ids)
2159
            }
2160
          }
2161
          if (missing_ids.length == 0) {
2162
            callback(missing_ids);
2163
            return;
2164
          }
2165
          // start resolving missing image ids
2166
          _(missing_ids).each(function(imgid){
2167
            synnefo.storage.images.update_unknown_id(imgid, check);
2168
          });
2169
        }
2170
    })
2171
    
2172
    models.NIC = models.Model.extend({
2173
        
2174
        initialize: function() {
2175
            models.NIC.__super__.initialize.apply(this, arguments);
2176
            this.pending_for_firewall = false;
2177
            this.bind("change:firewallProfile", _.bind(this.check_firewall, this));
2178
            this.bind("change:pending_firewall", function(nic) {
2179
                nic.get_network().update_state();
2180
            });
2181
            this.get_vm().bind("remove", function(){
2182
                try {
2183
                    this.collection.remove(this);
2184
                } catch (err) {};
2185
            }, this);
2186
            this.get_network().bind("remove", function(){
2187
                try {
2188
                    this.collection.remove(this);
2189
                } catch (err) {};
2190
            }, this);
2191

    
2192
        },
2193

    
2194
        get_vm: function() {
2195
            return synnefo.storage.vms.get(parseInt(this.get('vm_id')));
2196
        },
2197

    
2198
        get_network: function() {
2199
            return synnefo.storage.networks.get(this.get('network_id'));
2200
        },
2201

    
2202
        get_v6_address: function() {
2203
            return this.get("ipv6");
2204
        },
2205

    
2206
        get_v4_address: function() {
2207
            return this.get("ipv4");
2208
        },
2209

    
2210
        set_firewall: function(value, callback, error, options) {
2211
            var net_id = this.get('network_id');
2212
            var self = this;
2213

    
2214
            // api call data
2215
            var payload = {"firewallProfile":{"profile":value}};
2216
            payload._options = _.extend({critical: false}, options);
2217
            
2218
            this.set({'pending_firewall': value});
2219
            this.set({'pending_firewall_sending': true});
2220
            this.set({'pending_firewall_from': this.get('firewallProfile')});
2221

    
2222
            var success_cb = function() {
2223
                if (callback) {
2224
                    callback();
2225
                }
2226
                self.set({'pending_firewall_sending': false});
2227
            };
2228

    
2229
            var error_cb = function() {
2230
                self.reset_pending_firewall();
2231
            }
2232
            
2233
            this.get_vm().api_call(this.get_vm().api_path() + "/action", "create", payload, success_cb, error_cb);
2234
        },
2235

    
2236
        reset_pending_firewall: function() {
2237
            this.set({'pending_firewall': false});
2238
            this.set({'pending_firewall': false});
2239
        },
2240

    
2241
        check_firewall: function() {
2242
            var firewall = this.get('firewallProfile');
2243
            var pending = this.get('pending_firewall');
2244
            var previous = this.get('pending_firewall_from');
2245
            if (previous != firewall) { this.get_vm().require_reboot() };
2246
            this.reset_pending_firewall();
2247
        }
2248
        
2249
    });
2250

    
2251
    models.NICs = models.Collection.extend({
2252
        model: models.NIC,
2253
        
2254
        add_or_update: function(nic_id, data, vm) {
2255
            var params = _.clone(data);
2256
            var vm;
2257
            params.attachment_id = params.id;
2258
            params.id = params.id + '-' + params.network_id;
2259
            params.vm_id = parseInt(NIC_REGEX.exec(nic_id)[1]);
2260

    
2261
            if (!this.get(params.id)) {
2262
                this.add(params);
2263
                var nic = this.get(params.id);
2264
                vm = nic.get_vm();
2265
                nic.get_network().decrease_connecting();
2266
                nic.bind("remove", function() {
2267
                    nic.set({"removing": 0});
2268
                    if (this.get_network()) {
2269
                        // network might got removed before nic
2270
                        nic.get_network().update_state();
2271
                    }
2272
                });
2273

    
2274
            } else {
2275
                this.get(params.id).set(params);
2276
                vm = this.get(params.id).get_vm();
2277
            }
2278
            
2279
            // vm nics changed, trigger vm update
2280
            if (vm) { vm.trigger("change", vm)};
2281
        },
2282
        
2283
        reset_nics: function(nics, filter_attr, filter_val) {
2284
            var nics_to_check = this.filter(function(nic) {
2285
                return nic.get(filter_attr) == filter_val;
2286
            });
2287
            
2288
            _.each(nics_to_check, function(nic) {
2289
                if (nics.indexOf(nic.get('id')) == -1) {
2290
                    this.remove(nic);
2291
                } else {
2292
                }
2293
            }, this);
2294
        },
2295

    
2296
        update_vm_nics: function(vm) {
2297
            var nics = vm.get('nics');
2298
            this.reset_nics(_.map(nics, function(nic, key){
2299
                return key + "-" + nic.network_id;
2300
            }), 'vm_id', vm.id);
2301

    
2302
            _.each(nics, function(val, key) {
2303
                var net = synnefo.storage.networks.get(val.network_id);
2304
                if (net && net.connected_with_nic_id(key) && vm.connected_with_nic_id(key)) {
2305
                    this.add_or_update(key, vm.get('nics')[key], vm);
2306
                }
2307
            }, this);
2308
        },
2309

    
2310
        update_net_nics: function(net) {
2311
            var nics = net.get('nics');
2312
            this.reset_nics(_.map(nics, function(nic, key){
2313
                return key + "-" + net.get('id');
2314
            }), 'network_id', net.id);
2315

    
2316
            _.each(nics, function(val, key) {
2317
                var vm = synnefo.storage.vms.get(val.vm_id);
2318
                if (vm && net.connected_with_nic_id(key) && vm.connected_with_nic_id(key)) {
2319
                    this.add_or_update(key, vm.get('nics')[key], vm);
2320
                }
2321
            }, this);
2322
        }
2323
    });
2324

    
2325
    models.PublicKey = models.Model.extend({
2326
        path: 'keys',
2327
        api_type: 'userdata',
2328
        details: false,
2329
        noUpdate: true,
2330

    
2331

    
2332
        get_public_key: function() {
2333
            return cryptico.publicKeyFromString(this.get("content"));
2334
        },
2335

    
2336
        get_filename: function() {
2337
            return "{0}.pub".format(this.get("name"));
2338
        },
2339

    
2340
        identify_type: function() {
2341
            try {
2342
                var cont = snf.util.validatePublicKey(this.get("content"));
2343
                var type = cont.split(" ")[0];
2344
                return synnefo.util.publicKeyTypesMap[type];
2345
            } catch (err) { return false };
2346
        }
2347

    
2348
    })
2349
    
2350
    models.PublicKeys = models.Collection.extend({
2351
        model: models.PublicKey,
2352
        details: false,
2353
        path: 'keys',
2354
        api_type: 'userdata',
2355
        noUpdate: true,
2356

    
2357
        generate_new: function(success, error) {
2358
            snf.api.sync('create', undefined, {
2359
                url: getUrl.call(this, this.base_url) + "/generate", 
2360
                success: success, 
2361
                error: error,
2362
                skip_api_error: true
2363
            });
2364
        },
2365

    
2366
        add_crypto_key: function(key, success, error, options) {
2367
            var options = options || {};
2368
            var m = new models.PublicKey();
2369

    
2370
            // guess a name
2371
            var name_tpl = "my generated public key";
2372
            var name = name_tpl;
2373
            var name_count = 1;
2374
            
2375
            while(this.filter(function(m){ return m.get("name") == name }).length > 0) {
2376
                name = name_tpl + " " + name_count;
2377
                name_count++;
2378
            }
2379
            
2380
            m.set({name: name});
2381
            m.set({content: key});
2382
            
2383
            options.success = function () { return success(m) };
2384
            options.errror = error;
2385
            options.skip_api_error = true;
2386
            
2387
            this.create(m.attributes, options);
2388
        }
2389
    });
2390

    
2391
  
2392
    models.Quota = models.Model.extend({
2393

    
2394
        initialize: function() {
2395
            models.Quota.__super__.initialize.apply(this, arguments);
2396
            this.bind("change", this.check, this);
2397
            this.check();
2398
        },
2399
        
2400
        check: function() {
2401
            var usage, limit;
2402
            usage = this.get('usage');
2403
            limit = this.get('limit');
2404
            if (usage >= limit) {
2405
                this.trigger("available");
2406
            } else {
2407
                this.trigger("unavailable");
2408
            }
2409
        },
2410

    
2411
        increase: function(val) {
2412
            if (val === undefined) { val = 1};
2413
            this.set({'usage': this.get('usage') + val})
2414
        },
2415

    
2416
        decrease: function(val) {
2417
            if (val === undefined) { val = 1};
2418
            this.set({'usage': this.get('usage') - val})
2419
        },
2420

    
2421
        can_consume: function() {
2422
            var usage, limit;
2423
            usage = this.get('usage');
2424
            limit = this.get('limit');
2425
            if (usage >= limit) {
2426
                return false
2427
            } else {
2428
                return true
2429
            }
2430
        },
2431
        
2432
        is_bytes: function() {
2433
            return this.get('resource').get('unit') == 'bytes';
2434
        },
2435
        
2436
        get_available: function() {
2437
            var value = this.get('limit') - this.get('usage');
2438
            if (value < 0) { return value }
2439
            return value
2440
        },
2441

    
2442
        get_readable: function(key) {
2443
            var value;
2444
            if (key == 'available') {
2445
                value = this.get_available();
2446
            } else {
2447
                value = this.get(key)
2448
            }
2449
            if (!this.is_bytes()) {
2450
              return value + "";
2451
            }
2452
            return snf.util.readablizeBytes(value);
2453
        }
2454
    });
2455

    
2456
    models.Quotas = models.Collection.extend({
2457
        model: models.Quota,
2458
        api_type: 'accounts',
2459
        path: 'quotas',
2460
        parse: function(resp) {
2461
            return _.map(resp.system, function(value, key) {
2462
                var available = (value.limit - value.usage) || 0;
2463
                return _.extend(value, {'name': key, 'id': key, 
2464
                          'available': available,
2465
                          'resource': snf.storage.resources.get(key)});
2466
            })
2467
        }
2468
    })
2469

    
2470
    models.Resource = models.Model.extend({
2471
        api_type: 'accounts',
2472
        path: 'resources'
2473
    });
2474

    
2475
    models.Resources = models.Collection.extend({
2476
        api_type: 'accounts',
2477
        path: 'resources',
2478
        model: models.Network,
2479

    
2480
        parse: function(resp) {
2481
            return _.map(resp, function(value, key) {
2482
                return _.extend(value, {'name': key, 'id': key});
2483
            })
2484
        }
2485
    });
2486
    
2487
    // storage initialization
2488
    snf.storage.images = new models.Images();
2489
    snf.storage.flavors = new models.Flavors();
2490
    snf.storage.networks = new models.Networks();
2491
    snf.storage.vms = new models.VMS();
2492
    snf.storage.keys = new models.PublicKeys();
2493
    snf.storage.nics = new models.NICs();
2494
    snf.storage.resources = new models.Resources();
2495
    snf.storage.quotas = new models.Quotas();
2496

    
2497
})(this);