Statistics
| Branch: | Tag: | Revision:

root / ui / static / snf / js / models.js @ 3162bebd

History | View | Annotate | Download (52.2 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){
441
                return servers.indexOf(vm) == -1 && !vm.in_error_state();
442
            })
443
        },
444

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

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

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

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

    
471
    // Virtualmachine model
472
    models.VM = models.Model.extend({
473

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

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

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

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

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

    
515
        handle_firewall_change: function() {
516

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

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

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

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

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

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

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

    
590
        start_stats_update: function(force_if_empty) {
591
            var prev_state = this.do_update_stats;
592

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

    
600

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

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

    
611
        stop_stats_update: function(stop_calls) {
612
            this.do_update_stats = false;
613

    
614
            if (stop_calls) {
615
                this.stats_fetcher.stop();
616
            }
617
        },
618

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

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

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

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

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

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

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

    
683
            this.set({'stats': stats});
684
        },
685

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

    
697
                function check_images_loaded() {
698
                    images_loaded++;
699

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

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

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

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

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

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

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

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

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

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

    
807
        remove_pending_firewall: function(net_id, value) {
808
            if (this.pending_firewalls[net_id] == value) {
809
                delete this.pending_firewalls[net_id];
810
                storage.networks.get(net_id).update_state();
811
            }
812
        },
813
            
814
        remove_meta: function(key, complete, error) {
815
            var url = this.api_path() + "/meta/" + key;
816
            this.api.call(url, "delete", undefined, complete, error);
817
        },
818

    
819
        save_meta: function(meta, complete, error) {
820
            var url = this.api_path() + "/meta/" + meta.key;
821
            var payload = {meta:{}};
822
            payload.meta[meta.key] = meta.value;
823
            payload._options = {
824
                critical:false, 
825
                error_params: {
826
                    title: "Machine metadata error",
827
                    extra_details: {"Machine id": this.id}
828
            }};
829

    
830
            this.api.call(url, "update", payload, complete, error);
831
        },
832

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

    
836
            this.pending_firewalls[net_id] = value;
837
            this.trigger("change", this, this);
838
            var payload = {"firewallProfile":{"profile":value}};
839
            payload._options = _.extend({critical: false}, options);
840
            
841
            // reset firewall state on error
842
            var error_cb = _.bind(function() {
843
                thi
844
            }, this);
845

    
846
            this.api.call(this.api_path() + "/action", "create", payload, callback, error);
847
            storage.networks.get(net_id).update_state();
848
        },
849

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

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

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

    
959
        get_network_info: function(net_id) {
960
            var net_id = net_id || "public";
961
            
962
            if (!this.networks.network_ids.length) { return {} };
963

    
964
            var addresses = this.networks.get();
965
            try {
966
                return _.select(addresses, function(net, key){return key == net_id })[0];
967
            } catch (err) {
968
                //this.log.debug("Cannot find network {0}".format(net_id))
969
            }
970
        },
971

    
972
        firewall_profile: function(net_id) {
973
            var net_id = net_id || "public";
974
            var firewalls = this.get("firewalls");
975
            return firewalls[net_id];
976
        },
977

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

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

    
1022
        // action helper
1023
        call: function(action_name, success, error) {
1024
            var id_param = [this.id];
1025

    
1026
            success = success || function() {};
1027
            error = error || function() {};
1028

    
1029
            var self = this;
1030

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

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

    
1112
        handle_action_succeed: function() {
1113
            this.trigger("action:success", arguments);
1114
        },
1115
        
1116
        reset_action_error: function() {
1117
            this.action_error = false;
1118
            this.trigger("action:fail:reset", this.action_error);
1119
        },
1120

    
1121
        handle_action_fail: function() {
1122
            this.action_error = arguments;
1123
            this.trigger("action:fail", arguments);
1124
        },
1125

    
1126
        get_action_url: function(name) {
1127
            return this.url() + "/action";
1128
        },
1129

    
1130
        get_connection_info: function(host_os, success, error) {
1131
            var url = "/machines/connect";
1132
            params = {
1133
                ip_address: this.get_addresses().ip4,
1134
                os: this.get_os(),
1135
                host_os: host_os,
1136
                srv: this.id
1137
            }
1138

    
1139
            url = url + "?" + $.param(params);
1140

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

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

    
1174
    // api status values
1175
    models.VM.STATUSES = [
1176
        'UNKNWON',
1177
        'BUILD',
1178
        'REBOOT',
1179
        'STOPPED',
1180
        'ACTIVE',
1181
        'ERROR',
1182
        'DELETED'
1183
    ]
1184

    
1185
    // api status values
1186
    models.VM.CONNECT_STATES = [
1187
        'ACTIVE',
1188
        'REBOOT',
1189
        'SHUTDOWN'
1190
    ]
1191

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

    
1218
    models.VM.TRANSITION_STATES = [
1219
        'DESTROY',
1220
        'SHUTDOWN',
1221
        'START',
1222
        'REBOOT',
1223
        'BUILD'
1224
    ]
1225

    
1226
    models.VM.ACTIVE_STATES = [
1227
        'BUILD', 'REBOOT', 'ACTIVE',
1228
        'BUILD_INIT', 'BUILD_COPY', 'BUILD_FINAL',
1229
        'SHUTDOWN', 'CONNECT', 'DISCONNECT'
1230
    ]
1231

    
1232
    models.VM.BUILDING_STATES = [
1233
        'BUILD', 'BUILD_INIT', 'BUILD_COPY', 'BUILD_FINAL'
1234
    ]
1235

    
1236
    models.Networks = models.Collection.extend({
1237
        model: models.Network,
1238
        path: 'networks',
1239
        details: true,
1240
        //noUpdate: true,
1241
        defaults: {'linked_to':[]},
1242

    
1243
        parse: function (resp, xhr) {
1244
            // FIXME: depricated global var
1245
            if (!resp) { return []};
1246
               
1247
            var data = _.map(resp.networks.values, _.bind(this.parse_net_api_data, this));
1248
            return data;
1249
        },
1250

    
1251
        parse_net_api_data: function(data) {
1252
            if (data.servers && data.servers.values) {
1253
                data['linked_to'] = data.servers.values;
1254
            }
1255
            return data;
1256
        },
1257

    
1258
        create: function (name, callback) {
1259
            return this.api.call(this.path, "create", {network:{name:name}}, callback);
1260
        }
1261
    })
1262

    
1263
    models.Images = models.Collection.extend({
1264
        model: models.Image,
1265
        path: 'images',
1266
        details: true,
1267
        noUpdate: true,
1268
        
1269
        meta_keys_as_attrs: ["OS", "description", "kernel", "size", "GUI"],
1270

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

    
1284
        parse: function (resp, xhr) {
1285
            // FIXME: depricated global var
1286
            var data = _.map(resp.images.values, _.bind(this.parse_meta, this));
1287
            return resp.images.values;
1288
        },
1289

    
1290
        get_meta_key: function(img, key) {
1291
            if (img.metadata && img.metadata.values && img.metadata.values[key]) {
1292
                return img.metadata.values[key];
1293
            }
1294
            return undefined;
1295
        },
1296

    
1297
        comparator: function(img) {
1298
            return -img.get_sort_order("sortorder") || 1000 * img.id;
1299
        },
1300

    
1301
        parse_meta: function(img) {
1302
            _.each(this.meta_keys_as_attrs, _.bind(function(key){
1303
                img[key] = this.get_meta_key(img, key);
1304
            }, this));
1305
            return img;
1306
        },
1307

    
1308
        active: function() {
1309
            return this.filter(function(img){return img.get('status') != "DELETED"});
1310
        }
1311
    })
1312

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

    
1333
        parse: function (resp, xhr) {
1334
            // FIXME: depricated global var
1335
            return resp.flavors.values;
1336
        },
1337

    
1338
        comparator: function(flv) {
1339
            return flv.get("disk") * flv.get("cpu") * flv.get("ram");
1340
        },
1341

    
1342
        unavailable_values_for_image: function(img, flavors) {
1343
            var flavors = flavors || this.active();
1344
            var size = img.get_size();
1345
            
1346
            var index = {cpu:[], disk:[], ram:[]};
1347

    
1348
            _.each(this.active(), function(el) {
1349
                var img_size = size;
1350
                var flv_size = el.get_disk_size();
1351
                if (flv_size < img_size) {
1352
                    if (index.disk.indexOf(flv_size) == -1) {
1353
                        index.disk.push(flv_size);
1354
                    }
1355
                };
1356
            });
1357
            
1358
            return index;
1359
        },
1360

    
1361
        get_flavor: function(cpu, mem, disk, filter_list) {
1362
            if (!filter_list) { filter_list = this.models };
1363

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

    
1375
            _.each(lst, function(flv) {
1376
                if (data.cpu.indexOf(flv.get("cpu")) == -1) {
1377
                    data.cpu.push(flv.get("cpu"));
1378
                }
1379
                if (data.mem.indexOf(flv.get("ram")) == -1) {
1380
                    data.mem.push(flv.get("ram"));
1381
                }
1382
                if (data.disk.indexOf(flv.get("disk")) == -1) {
1383
                    data.disk.push(flv.get("disk"));
1384
                }
1385
            })
1386
            
1387
            return data;
1388
        },
1389

    
1390
        active: function() {
1391
            return this.filter(function(flv){return flv.get('status') != "DELETED"});
1392
        }
1393
            
1394
    })
1395

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

    
1414
        has_pending_actions: function() {
1415
            return this.filter(function(vm){return vm.pending_action}).length > 0;
1416
        },
1417

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

    
1438
        has_addresses: function(vm_data) {
1439
            return vm_data.metadata && vm_data.metadata.values
1440
        },
1441

    
1442
        parse_vm_api_data: function(data) {
1443
            // do not add non existing DELETED entries
1444
            if (data.status && data.status == "DELETED") {
1445
                if (!this.get(data.id)) {
1446
                    console.error("non exising deleted vm", data)
1447
                    return false;
1448
                }
1449
            }
1450

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

    
1473
            return data;
1474
        },
1475

    
1476
        create: function (name, image, flavor, meta, extra, callback) {
1477
            if (this.copy_image_meta) {
1478
                meta['OS'] = image.get("OS");
1479
           }
1480
            
1481
            opts = {name: name, imageRef: image.id, flavorRef: flavor.id, metadata:meta}
1482
            opts = _.extend(opts, extra);
1483

    
1484
            this.api.call(this.path, "create", {'server': opts}, undefined, undefined, callback, {critical: false});
1485
        }
1486

    
1487
    })
1488
    
1489

    
1490
    // storage initialization
1491
    snf.storage.images = new models.Images();
1492
    snf.storage.flavors = new models.Flavors();
1493
    snf.storage.networks = new models.Networks();
1494
    snf.storage.vms = new models.VMS();
1495

    
1496
    //snf.storage.vms.fetch({update:true});
1497
    //snf.storage.images.fetch({update:true});
1498
    //snf.storage.flavors.fetch({update:true});
1499

    
1500
})(this);