Statistics
| Branch: | Tag: | Revision:

root / ui / static / snf / js / models.js @ 9ffd10ce

History | View | Annotate | Download (52.1 kB)

1
;(function(root){
2
    
3
    // root
4
    var root = root;
5
    
6
    // setup namepsaces
7
    var snf = root.synnefo = root.synnefo || {};
8
    var models = snf.models = snf.models || {}
9
    var storage = snf.storage = snf.storage || {};
10
    var util = snf.util = snf.util || {};
11

    
12
    // shortcuts
13
    var bb = root.Backbone;
14
    var slice = Array.prototype.slice
15

    
16
    // logging
17
    var logger = new snf.logging.logger("SNF-MODELS");
18
    var debug = _.bind(logger.debug, logger);
19
    
20
    // get url helper
21
    var getUrl = function() {
22
        return snf.config.api_url + "/" + this.path;
23
    }
24
    
25
    // i18n
26
    BUILDING_MESSAGES = window.BUILDING_MESSAGES || {'INIT': 'init', 'COPY': '{0}, {1}, {2}', 'FINAL': 'final'};
27

    
28
    // Base object for all our models
29
    models.Model = bb.Model.extend({
30
        sync: snf.api.sync,
31
        api: snf.api,
32
        has_status: false,
33

    
34
        initialize: function() {
35
            if (this.has_status) {
36
                this.bind("change:status", this.handle_remove);
37
                this.handle_remove();
38
            }
39
            models.Model.__super__.initialize.apply(this, arguments)
40
        },
41

    
42
        handle_remove: function() {
43
            if (this.get("status") == 'DELETED') {
44
                if (this.collection) {
45
                    try { this.clear_pending_action();} catch (err) {};
46
                    try { this.reset_pending_actions();} catch (err) {};
47
                    try { this.stop_stats_update();} catch (err) {};
48
                    this.collection.remove(this.id);
49
                }
50
            }
51
        },
52
        
53
        // custom set method to allow submodels to use
54
        // set_<attr> methods for handling the value of each
55
        // attribute and overriding the default set method
56
        // for specific parameters
57
        set: function(params, options) {
58
            _.each(params, _.bind(function(value, key){
59
                if (this["set_" + key]) {
60
                    params[key] = this["set_" + key](value);
61
                }
62
            }, this))
63
            var ret = bb.Model.prototype.set.call(this, params, options);
64
            return ret;
65
        },
66

    
67
        url: function(options) {
68
            return getUrl.call(this) + "/" + this.id;
69
        },
70

    
71
        api_path: function(options) {
72
            return this.path + "/" + this.id;
73
        },
74

    
75
        parse: function(resp, xhr) {
76
            return resp.server;
77
        },
78

    
79
        remove: function() {
80
            this.api.call(this.api_path(), "delete");
81
        },
82

    
83
        changedKeys: function() {
84
            return _.keys(this.changedAttributes() || {});
85
        },
86

    
87
        hasOnlyChange: function(keys) {
88
            var ret = false;
89
            _.each(keys, _.bind(function(key) {
90
                if (this.changedKeys().length == 1 && this.changedKeys().indexOf(key) > -1) { ret = true};
91
            }, this));
92
            return ret;
93
        }
94

    
95
    })
96
    
97
    // Base object for all our model collections
98
    models.Collection = bb.Collection.extend({
99
        sync: snf.api.sync,
100
        api: snf.api,
101

    
102
        url: function(options) {
103
            return getUrl.call(this) + (options.details || this.details ? '/detail' : '');
104
        },
105

    
106
        fetch: function(options) {
107
            // default to update
108
            if (!this.noUpdate) {
109
                if (!options) { options = {} };
110
                if (options.update === undefined) { options.update = true };
111
                if (!options.removeMissing && options.refresh) { options.removeMissing = true };
112
            }
113
            // custom event foreach fetch
114
            return bb.Collection.prototype.fetch.call(this, options)
115
        },
116

    
117
        get_fetcher: function(timeout, fast, limit, initial, params) {
118
            var fetch_params = params || {};
119
            fetch_params.skips_timeouts = true;
120

    
121
            var timeout = parseInt(timeout);
122
            var fast = fast || 1000;
123
            var limit = limit;
124
            var initial_call = initial || true;
125
            
126
            var last_ajax = undefined;
127
            var cb = _.bind(function() {
128
                // clone to avoid referenced objects
129
                var params = _.clone(fetch_params);
130
                updater._ajax = last_ajax;
131
                if (last_ajax) {
132
                    last_ajax.abort();
133
                }
134
                last_ajax = this.fetch(params);
135
            }, this);
136
            var updater = new snf.api.updateHandler({'callback': cb, timeout:timeout, 
137
                                                    fast:fast, limit:limit, 
138
                                                    call_on_start:initial_call});
139

    
140
            snf.api.bind("call", _.throttle(_.bind(function(){ updater.faster(true)}, this)), 1000);
141
            return updater;
142
        }
143
    });
144
    
145
    // Image model
146
    models.Image = models.Model.extend({
147
        path: 'images',
148

    
149
        get_size: function() {
150
            return parseInt(this.get('metadata') ? this.get('metadata').values.size : -1)
151
        },
152

    
153
        get_os: function() {
154
            return this.get("OS");
155
        },
156

    
157
        get_sort_order: function() {
158
            return parseInt(this.get('metadata') ? this.get('metadata').values.sortorder : -1)
159
        }
160
    });
161

    
162
    // Flavor model
163
    models.Flavor = models.Model.extend({
164
        path: 'flavors',
165

    
166
        details_string: function() {
167
            return "{0} CPU, {1}MB, {2}GB".format(this.get('cpu'), this.get('ram'), this.get('disk'));
168
        },
169

    
170
        get_disk_size: function() {
171
            return parseInt(this.get("disk") * 1000)
172
        }
173

    
174
    });
175
    
176
    //network vms list helper
177
    var NetworkVMSList = function() {
178
        this.initialize = function() {
179
            this.vms = [];
180
            this.pending = [];
181
            this.pending_for_removal = [];
182
        }
183
        
184
        this.add_pending_for_remove = function(vm_id) {
185
            if (this.pending_for_removal.indexOf(vm_id) == -1) {
186
                this.pending_for_removal.push(vm_id);
187
            }
188

    
189
            if (this.pending_for_removal.length) {
190
                this.trigger("pending:remove:add");
191
            }
192
        },
193

    
194
        this.add_pending = function(vm_id) {
195
            if (this.pending.indexOf(vm_id) == -1) {
196
                this.pending[this.pending.length] = vm_id;
197
            }
198

    
199
            if (this.pending.length) {
200
                this.trigger("pending:add");
201
            }
202
        }
203

    
204
        this.check_pending = function() {
205
            var len = this.pending.length;
206
            var args = [this.pending];
207
            this.pending = _.difference(this.pending, this.vms);
208
            if (len != this.pending.length) {
209
                if (this.pending.length == 0) {
210
                    this.trigger("pending:clear");
211
                }
212
            }
213

    
214
            var len = this.pending_for_removal.length;
215
            this.pending_for_removal = _.intersection(this.pending_for_removal, this.vms);
216
            if (this.pending_for_removal.length == 0) {
217
                this.trigger("pending:remove:clear");
218
            }
219

    
220
        }
221

    
222

    
223
        this.add = function(vm_id) {
224
            if (this.vms.indexOf(vm_id) == -1) {
225
                this.vms[this.vms.length] = vm_id;
226
                this.trigger("network:connect", vm_id);
227
                this.check_pending();
228
                return true;
229
            }
230
        }
231

    
232
        this.remove = function(vm_id) {
233
            if (this.vms.indexOf(vm_id) > -1) {
234
                this.vms = _.without(this.vms, vm_id);
235
                this.trigger("network:disconnect", vm_id);
236
                this.check_pending();
237
                return true;
238
            }
239
        }
240

    
241
        this.get = function() {
242
            return this.vms;
243
        }
244

    
245
        this.list = function() {
246
            return storage.vms.filter(_.bind(function(vm){
247
                return this.vms.indexOf(vm.id) > -1;
248
            }, this))
249
        }
250

    
251
        this.initialize();
252
    };
253
    _.extend(NetworkVMSList.prototype, bb.Events);
254
    
255
    // vm networks list helper
256
    var VMNetworksList = function() {
257
        this.initialize = function() {
258
            this.networks = {};
259
            this.network_ids = [];
260
        }
261

    
262
        this.add = function(net_id, data) {
263
            if (!this.networks[net_id]) {
264
                this.networks[net_id] = data || {};
265
                this.network_ids[this.network_ids.length] = net_id;
266
                this.trigger("network:connect", net_id);
267
                return true;
268
            }
269
        }
270

    
271
        this.remove = function(net_id) {
272
            if (this.networks[net_id]) {
273
                delete this.networks[net_id];
274
                this.network_ids = _.without(this.network_ids, net_id);
275
                this.trigger("network:disconnect", net_id);
276
                return true;
277
            }
278
            return false;
279
        }
280

    
281
        this.get = function() {
282
            return this.networks;
283
        }
284

    
285
        this.list = function() {
286
            return storage.networks.filter(_.bind(function(net){
287
                return this.network_ids.indexOf(net.id) > -1;
288
            }, this))
289
        }
290

    
291
        this.initialize();
292
    };
293
    _.extend(VMNetworksList.prototype, bb.Events);
294

    
295
    // Image model
296
    models.Network = models.Model.extend({
297
        path: 'networks',
298
        has_status: true,
299
        
300
        initialize: function() {
301
            this.vms = new NetworkVMSList();
302
            this.vms.bind("pending:add", _.bind(this.handle_pending_connections, this, "add"));
303
            this.vms.bind("pending:clear", _.bind(this.handle_pending_connections, this, "clear"));
304
            this.vms.bind("pending:remove:add", _.bind(this.handle_pending_connections, this, "add"));
305
            this.vms.bind("pending:remove:clear", _.bind(this.handle_pending_connections, this, "clear"));
306

    
307
            ret = models.Network.__super__.initialize.apply(this, arguments);
308

    
309
            storage.vms.bind("change:linked_to_nets", _.bind(this.update_connections, this, "vm:change"));
310
            storage.vms.bind("add", _.bind(this.update_connections, this, "add"));
311
            storage.vms.bind("remove", _.bind(this.update_connections, this, "remove"));
312
            storage.vms.bind("reset", _.bind(this.update_connections, this, "reset"));
313
            this.bind("change:linked_to", _.bind(this.update_connections, this, "net:change"));
314
            this.update_connections();
315
            this.update_state();
316
            return ret;
317
        },
318

    
319
        update_state: function() {
320
            if (this.vms.pending.length) {
321
                this.set({state: "CONNECTING"});
322
                return
323
            }
324
            if (this.vms.pending_for_removal.length) {
325
                this.set({state: "DISCONNECTING"});
326
                return
327
            }   
328
            
329
            var firewalling = false;
330
            _.each(this.vms.get(), _.bind(function(vm_id){
331
                var vm = storage.vms.get(vm_id);
332
                if (!vm) { return };
333
                if (!_.isEmpty(vm.pending_firewalls)) {
334
                    this.set({state:"FIREWALLING"});
335
                    firewalling = true;
336
                    return false;
337
                }
338
            },this));
339
            if (firewalling) { return };
340

    
341
            this.set({state:"NORMAL"});
342
        },
343

    
344
        handle_pending_connections: function(action) {
345
            this.update_state();
346
        },
347

    
348
        // handle vm/network connections
349
        update_connections: function(action, model) {
350
            
351
            // vm removed disconnect vm from network
352
            if (action == "remove") {
353
                var removed_from_net = this.vms.remove(model.id);
354
                var removed_from_vm = model.networks.remove(this.id);
355
                if (removed_from_net) {this.trigger("vm:disconnect", model, this); this.change()};
356
                if (removed_from_vm) {model.trigger("network:disconnect", this, model); this.change()};
357
                return;
358
            }
359
            
360
            // update links for all vms
361
            var links = this.get("linked_to");
362
            storage.vms.each(_.bind(function(vm) {
363
                var vm_links = vm.get("linked_to") || [];
364
                if (vm_links.indexOf(this.id) > -1) {
365
                    // vm has connection to current network
366
                    if (links.indexOf(vm.id) > -1) {
367
                        // and network has connection to vm, so try
368
                        // to append it
369
                        var add_to_net = this.vms.add(vm.id);
370
                        var index = _.indexOf(vm_links, this.id);
371
                        var add_to_vm = vm.networks.add(this.id, vm.get("linked_to_nets")[index]);
372
                        
373
                        // call only if connection did not existed
374
                        if (add_to_net) {this.trigger("vm:connect", vm, this); this.change()};
375
                        if (add_to_vm) {vm.trigger("network:connect", this, vm); vm.change()};
376
                    } else {
377
                        // no connection, try to remove it
378
                        var removed_from_net = this.vms.remove(vm.id);
379
                        var removed_from_vm = vm.networks.remove(this.id);
380
                        if (removed_from_net) {this.trigger("vm:disconnect", vm, this); this.change()};
381
                        if (removed_from_vm) {vm.trigger("network:disconnect", this, vm); vm.change()};
382
                    }
383
                } else {
384
                    // vm has no connection to current network, try to remove it
385
                    var removed_from_net = this.vms.remove(vm.id);
386
                    var removed_from_vm = vm.networks.remove(this.id);
387
                    if (removed_from_net) {this.trigger("vm:disconnect", vm, this); this.change()};
388
                    if (removed_from_vm) {vm.trigger("network:disconnect", this, vm); vm.change()};
389
                }
390
            },this));
391
        },
392

    
393
        is_public: function() {
394
            return this.id == "public";
395
        },
396

    
397
        contains_vm: function(vm) {
398
            var net_vm_exists = this.vms.get().indexOf(vm.id) > -1;
399
            var vm_net_exists = vm.is_connected_to(this);
400
            return net_vm_exists && vm_net_exists;
401
        },
402

    
403
        add_vm: function (vm, callback, error, options) {
404
            var payload = {add:{serverRef:"" + vm.id}};
405
            payload._options = options || {};
406
            return this.api.call(this.api_path() + "/action", "create", 
407
                                 payload,
408
                                 _.bind(function(){
409
                                     this.vms.add_pending(vm.id);
410
                                     if (callback) {callback()}
411
                                 },this), error);
412
        },
413

    
414
        remove_vm: function (vm, callback, error, options) {
415
            var payload = {remove:{serverRef:"" + vm.id}};
416
            payload._options = options || {};
417
            return this.api.call(this.api_path() + "/action", "create", 
418
                                 {remove:{serverRef:"" + vm.id}},
419
                                 _.bind(function(){
420
                                     this.vms.add_pending_for_remove(vm.id);
421
                                     if (callback) {callback()}
422
                                 },this), error);
423
        },
424

    
425
        rename: function(name, callback) {
426
            return this.api.call(this.api_path(), "update", {
427
                network:{name:name}, 
428
                _options:{
429
                    critical: false, 
430
                    error_params:{
431
                        title: "Network action failed",
432
                        ns: "Networks",
433
                        extra_details: {"Network id": this.id},
434
                    }
435
                }}, callback);
436
        },
437

    
438
        get_connectable_vms: function() {
439
            var servers = this.vms.list();
440
            return storage.vms.filter(function(vm){return servers.indexOf(vm) == -1})
441
        },
442

    
443
        state_message: function() {
444
            if (this.get("state") == "NORMAL" && this.is_public()) {
445
                return "Public network";
446
            }
447

    
448
            return models.Network.STATES[this.get("state")];
449
        },
450

    
451
        in_progress: function() {
452
            return models.Network.STATES_TRANSITIONS[this.get("state")] != undefined;
453
        }
454
    });
455
    
456
    models.Network.STATES = {
457
        'NORMAL': 'Private network',
458
        'CONNECTING': 'Connecting...',
459
        'DISCONNECTING': 'Disconnecting...',
460
        'FIREWALLING': 'Firewall update...'
461
    }
462

    
463
    models.Network.STATES_TRANSITIONS = {
464
        'CONNECTING': ['NORMAL'],
465
        'DISCONNECTING': ['NORMAL'],
466
        'FIREWALLING': ['NORMAL']
467
    }
468

    
469
    // Virtualmachine model
470
    models.VM = models.Model.extend({
471

    
472
        path: 'servers',
473
        has_status: true,
474
        initialize: function(params) {
475
            this.networks = new VMNetworksList();
476
            
477
            this.pending_firewalls = {};
478
            
479
            models.VM.__super__.initialize.apply(this, arguments);
480

    
481
            this.set({state: params.status || "ERROR"});
482
            this.log = new snf.logging.logger("VM " + this.id);
483
            this.pending_action = undefined;
484
            
485
            // init stats parameter
486
            this.set({'stats': undefined}, {silent: true});
487
            // defaults to not update the stats
488
            // each view should handle this vm attribute 
489
            // depending on if it displays stat images or not
490
            this.do_update_stats = false;
491
            
492
            // interval time
493
            // this will dynamicaly change if the server responds that
494
            // images get refreshed on different intervals
495
            this.stats_update_interval = synnefo.config.STATS_INTERVAL || 5000;
496
            this.stats_available = false;
497

    
498
            // initialize interval
499
            this.init_stats_intervals(this.stats_update_interval);
500
            
501
            this.bind("change:progress", _.bind(this.update_building_progress, this));
502
            this.update_building_progress();
503

    
504
            this.bind("change:firewalls", _.bind(this.handle_firewall_change, this));
505
            
506
            // default values
507
            this.set({linked_to_nets:this.get("linked_to_nets") || []});
508
            this.set({firewalls:this.get("firewalls") || []});
509

    
510
            this.bind("change:state", _.bind(function(){if (this.state() == "DESTROY") { this.handle_destroy() }}, this))
511
        },
512

    
513
        handle_firewall_change: function() {
514

    
515
        },
516
        
517
        set_linked_to_nets: function(data) {
518
            this.set({"linked_to":_.map(data, function(n){ return n.id})});
519
            return data;
520
        },
521

    
522
        is_connected_to: function(net) {
523
            return _.filter(this.networks.list(), function(n){return n.id == net.id}).length > 0;
524
        },
525
        
526
        status: function(st) {
527
            if (!st) { return this.get("status")}
528
            return this.set({status:st});
529
        },
530

    
531
        set_status: function(st) {
532
            var new_state = this.state_for_api_status(st);
533
            var transition = false;
534

    
535
            if (this.state() != new_state) {
536
                if (models.VM.STATES_TRANSITIONS[this.state()]) {
537
                    transition = this.state();
538
                }
539
            }
540
            
541
            // call it silently to avoid double change trigger
542
            this.set({'state': this.state_for_api_status(st)}, {silent: true});
543
            
544
            // trigger transition
545
            if (transition && models.VM.TRANSITION_STATES.indexOf(new_state) == -1) { 
546
                this.trigger("transition", {from:transition, to:new_state}) 
547
            };
548
            return st;
549
        },
550

    
551
        update_building_progress: function() {
552
            if (this.is_building()) {
553
                var progress = this.get("progress");
554
                if (progress == 0) {
555
                    this.state("BUILD_INIT");
556
                    this.set({progress_message: BUILDING_MESSAGES['INIT']});
557
                }
558
                if (progress > 0 && progress < 99) {
559
                    this.state("BUILD_COPY");
560
                    var params = this.get_copy_details(true);
561
                    this.set({progress_message: BUILDING_MESSAGES['COPY'].format(params.copy, 
562
                                                                                 params.size, 
563
                                                                                 params.progress)});
564
                }
565
                if (progress == 100) {
566
                    this.state("BUILD_FINAL");
567
                    this.set({progress_message: BUILDING_MESSAGES['FINAL']});
568
                }
569
            } else {
570
            }
571
        },
572

    
573
        get_copy_details: function(human, image) {
574
            var human = human || false;
575
            var image = image || this.get_image();
576

    
577
            var progress = this.get('progress');
578
            var size = image.get_size();
579
            var size_copied = (size * progress / 100).toFixed(2);
580
            
581
            if (human) {
582
                size = util.readablizeBytes(size*1024*1024);
583
                size_copied = util.readablizeBytes(size_copied*1024*1024);
584
            }
585
            return {'progress': progress, 'size': size, 'copy': size_copied};
586
        },
587

    
588
        start_stats_update: function(force_if_empty) {
589
            var prev_state = this.do_update_stats;
590

    
591
            this.do_update_stats = true;
592
            
593
            // fetcher initialized ??
594
            if (!this.stats_fetcher) {
595
                this.init_stats_intervals();
596
            }
597

    
598

    
599
            // fetcher running ???
600
            if (!this.stats_fetcher.running || !prev_state) {
601
                this.stats_fetcher.start();
602
            }
603

    
604
            if (force_if_empty && this.get("stats") == undefined) {
605
                this.update_stats(true);
606
            }
607
        },
608

    
609
        stop_stats_update: function(stop_calls) {
610
            this.do_update_stats = false;
611

    
612
            if (stop_calls) {
613
                this.stats_fetcher.stop();
614
            }
615
        },
616

    
617
        // clear and reinitialize update interval
618
        init_stats_intervals: function (interval) {
619
            this.stats_fetcher = this.get_stats_fetcher(this.stats_update_interval);
620
            this.stats_fetcher.start();
621
        },
622
        
623
        get_stats_fetcher: function(timeout) {
624
            var cb = _.bind(function(data){
625
                this.update_stats();
626
            }, this);
627
            var fetcher = new snf.api.updateHandler({'callback': cb, timeout:timeout});
628
            return fetcher;
629
        },
630

    
631
        // do the api call
632
        update_stats: function(force) {
633
            // do not update stats if flag not set
634
            if ((!this.do_update_stats && !force) || this.updating_stats) {
635
                return;
636
            }
637

    
638
            // make the api call, execute handle_stats_update on sucess
639
            // TODO: onError handler ???
640
            stats_url = this.url() + "/stats";
641
            this.updating_stats = true;
642
            this.sync("GET", this, {
643
                handles_error:true, 
644
                url: stats_url, 
645
                refresh:true, 
646
                success: _.bind(this.handle_stats_update, this),
647
                error: _.bind(this.handle_stats_error, this),
648
                complete: _.bind(function(){this.updating_stats = false;}, this),
649
                critical: false,
650
                display: false,
651
                log_error: false
652
            });
653
        },
654

    
655
        get_stats_image: function(stat, type) {
656
        },
657
        
658
        _set_stats: function(stats) {
659
            var silent = silent === undefined ? false : silent;
660
            // unavailable stats while building
661
            if (this.get("status") == "BUILD") { 
662
                this.stats_available = false;
663
            } else { this.stats_available = true; }
664

    
665
            if (this.get("status") == "DESTROY") { this.stats_available = false; }
666
            
667
            this.set({stats: stats}, {silent:true});
668
            this.trigger("stats:update", stats);
669
        },
670

    
671
        unbind: function() {
672
            models.VM.__super__.unbind.apply(this, arguments);
673
        },
674

    
675
        handle_stats_error: function() {
676
            stats = {};
677
            _.each(['cpuBar', 'cpuTimeSeries', 'netBar', 'netTimeSeries'], function(k) {
678
                stats[k] = false;
679
            });
680

    
681
            this.set({'stats': stats});
682
        },
683

    
684
        // this method gets executed after a successful vm stats api call
685
        handle_stats_update: function(data) {
686
            var self = this;
687
            // avoid browser caching
688
            
689
            if (data.stats && _.size(data.stats) > 0) {
690
                var ts = $.now();
691
                var stats = data.stats;
692
                var images_loaded = 0;
693
                var images = {};
694

    
695
                function check_images_loaded() {
696
                    images_loaded++;
697

    
698
                    if (images_loaded == 4) {
699
                        self._set_stats(images);
700
                    }
701
                }
702
                _.each(['cpuBar', 'cpuTimeSeries', 'netBar', 'netTimeSeries'], function(k) {
703
                    
704
                    stats[k] = stats[k] + "?_=" + ts;
705
                    
706
                    var stat = k.slice(0,3);
707
                    var type = k.slice(3,6) == "Bar" ? "bar" : "time";
708
                    var img = $("<img />");
709
                    var val = stats[k];
710
                    
711
                    // load stat image to a temporary dom element
712
                    // update model stats on image load/error events
713
                    img.load(function() {
714
                        images[k] = val;
715
                        check_images_loaded();
716
                    });
717

    
718
                    img.error(function() {
719
                        images[stat + type] = false;
720
                        check_images_loaded();
721
                    });
722

    
723
                    img.attr({'src': stats[k]});
724
                })
725
                data.stats = stats;
726
            }
727

    
728
            // do we need to change the interval ??
729
            if (data.stats.refresh * 1000 != this.stats_update_interval) {
730
                this.stats_update_interval = data.stats.refresh * 1000;
731
                this.stats_fetcher.timeout = this.stats_update_interval;
732
                this.stats_fetcher.stop();
733
                this.stats_fetcher.start(false);
734
            }
735
        },
736

    
737
        // helper method that sets the do_update_stats
738
        // in the future this method could also make an api call
739
        // immediaetly if needed
740
        enable_stats_update: function() {
741
            this.do_update_stats = true;
742
        },
743
        
744
        handle_destroy: function() {
745
            this.stats_fetcher.stop();
746
        },
747

    
748
        require_reboot: function() {
749
            if (this.is_active()) {
750
                this.set({'reboot_required': true});
751
            }
752
        },
753
        
754
        set_pending_action: function(data) {
755
            this.pending_action = data;
756
            return data;
757
        },
758

    
759
        // machine has pending action
760
        update_pending_action: function(action, force) {
761
            this.set({pending_action: action});
762
        },
763

    
764
        clear_pending_action: function() {
765
            this.set({pending_action: undefined});
766
        },
767

    
768
        has_pending_action: function() {
769
            return this.get("pending_action") ? this.get("pending_action") : false;
770
        },
771
        
772
        // machine is active
773
        is_active: function() {
774
            return models.VM.ACTIVE_STATES.indexOf(this.state()) > -1;
775
        },
776
        
777
        // machine is building 
778
        is_building: function() {
779
            return models.VM.BUILDING_STATES.indexOf(this.state()) > -1;
780
        },
781

    
782
        // user can connect to machine
783
        is_connectable: function() {
784
            // check if ips exist
785
            if (!this.get_addresses().ip4 && !this.get_addresses().ip6) {
786
                return false;
787
            }
788
            return models.VM.CONNECT_STATES.indexOf(this.state()) > -1;
789
        },
790
        
791
        set_firewalls: function(data) {
792
            _.each(data, _.bind(function(val, key){
793
                if (this.pending_firewalls && this.pending_firewalls[key] && this.pending_firewalls[key] == val) {
794
                        this.require_reboot();
795
                        this.remove_pending_firewall(key, val);
796
                }
797
            }, this));
798
            return data;
799
        },
800

    
801
        remove_pending_firewall: function(net_id, value) {
802
            if (this.pending_firewalls[net_id] == value) {
803
                delete this.pending_firewalls[net_id];
804
                storage.networks.get(net_id).update_state();
805
            }
806
        },
807
            
808
        remove_meta: function(key, complete, error) {
809
            var url = this.api_path() + "/meta/" + key;
810
            this.api.call(url, "delete", undefined, complete, error);
811
        },
812

    
813
        save_meta: function(meta, complete, error) {
814
            var url = this.api_path() + "/meta/" + meta.key;
815
            var payload = {meta:{}};
816
            payload.meta[meta.key] = meta.value;
817
            payload._options = {
818
                critical:false, 
819
                error_params: {
820
                    title: "Machine metadata error",
821
                    extra_details: {"Machine id": this.id}
822
            }};
823

    
824
            this.api.call(url, "update", payload, complete, error);
825
        },
826

    
827
        set_firewall: function(net_id, value, callback, error, options) {
828
            if (this.get("firewalls") && this.get("firewalls")[net_id] == value) { return }
829

    
830
            this.pending_firewalls[net_id] = value;
831
            this.trigger("change", this, this);
832
            var payload = {"firewallProfile":{"profile":value}};
833
            payload._options = _.extend({critical: false}, options);
834
            
835
            // reset firewall state on error
836
            var error_cb = _.bind(function() {
837
                thi
838
            }, this);
839

    
840
            this.api.call(this.api_path() + "/action", "create", payload, callback, error);
841
            storage.networks.get(net_id).update_state();
842
        },
843

    
844
        firewall_pending: function(net_id) {
845
            return this.pending_firewalls[net_id] != undefined;
846
        },
847
        
848
        // update/get the state of the machine
849
        state: function() {
850
            var args = slice.call(arguments);
851
                
852
            // TODO: it might not be a good idea to set the state in set_state method
853
            if (args.length > 0 && models.VM.STATES.indexOf(args[0]) > -1) {
854
                this.set({'state': args[0]});
855
            }
856

    
857
            return this.get('state');
858
        },
859
        
860
        // get the state that the api status corresponds to
861
        state_for_api_status: function(status) {
862
            return this.state_transition(this.state(), status);
863
        },
864
        
865
        // vm state equals vm api status
866
        state_is_status: function(state) {
867
            return models.VM.STATUSES.indexOf(state) != -1;
868
        },
869
        
870
        // get transition state for the corresponging api status
871
        state_transition: function(state, new_status) {
872
            var statuses = models.VM.STATES_TRANSITIONS[state];
873
            if (statuses) {
874
                if (statuses.indexOf(new_status) > -1) {
875
                    return new_status;
876
                } else {
877
                    return state;
878
                }
879
            } else {
880
                return new_status;
881
            }
882
        },
883
        
884
        // the current vm state is a transition state
885
        in_transition: function() {
886
            return models.VM.TRANSITION_STATES.indexOf(this.state()) > -1 || 
887
                models.VM.TRANSITION_STATES.indexOf(this.get('status')) > -1;
888
        },
889
        
890
        // get image object
891
        // TODO: update images synchronously if image not found
892
        get_image: function() {
893
            var image = storage.images.get(this.get('imageRef'));
894
            if (!image) {
895
                storage.images.update_unknown_id(this.get('imageRef'));
896
                image = storage.flavors.get(this.get('imageRef'));
897
            }
898
            return image;
899
        },
900
        
901
        // get flavor object
902
        // TODO: update flavors synchronously if image not found
903
        get_flavor: function() {
904
            var flv = storage.flavors.get(this.get('flavorRef'));
905
            if (!flv) {
906
                storage.flavors.update_unknown_id(this.get('flavorRef'));
907
                flv = storage.flavors.get(this.get('flavorRef'));
908
            }
909
            return flv;
910
        },
911

    
912
        // retrieve the metadata object
913
        get_meta: function() {
914
            //return {
915
                //'OS': 'debian',
916
                //'username': 'vinilios',
917
                //'group': 'webservers',
918
                //'meta2': 'meta value',
919
                //'looooooooooooooooong meta': 'short value',
920
                //'short meta': 'loooooooooooooooooooooooooooooooooong value',
921
                //'21421': 'fdsfds fds',
922
                //'21421': 'fdsfds fds',
923
                //'1fds 21421': 'fdsfds fds',
924
                //'fds 21421': 'fdsfds fds',
925
                //'fge 21421': 'fdsfds fds',
926
                //'21421 rew rew': 'fdsfds fds'
927
            //}
928
            try {
929
                return this.get('metadata').values
930
            } catch (err) {
931
                return {};
932
            }
933
        },
934
        
935
        // get metadata OS value
936
        get_os: function() {
937
            return this.get_meta().OS || (this.get_image() ? this.get_image().get_os() || "okeanos" : "okeanos");
938
        },
939
        
940
        // get public ip addresses
941
        // TODO: public network is always the 0 index ???
942
        get_addresses: function(net_id) {
943
            var net_id = net_id || "public";
944
            
945
            var info = this.get_network_info(net_id);
946
            if (!info) { return {} };
947
            addrs = {};
948
            _.each(info.values, function(addr) {
949
                addrs["ip" + addr.version] = addr.addr;
950
            });
951
            return addrs
952
        },
953

    
954
        get_network_info: function(net_id) {
955
            var net_id = net_id || "public";
956
            
957
            if (!this.networks.network_ids.length) { return {} };
958

    
959
            var addresses = this.networks.get();
960
            try {
961
                return _.select(addresses, function(net, key){return key == net_id })[0];
962
            } catch (err) {
963
                //this.log.debug("Cannot find network {0}".format(net_id))
964
            }
965
        },
966

    
967
        firewall_profile: function(net_id) {
968
            var net_id = net_id || "public";
969
            var firewalls = this.get("firewalls");
970
            return firewalls[net_id];
971
        },
972

    
973
        has_firewall: function(net_id) {
974
            var net_id = net_id || "public";
975
            return ["ENABLED","PROTECTED"].indexOf(this.firewall_profile()) > -1;
976
        },
977
    
978
        // get actions that the user can execute
979
        // depending on the vm state/status
980
        get_available_actions: function() {
981
            return models.VM.AVAILABLE_ACTIONS[this.state()];
982
        },
983

    
984
        set_profile: function(profile, net_id) {
985
        },
986
        
987
        // call rename api
988
        rename: function(new_name) {
989
            //this.set({'name': new_name});
990
            this.sync("update", this, {
991
                critical: true,
992
                data: {
993
                    'server': {
994
                        'name': new_name
995
                    }
996
                }, 
997
                // do the rename after the method succeeds
998
                success: _.bind(function(){
999
                    //this.set({name: new_name});
1000
                    snf.api.trigger("call");
1001
                }, this)
1002
            });
1003
        },
1004
        
1005
        get_console_url: function(data) {
1006
            var url_params = {
1007
                machine: this.get("name"),
1008
                host_ip: this.get_addresses().ip4,
1009
                host_ip_v6: this.get_addresses().ip6,
1010
                host: data.host,
1011
                port: data.port,
1012
                password: data.password
1013
            }
1014
            return '/machines/console?' + $.param(url_params);
1015
        },
1016

    
1017
        // action helper
1018
        call: function(action_name, success, error) {
1019
            var id_param = [this.id];
1020

    
1021
            success = success || function() {};
1022
            error = error || function() {};
1023

    
1024
            var self = this;
1025

    
1026
            switch(action_name) {
1027
                case 'start':
1028
                    this.__make_api_call(this.get_action_url(), // vm actions url
1029
                                         "create", // create so that sync later uses POST to make the call
1030
                                         {start:{}}, // payload
1031
                                         function() {
1032
                                             // set state after successful call
1033
                                             self.state("START"); 
1034
                                             success.apply(this, arguments);
1035
                                             snf.api.trigger("call");
1036
                                         },  
1037
                                         error, 'start');
1038
                    break;
1039
                case 'reboot':
1040
                    this.__make_api_call(this.get_action_url(), // vm actions url
1041
                                         "create", // create so that sync later uses POST to make the call
1042
                                         {reboot:{type:"HARD"}}, // payload
1043
                                         function() {
1044
                                             // set state after successful call
1045
                                             self.state("REBOOT"); 
1046
                                             success.apply(this, arguments)
1047
                                             snf.api.trigger("call");
1048
                                             self.set({'reboot_required': false});
1049
                                         },
1050
                                         error, 'reboot');
1051
                    break;
1052
                case 'shutdown':
1053
                    this.__make_api_call(this.get_action_url(), // vm actions url
1054
                                         "create", // create so that sync later uses POST to make the call
1055
                                         {shutdown:{}}, // payload
1056
                                         function() {
1057
                                             // set state after successful call
1058
                                             self.state("SHUTDOWN"); 
1059
                                             success.apply(this, arguments)
1060
                                             snf.api.trigger("call");
1061
                                         },  
1062
                                         error, 'shutdown');
1063
                    break;
1064
                case 'console':
1065
                    this.__make_api_call(this.url() + "/action", "create", {'console': {'type':'vnc'}}, function(data) {
1066
                        var cons_data = data.console;
1067
                        success.apply(this, [cons_data]);
1068
                    }, undefined, 'console')
1069
                    break;
1070
                case 'destroy':
1071
                    this.__make_api_call(this.url(), // vm actions url
1072
                                         "delete", // create so that sync later uses POST to make the call
1073
                                         undefined, // payload
1074
                                         function() {
1075
                                             // set state after successful call
1076
                                             self.state('DESTROY');
1077
                                             success.apply(this, arguments)
1078
                                         },  
1079
                                         error, 'destroy');
1080
                    break;
1081
                default:
1082
                    throw "Invalid VM action ("+action_name+")";
1083
            }
1084
        },
1085
        
1086
        __make_api_call: function(url, method, data, success, error, action) {
1087
            var self = this;
1088
            error = error || function(){};
1089
            success = success || function(){};
1090

    
1091
            var params = {
1092
                url: url,
1093
                data: data,
1094
                success: function(){ self.handle_action_succeed.apply(self, arguments); success.apply(this, arguments)},
1095
                error: function(){ self.handle_action_fail.apply(self, arguments); error.apply(this, arguments)},
1096
                error_params: { ns: "Machines actions", 
1097
                                title: "'" + this.get("name") + "'" + " " + action + " failed", 
1098
                                extra_details: { 'Machine ID': this.id, 'URL': url, 'Action': action || "undefined" },
1099
                                allow_reload: false
1100
                              },
1101
                display: false,
1102
                critical: false
1103
            }
1104
            this.sync(method, this, params);
1105
        },
1106

    
1107
        handle_action_succeed: function() {
1108
            this.trigger("action:success", arguments);
1109
        },
1110
        
1111
        reset_action_error: function() {
1112
            this.action_error = false;
1113
            this.trigger("action:fail:reset", this.action_error);
1114
        },
1115

    
1116
        handle_action_fail: function() {
1117
            this.action_error = arguments;
1118
            this.trigger("action:fail", arguments);
1119
        },
1120

    
1121
        get_action_url: function(name) {
1122
            return this.url() + "/action";
1123
        },
1124

    
1125
        get_connection_info: function(host_os, success, error) {
1126
            var url = "/machines/connect";
1127
            params = {
1128
                ip_address: this.get_addresses().ip4,
1129
                os: this.get_os(),
1130
                host_os: host_os,
1131
                srv: this.id
1132
            }
1133

    
1134
            url = url + "?" + $.param(params);
1135

    
1136
            var ajax = snf.api.sync("read", undefined, { url: url, 
1137
                                                         error:error, 
1138
                                                         success:success, 
1139
                                                         handles_error:1});
1140
        }
1141
    })
1142
    
1143
    models.VM.ACTIONS = [
1144
        'start',
1145
        'shutdown',
1146
        'reboot',
1147
        'console',
1148
        'destroy'
1149
    ]
1150

    
1151
    models.VM.AVAILABLE_ACTIONS = {
1152
        'UNKNWON'       : ['destroy'],
1153
        'BUILD'         : ['destroy'],
1154
        'REBOOT'        : ['shutdown', 'destroy', 'console'],
1155
        'STOPPED'       : ['start', 'destroy'],
1156
        'ACTIVE'        : ['shutdown', 'destroy', 'reboot', 'console'],
1157
        'ERROR'         : ['destroy'],
1158
        'DELETED'        : [],
1159
        'DESTROY'       : [],
1160
        'BUILD_INIT'    : ['destroy'],
1161
        'BUILD_COPY'    : ['destroy'],
1162
        'BUILD_FINAL'   : ['destroy'],
1163
        'SHUTDOWN'      : ['destroy'],
1164
        'START'         : [],
1165
        'CONNECT'       : [],
1166
        'DISCONNECT'    : []
1167
    }
1168

    
1169
    // api status values
1170
    models.VM.STATUSES = [
1171
        'UNKNWON',
1172
        'BUILD',
1173
        'REBOOT',
1174
        'STOPPED',
1175
        'ACTIVE',
1176
        'ERROR',
1177
        'DELETED'
1178
    ]
1179

    
1180
    // api status values
1181
    models.VM.CONNECT_STATES = [
1182
        'ACTIVE',
1183
        'REBOOT',
1184
        'SHUTDOWN'
1185
    ]
1186

    
1187
    // vm states
1188
    models.VM.STATES = models.VM.STATUSES.concat([
1189
        'DESTROY',
1190
        'BUILD_INIT',
1191
        'BUILD_COPY',
1192
        'BUILD_FINAL',
1193
        'SHUTDOWN',
1194
        'START',
1195
        'CONNECT',
1196
        'DISCONNECT',
1197
        'FIREWALL'
1198
    ]);
1199
    
1200
    models.VM.STATES_TRANSITIONS = {
1201
        'DESTROY' : ['DELETED'],
1202
        'SHUTDOWN': ['ERROR', 'STOPPED', 'DESTROY'],
1203
        'STOPPED': ['ERROR', 'ACTIVE', 'DESTROY'],
1204
        'ACTIVE': ['ERROR', 'STOPPED', 'REBOOT', 'SHUTDOWN', 'DESTROY'],
1205
        'START': ['ERROR', 'ACTIVE', 'DESTROY'],
1206
        'REBOOT': ['ERROR', 'ACTIVE', 'STOPPED', 'DESTROY'],
1207
        'BUILD': ['ERROR', 'ACTIVE', 'DESTROY'],
1208
        'BUILD_COPY': ['ERROR', 'ACTIVE', 'BUILD_FINAL', 'DESTROY'],
1209
        'BUILD_FINAL': ['ERROR', 'ACTIVE', 'DESTROY'],
1210
        'BUILD_INIT': ['ERROR', 'ACTIVE', 'BUILD_COPY', 'BUILD_FINAL', 'DESTROY']
1211
    }
1212

    
1213
    models.VM.TRANSITION_STATES = [
1214
        'DESTROY',
1215
        'SHUTDOWN',
1216
        'START',
1217
        'REBOOT',
1218
        'BUILD'
1219
    ]
1220

    
1221
    models.VM.ACTIVE_STATES = [
1222
        'BUILD', 'REBOOT', 'ACTIVE',
1223
        'BUILD_INIT', 'BUILD_COPY', 'BUILD_FINAL',
1224
        'SHUTDOWN', 'CONNECT', 'DISCONNECT'
1225
    ]
1226

    
1227
    models.VM.BUILDING_STATES = [
1228
        'BUILD', 'BUILD_INIT', 'BUILD_COPY', 'BUILD_FINAL'
1229
    ]
1230

    
1231
    models.Networks = models.Collection.extend({
1232
        model: models.Network,
1233
        path: 'networks',
1234
        details: true,
1235
        //noUpdate: true,
1236
        defaults: {'linked_to':[]},
1237

    
1238
        parse: function (resp, xhr) {
1239
            // FIXME: depricated global var
1240
            if (!resp) { return []};
1241
               
1242
            var data = _.map(resp.networks.values, _.bind(this.parse_net_api_data, this));
1243
            return data;
1244
        },
1245

    
1246
        parse_net_api_data: function(data) {
1247
            if (data.servers && data.servers.values) {
1248
                data['linked_to'] = data.servers.values;
1249
            }
1250
            return data;
1251
        },
1252

    
1253
        create: function (name, callback) {
1254
            return this.api.call(this.path, "create", {network:{name:name}}, callback);
1255
        }
1256
    })
1257

    
1258
    models.Images = models.Collection.extend({
1259
        model: models.Image,
1260
        path: 'images',
1261
        details: true,
1262
        noUpdate: true,
1263
        
1264
        meta_keys_as_attrs: ["OS", "description", "kernel", "size", "GUI"],
1265

    
1266
        // update collection model with id passed
1267
        // making a direct call to the flavor
1268
        // api url
1269
        update_unknown_id: function(id) {
1270
            var url = getUrl.call(this) + "/" + id;
1271
            this.api.call(this.path + "/" + id, "read", {_options:{async:false}}, undefined, 
1272
            _.bind(function() {
1273
                this.add({id:id, name:"Unknown image", size:-1, progress:100, status:"DELETED"})
1274
            }, this), _.bind(function(image) {
1275
                this.add(image.image);
1276
            }, this));
1277
        },
1278

    
1279
        parse: function (resp, xhr) {
1280
            // FIXME: depricated global var
1281
            var data = _.map(resp.images.values, _.bind(this.parse_meta, this));
1282
            return resp.images.values;
1283
        },
1284

    
1285
        get_meta_key: function(img, key) {
1286
            if (img.metadata && img.metadata.values && img.metadata.values[key]) {
1287
                return img.metadata.values[key];
1288
            }
1289
            return undefined;
1290
        },
1291

    
1292
        comparator: function(img) {
1293
            return -img.get_sort_order("sortorder") || 1000 * img.id;
1294
        },
1295

    
1296
        parse_meta: function(img) {
1297
            _.each(this.meta_keys_as_attrs, _.bind(function(key){
1298
                img[key] = this.get_meta_key(img, key);
1299
            }, this));
1300
            return img;
1301
        },
1302

    
1303
        active: function() {
1304
            return this.filter(function(img){return img.get('status') != "DELETED"});
1305
        }
1306
    })
1307

    
1308
    models.Flavors = models.Collection.extend({
1309
        model: models.Flavor,
1310
        path: 'flavors',
1311
        details: true,
1312
        noUpdate: true,
1313
        
1314
        // update collection model with id passed
1315
        // making a direct call to the flavor
1316
        // api url
1317
        update_unknown_id: function(id) {
1318
            var url = getUrl.call(this) + "/" + id;
1319
            this.api.call(this.path + "/" + id, "read", {_options:{async:false}}, undefined, 
1320
            _.bind(function() {
1321
                this.add({id:id, cpu:"", ram:"", disk:"", name: "", status:"DELETED"})
1322
            }, this), _.bind(function(flv) {
1323
                if (!flv.flavor.status) { flv.flavor.status = "DELETED" };
1324
                this.add(flv.flavor);
1325
            }, this));
1326
        },
1327

    
1328
        parse: function (resp, xhr) {
1329
            // FIXME: depricated global var
1330
            return resp.flavors.values;
1331
        },
1332

    
1333
        comparator: function(flv) {
1334
            return flv.get("disk") * flv.get("cpu") * flv.get("ram");
1335
        },
1336

    
1337
        unavailable_values_for_image: function(img, flavors) {
1338
            var flavors = flavors || this.active();
1339
            var size = img.get_size();
1340
            
1341
            var index = {cpu:[], disk:[], ram:[]};
1342

    
1343
            _.each(this.active(), function(el) {
1344
                var img_size = size;
1345
                var flv_size = el.get_disk_size();
1346
                if (flv_size < img_size) {
1347
                    if (index.disk.indexOf(flv_size) == -1) {
1348
                        index.disk.push(flv_size);
1349
                    }
1350
                };
1351
            });
1352
            
1353
            return index;
1354
        },
1355

    
1356
        get_flavor: function(cpu, mem, disk, filter_list) {
1357
            if (!filter_list) { filter_list = this.models };
1358

    
1359
            return this.select(function(flv){
1360
                if (flv.get("cpu") == cpu + "" &&
1361
                   flv.get("ram") == mem + "" &&
1362
                   flv.get("disk") == disk + "" &&
1363
                   filter_list.indexOf(flv) > -1) { return true; }
1364
            })[0];
1365
        },
1366
        
1367
        get_data: function(lst) {
1368
            var data = {'cpu': [], 'mem':[], 'disk':[]};
1369

    
1370
            _.each(lst, function(flv) {
1371
                if (data.cpu.indexOf(flv.get("cpu")) == -1) {
1372
                    data.cpu.push(flv.get("cpu"));
1373
                }
1374
                if (data.mem.indexOf(flv.get("ram")) == -1) {
1375
                    data.mem.push(flv.get("ram"));
1376
                }
1377
                if (data.disk.indexOf(flv.get("disk")) == -1) {
1378
                    data.disk.push(flv.get("disk"));
1379
                }
1380
            })
1381
            
1382
            return data;
1383
        },
1384

    
1385
        active: function() {
1386
            return this.filter(function(flv){return flv.get('status') != "DELETED"});
1387
        }
1388
            
1389
    })
1390

    
1391
    models.VMS = models.Collection.extend({
1392
        model: models.VM,
1393
        path: 'servers',
1394
        details: true,
1395
        copy_image_meta: true,
1396
        
1397
        parse: function (resp, xhr) {
1398
            // FIXME: depricated after refactoring
1399
            var data = resp;
1400
            if (!resp) { return [] };
1401
            data = _.filter(_.map(resp.servers.values, _.bind(this.parse_vm_api_data, this)), function(v){return v});
1402
            return data;
1403
        },
1404
        
1405
        get_reboot_required: function() {
1406
            return this.filter(function(vm){return vm.get("reboot_required") == true})
1407
        },
1408

    
1409
        has_pending_actions: function() {
1410
            return this.filter(function(vm){return vm.pending_action}).length > 0;
1411
        },
1412

    
1413
        reset_pending_actions: function() {
1414
            this.each(function(vm) {
1415
                vm.clear_pending_action();
1416
            })
1417
        },
1418
        
1419
        stop_stats_update: function(exclude) {
1420
            var exclude = exclude || [];
1421
            this.each(function(vm) {
1422
                if (exclude.indexOf(vm) > -1) {
1423
                    return;
1424
                }
1425
                vm.stop_stats_update();
1426
            })
1427
        },
1428
        
1429
        has_meta: function(vm_data) {
1430
            return vm_data.metadata && vm_data.metadata.values
1431
        },
1432

    
1433
        has_addresses: function(vm_data) {
1434
            return vm_data.metadata && vm_data.metadata.values
1435
        },
1436

    
1437
        parse_vm_api_data: function(data) {
1438
            // do not add non existing DELETED entries
1439
            if (data.status && data.status == "DELETED") {
1440
                if (!this.get(data.id)) {
1441
                    console.error("non exising deleted vm", data)
1442
                    return false;
1443
                }
1444
            }
1445

    
1446
            // OS attribute
1447
            if (this.has_meta(data)) {
1448
                data['OS'] = data.metadata.values.OS || "okeanos";
1449
            }
1450
            
1451
            data['firewalls'] = {};
1452
            if (data['addresses'] && data['addresses'].values) {
1453
                data['linked_to_nets'] = data['addresses'].values;
1454
                _.each(data['addresses'].values, function(f){
1455
                    if (f['firewallProfile']) {
1456
                        data['firewalls'][f['id']] = f['firewallProfile']
1457
                    }
1458
                });
1459
            }
1460
            
1461
            // if vm has no metadata, no metadata object
1462
            // is in json response, reset it to force
1463
            // value update
1464
            if (!data['metadata']) {
1465
                data['metadata'] = {values:{}};
1466
            }
1467

    
1468
            return data;
1469
        },
1470

    
1471
        create: function (name, image, flavor, meta, extra, callback) {
1472
            if (this.copy_image_meta) {
1473
                meta['OS'] = image.get("OS");
1474
           }
1475
            
1476
            opts = {name: name, imageRef: image.id, flavorRef: flavor.id, metadata:meta}
1477
            opts = _.extend(opts, extra);
1478

    
1479
            this.api.call(this.path, "create", {'server': opts}, undefined, undefined, callback, {critical: false});
1480
        }
1481

    
1482
    })
1483
    
1484

    
1485
    // storage initialization
1486
    snf.storage.images = new models.Images();
1487
    snf.storage.flavors = new models.Flavors();
1488
    snf.storage.networks = new models.Networks();
1489
    snf.storage.vms = new models.VMS();
1490

    
1491
    //snf.storage.vms.fetch({update:true});
1492
    //snf.storage.images.fetch({update:true});
1493
    //snf.storage.flavors.fetch({update:true});
1494

    
1495
})(this);