Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (93.6 kB)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
305
        get_created_users: function() {
306
            try {
307
              var users = this.get_meta('users').split(" ");
308
            } catch (err) { users = null }
309
            if (!users) {
310
                var osfamily = this.get_meta('osfamily');
311
                if (osfamily == 'windows') { 
312
                  users = ['Administrator'];
313
                } else {
314
                  users = ['root'];
315
                }
316
            }
317
            return users;
318
        },
319

    
320
        get_sort_order: function() {
321
            return parseInt(this.get('metadata') ? this.get('metadata').sortorder : -1)
322
        },
323

    
324
        get_vm: function() {
325
            var vm_id = this.get("serverRef");
326
            var vm = undefined;
327
            vm = storage.vms.get(vm_id);
328
            return vm;
329
        },
330

    
331
        is_public: function() {
332
            return this.get('is_public') == undefined ? true : this.get('is_public');
333
        },
334

    
335
        is_deleted: function() {
336
            return this.get('status') == "DELETED"
337
        },
338
        
339
        ssh_keys_paths: function() {
340
            return _.map(this.get_created_users(), function(username) {
341
                prepend = '';
342
                if (username != 'root') {
343
                    prepend = '/home'
344
                }
345
                return {'user': username, 'path': '{1}/{0}/.ssh/authorized_keys'.format(username, 
346
                                                             prepend)};
347
            });
348
        },
349

    
350
        _supports_ssh: function() {
351
            if (synnefo.config.support_ssh_os_list.indexOf(this.get_os()) > -1) {
352
                return true;
353
            }
354
            if (this.get_meta('osfamily') == 'linux') {
355
              return true;
356
            }
357
            return false;
358
        },
359

    
360
        supports: function(feature) {
361
            if (feature == "ssh") {
362
                return this._supports_ssh()
363
            }
364
            return false;
365
        },
366

    
367
        personality_data_for_keys: function(keys) {
368
            return _.map(this.ssh_keys_paths(), function(pathinfo) {
369
                var contents = '';
370
                _.each(keys, function(key){
371
                    contents = contents + key.get("content") + "\n"
372
                });
373
                contents = $.base64.encode(contents);
374

    
375
                return {
376
                    path: pathinfo.path,
377
                    contents: contents,
378
                    mode: 0600,
379
                    owner: pathinfo.user
380
                }
381
            });
382
        }
383
    });
384

    
385
    // Flavor model
386
    models.Flavor = models.Model.extend({
387
        path: 'flavors',
388

    
389
        details_string: function() {
390
            return "{0} CPU, {1}MB, {2}GB".format(this.get('cpu'), this.get('ram'), this.get('disk'));
391
        },
392

    
393
        get_disk_size: function() {
394
            return parseInt(this.get("disk") * 1000)
395
        },
396

    
397
        get_ram_size: function() {
398
            return parseInt(this.get("ram"))
399
        },
400

    
401
        get_disk_template_info: function() {
402
            var info = snf.config.flavors_disk_templates_info[this.get("disk_template")];
403
            if (!info) {
404
                info = { name: this.get("disk_template"), description:'' };
405
            }
406
            return info
407
        },
408

    
409
        disk_to_bytes: function() {
410
            return parseInt(this.get("disk")) * 1024 * 1024 * 1024;
411
        },
412

    
413
        ram_to_bytes: function() {
414
            return parseInt(this.get("ram")) * 1024 * 1024;
415
        },
416

    
417
    });
418
    
419
    models.ParamsList = function(){this.initialize.apply(this, arguments)};
420
    _.extend(models.ParamsList.prototype, bb.Events, {
421

    
422
        initialize: function(parent, param_name) {
423
            this.parent = parent;
424
            this.actions = {};
425
            this.param_name = param_name;
426
            this.length = 0;
427
        },
428
        
429
        has_action: function(action) {
430
            return this.actions[action] ? true : false;
431
        },
432
            
433
        _parse_params: function(arguments) {
434
            if (arguments.length <= 1) {
435
                return [];
436
            }
437

    
438
            var args = _.toArray(arguments);
439
            return args.splice(1);
440
        },
441

    
442
        contains: function(action, params) {
443
            params = this._parse_params(arguments);
444
            var has_action = this.has_action(action);
445
            if (!has_action) { return false };
446

    
447
            var paramsEqual = false;
448
            _.each(this.actions[action], function(action_params) {
449
                if (_.isEqual(action_params, params)) {
450
                    paramsEqual = true;
451
                }
452
            });
453
                
454
            return paramsEqual;
455
        },
456
        
457
        is_empty: function() {
458
            return _.isEmpty(this.actions);
459
        },
460

    
461
        add: function(action, params) {
462
            params = this._parse_params(arguments);
463
            if (this.contains.apply(this, arguments)) { return this };
464
            var isnew = false
465
            if (!this.has_action(action)) {
466
                this.actions[action] = [];
467
                isnew = true;
468
            };
469

    
470
            this.actions[action].push(params);
471
            this.parent.trigger("change:" + this.param_name, this.parent, this);
472
            if (isnew) {
473
                this.trigger("add", action, params);
474
            } else {
475
                this.trigger("change", action, params);
476
            }
477
            return this;
478
        },
479
        
480
        remove_all: function(action) {
481
            if (this.has_action(action)) {
482
                delete this.actions[action];
483
                this.parent.trigger("change:" + this.param_name, this.parent, this);
484
                this.trigger("remove", action);
485
            }
486
            return this;
487
        },
488

    
489
        reset: function() {
490
            this.actions = {};
491
            this.parent.trigger("change:" + this.param_name, this.parent, this);
492
            this.trigger("reset");
493
            this.trigger("remove");
494
        },
495

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

    
516
    });
517

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

    
537
        toJSON: function() {
538
            var attrs = _.clone(this.attributes);
539
            attrs.actions = _.clone(this.get("actions").actions);
540
            return attrs;
541
        },
542
        
543
        set_state: function(val) {
544
            if (val == "PENDING" && this.get("state") == "DESTORY") {
545
                return "DESTROY";
546
            }
547
            return val;
548
        },
549

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

    
573
        is_public: function() {
574
            return this.get("public");
575
        },
576

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

    
587
        increase_connecting: function() {
588
            var conn = this.get("connecting");
589
            if (!conn) { conn = 0 };
590
            conn++;
591
            this.set({"connecting": conn});
592
            this.update_state();
593
        },
594

    
595
        connected_to: function(vm) {
596
            return this.get('linked_to').indexOf(""+vm.id) > -1;
597
        },
598

    
599
        connected_with_nic_id: function(nic_id) {
600
            return _.keys(this.get('nics')).indexOf(nic_id) > -1;
601
        },
602

    
603
        get_nics: function(filter) {
604
            var nics = synnefo.storage.nics.filter(function(nic) {
605
                return nic.get('network_id') == this.id;
606
            }, this);
607

    
608
            if (filter) {
609
                return _.filter(nics, filter);
610
            }
611
            return nics;
612
        },
613

    
614
        contains_firewalling_nics: function() {
615
            return this.get_nics(function(n){return n.get('pending_firewall')}).length
616
        },
617

    
618
        call: function(action, params, success, error) {
619
            if (action == "destroy") {
620
                var previous_state = this.get('state');
621
                var previous_status = this.get('status');
622

    
623
                this.set({state:"DESTROY"});
624

    
625
                var _success = _.bind(function() {
626
                    if (success) { success() };
627
                    synnefo.storage.quotas.get('cyclades.network.private').decrease();
628
                }, this);
629
                var _error = _.bind(function() {
630
                    this.set({state: previous_state, status: previous_status})
631
                    if (error) { error() };
632
                }, this);
633

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

    
652
        add_vm: function (vm, callback, error, options) {
653
            var payload = {add:{serverRef:"" + vm.id}};
654
            payload._options = options || {};
655
            return this.api_call(this.api_path() + "/action", "create", 
656
                                 payload,
657
                                 undefined,
658
                                 error,
659
                                 _.bind(function(){
660
                                     //this.vms.add_pending(vm.id);
661
                                     this.increase_connecting();
662
                                     if (callback) {callback()}
663
                                 },this), error);
664
        },
665

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

    
681
        rename: function(name, callback) {
682
            return this.api_call(this.api_path(), "update", {
683
                network:{name:name}, 
684
                _options:{
685
                    critical: false, 
686
                    error_params:{
687
                        title: "Network action failed",
688
                        ns: "Networks",
689
                        extra_details: {"Network id": this.id}
690
                    }
691
                }}, callback);
692
        },
693

    
694
        get_connectable_vms: function() {
695
            return storage.vms.filter(function(vm){
696
                return !vm.in_error_state() && !vm.is_building();
697
            });
698
        },
699

    
700
        state_message: function() {
701
            if (this.get("state") == "ACTIVE" && !this.is_public()) {
702
                if (this.get("cidr") && this.get("dhcp") == true) {
703
                    return this.get("cidr");
704
                } else {
705
                    return "Private network";
706
                }
707
            }
708
            if (this.get("state") == "ACTIVE" && this.is_public()) {
709
                  return "Public network";
710
            }
711

    
712
            return models.Network.STATES[this.get("state")];
713
        },
714

    
715
        in_progress: function() {
716
            return models.Network.STATES_TRANSITIONS[this.get("state")] != undefined;
717
        },
718

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

    
742
    models.Network.STATES_TRANSITIONS = {
743
        'CONNECTING': ['ACTIVE'],
744
        'DISCONNECTING': ['ACTIVE'],
745
        'PENDING': ['ACTIVE'],
746
        'FIREWALLING': ['ACTIVE']
747
    }
748

    
749
    // Virtualmachine model
750
    models.VM = models.Model.extend({
751

    
752
        path: 'servers',
753
        has_status: true,
754
        initialize: function(params) {
755
            
756
            this.pending_firewalls = {};
757
            
758
            models.VM.__super__.initialize.apply(this, arguments);
759

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

    
777
            // initialize interval
778
            this.init_stats_intervals(this.stats_update_interval);
779
            
780
            // handle progress message on instance change
781
            this.bind("change", _.bind(this.update_status_message, this));
782
            this.bind("change:task_state", _.bind(this.update_status, this));
783
            // force update of progress message
784
            this.update_status_message(true);
785
            
786
            // default values
787
            this.bind("change:state", _.bind(function(){
788
                if (this.state() == "DESTROY") { 
789
                    this.handle_destroy() 
790
                }
791
            }, this));
792

    
793
            this.bind("change:nics", _.bind(synnefo.storage.nics.update_vm_nics, synnefo.storage.nics));
794
        },
795

    
796
        status: function(st) {
797
            if (!st) { return this.get("status")}
798
            return this.set({status:st});
799
        },
800
        
801
        update_status: function() {
802
            this.set_status(this.get('status'));
803
        },
804

    
805
        set_status: function(st) {
806
            var new_state = this.state_for_api_status(st);
807
            var transition = false;
808

    
809
            if (this.state() != new_state) {
810
                if (models.VM.STATES_TRANSITIONS[this.state()]) {
811
                    transition = this.state();
812
                }
813
            }
814
            
815
            // call it silently to avoid double change trigger
816
            var state = this.state_for_api_status(st);
817
            this.set({'state': state}, {silent: true});
818
            
819
            // trigger transition
820
            if (transition && models.VM.TRANSITION_STATES.indexOf(new_state) == -1) { 
821
                this.trigger("transition", {from:transition, to:new_state}) 
822
            };
823
            return st;
824
        },
825
            
826
        get_diagnostics: function(success) {
827
            this.__make_api_call(this.get_diagnostics_url(),
828
                                 "read", // create so that sync later uses POST to make the call
829
                                 null, // payload
830
                                 function(data) {
831
                                     success(data);
832
                                 },  
833
                                 null, 'diagnostics');
834
        },
835

    
836
        has_diagnostics: function() {
837
            return this.get("diagnostics") && this.get("diagnostics").length;
838
        },
839

    
840
        get_progress_info: function() {
841
            // details about progress message
842
            // contains a list of diagnostic messages
843
            return this.get("status_messages");
844
        },
845

    
846
        get_status_message: function() {
847
            return this.get('status_message');
848
        },
849
        
850
        // extract status message from diagnostics
851
        status_message_from_diagnostics: function(diagnostics) {
852
            var valid_sources_map = synnefo.config.diagnostics_status_messages_map;
853
            var valid_sources = valid_sources_map[this.get('status')];
854
            if (!valid_sources) { return null };
855
            
856
            // filter messsages based on diagnostic source
857
            var messages = _.filter(diagnostics, function(diag) {
858
                return valid_sources.indexOf(diag.source) > -1;
859
            });
860

    
861
            var msg = messages[0];
862
            if (msg) {
863
              var message = msg.message;
864
              var message_tpl = snf.config.diagnostic_messages_tpls[msg.source];
865

    
866
              if (message_tpl) {
867
                  message = message_tpl.replace('MESSAGE', msg.message);
868
              }
869
              return message;
870
            }
871
            
872
            // no message to display, but vm in build state, display
873
            // finalizing message.
874
            if (this.is_building() == 'BUILD') {
875
                return synnefo.config.BUILDING_MESSAGES['FINAL'];
876
            }
877
            return null;
878
        },
879

    
880
        update_status_message: function(force) {
881
            // update only if one of the specified attributes has changed
882
            if (
883
              !this.keysChanged(['diagnostics', 'progress', 'status', 'state'])
884
                && !force
885
            ) { return };
886
            
887
            // if user requested to destroy the vm set the appropriate 
888
            // message.
889
            if (this.get('state') == "DESTROY") { 
890
                message = "Terminating..."
891
                this.set({status_message: message})
892
                return;
893
            }
894
            
895
            // set error message, if vm has diagnostic message display it as
896
            // progress message
897
            if (this.in_error_state()) {
898
                var d = this.get('diagnostics');
899
                if (d && d.length) {
900
                    var message = this.status_message_from_diagnostics(d);
901
                    this.set({status_message: message});
902
                } else {
903
                    this.set({status_message: null});
904
                }
905
                return;
906
            }
907
            
908
            // identify building status message
909
            if (this.is_building()) {
910
                var self = this;
911
                var success = function(msg) {
912
                    self.set({status_message: msg});
913
                }
914
                this.get_building_status_message(success);
915
                return;
916
            }
917

    
918
            this.set({status_message:null});
919
        },
920
            
921
        // get building status message. Asynchronous function since it requires
922
        // access to vm image.
923
        get_building_status_message: function(callback) {
924
            // no progress is set, vm is in initial build status
925
            var progress = this.get("progress");
926
            if (progress == 0 || !progress) {
927
                return callback(BUILDING_MESSAGES['INIT']);
928
            }
929
            
930
            // vm has copy progress, display copy percentage
931
            if (progress > 0 && progress <= 99) {
932
                this.get_copy_details(true, undefined, _.bind(
933
                    function(details){
934
                        callback(BUILDING_MESSAGES['COPY'].format(details.copy, 
935
                                                           details.size, 
936
                                                           details.progress));
937
                }, this));
938
                return;
939
            }
940

    
941
            // copy finished display FINAL message or identify status message
942
            // from diagnostics.
943
            if (progress >= 100) {
944
                if (!this.has_diagnostics()) {
945
                        callback(BUILDING_MESSAGES['FINAL']);
946
                } else {
947
                        var d = this.get("diagnostics");
948
                        var msg = this.status_message_from_diagnostics(d);
949
                        if (msg) {
950
                              callback(msg);
951
                        }
952
                }
953
            }
954
        },
955

    
956
        get_copy_details: function(human, image, callback) {
957
            var human = human || false;
958
            var image = image || this.get_image(_.bind(function(image){
959
                var progress = this.get('progress');
960
                var size = image.get_size();
961
                var size_copied = (size * progress / 100).toFixed(2);
962
                
963
                if (human) {
964
                    size = util.readablizeBytes(size*1024*1024);
965
                    size_copied = util.readablizeBytes(size_copied*1024*1024);
966
                }
967

    
968
                callback({'progress': progress, 'size': size, 'copy': size_copied})
969
            }, this));
970
        },
971

    
972
        start_stats_update: function(force_if_empty) {
973
            var prev_state = this.do_update_stats;
974

    
975
            this.do_update_stats = true;
976
            
977
            // fetcher initialized ??
978
            if (!this.stats_fetcher) {
979
                this.init_stats_intervals();
980
            }
981

    
982

    
983
            // fetcher running ???
984
            if (!this.stats_fetcher.running || !prev_state) {
985
                this.stats_fetcher.start();
986
            }
987

    
988
            if (force_if_empty && this.get("stats") == undefined) {
989
                this.update_stats(true);
990
            }
991
        },
992

    
993
        stop_stats_update: function(stop_calls) {
994
            this.do_update_stats = false;
995

    
996
            if (stop_calls) {
997
                this.stats_fetcher.stop();
998
            }
999
        },
1000

    
1001
        // clear and reinitialize update interval
1002
        init_stats_intervals: function (interval) {
1003
            this.stats_fetcher = this.get_stats_fetcher(this.stats_update_interval);
1004
            this.stats_fetcher.start();
1005
        },
1006
        
1007
        get_stats_fetcher: function(timeout) {
1008
            var cb = _.bind(function(data){
1009
                this.update_stats();
1010
            }, this);
1011
            var fetcher = new snf.api.updateHandler({'callback': cb, interval: timeout, id:'stats'});
1012
            return fetcher;
1013
        },
1014

    
1015
        // do the api call
1016
        update_stats: function(force) {
1017
            // do not update stats if flag not set
1018
            if ((!this.do_update_stats && !force) || this.updating_stats) {
1019
                return;
1020
            }
1021

    
1022
            // make the api call, execute handle_stats_update on sucess
1023
            // TODO: onError handler ???
1024
            stats_url = this.url() + "/stats";
1025
            this.updating_stats = true;
1026
            this.sync("read", this, {
1027
                handles_error:true, 
1028
                url: stats_url, 
1029
                refresh:true, 
1030
                success: _.bind(this.handle_stats_update, this),
1031
                error: _.bind(this.handle_stats_error, this),
1032
                complete: _.bind(function(){this.updating_stats = false;}, this),
1033
                critical: false,
1034
                log_error: false,
1035
                skips_timeouts: true
1036
            });
1037
        },
1038

    
1039
        get_stats_image: function(stat, type) {
1040
        },
1041
        
1042
        _set_stats: function(stats) {
1043
            var silent = silent === undefined ? false : silent;
1044
            // unavailable stats while building
1045
            if (this.get("status") == "BUILD") { 
1046
                this.stats_available = false;
1047
            } else { this.stats_available = true; }
1048

    
1049
            if (this.get("status") == "DESTROY") { this.stats_available = false; }
1050
            
1051
            this.set({stats: stats}, {silent:true});
1052
            this.trigger("stats:update", stats);
1053
        },
1054

    
1055
        unbind: function() {
1056
            models.VM.__super__.unbind.apply(this, arguments);
1057
        },
1058

    
1059
        can_resize: function() {
1060
          return this.get('status') == 'STOPPED';
1061
        },
1062

    
1063
        handle_stats_error: function() {
1064
            stats = {};
1065
            _.each(['cpuBar', 'cpuTimeSeries', 'netBar', 'netTimeSeries'], function(k) {
1066
                stats[k] = false;
1067
            });
1068

    
1069
            this.set({'stats': stats});
1070
        },
1071

    
1072
        // this method gets executed after a successful vm stats api call
1073
        handle_stats_update: function(data) {
1074
            var self = this;
1075
            // avoid browser caching
1076
            
1077
            if (data.stats && _.size(data.stats) > 0) {
1078
                var ts = $.now();
1079
                var stats = data.stats;
1080
                var images_loaded = 0;
1081
                var images = {};
1082

    
1083
                function check_images_loaded() {
1084
                    images_loaded++;
1085

    
1086
                    if (images_loaded == 4) {
1087
                        self._set_stats(images);
1088
                    }
1089
                }
1090
                _.each(['cpuBar', 'cpuTimeSeries', 'netBar', 'netTimeSeries'], function(k) {
1091
                    
1092
                    stats[k] = stats[k] + "?_=" + ts;
1093
                    
1094
                    var stat = k.slice(0,3);
1095
                    var type = k.slice(3,6) == "Bar" ? "bar" : "time";
1096
                    var img = $("<img />");
1097
                    var val = stats[k];
1098
                    
1099
                    // load stat image to a temporary dom element
1100
                    // update model stats on image load/error events
1101
                    img.load(function() {
1102
                        images[k] = val;
1103
                        check_images_loaded();
1104
                    });
1105

    
1106
                    img.error(function() {
1107
                        images[stat + type] = false;
1108
                        check_images_loaded();
1109
                    });
1110

    
1111
                    img.attr({'src': stats[k]});
1112
                })
1113
                data.stats = stats;
1114
            }
1115

    
1116
            // do we need to change the interval ??
1117
            if (data.stats.refresh * 1000 != this.stats_update_interval) {
1118
                this.stats_update_interval = data.stats.refresh * 1000;
1119
                this.stats_fetcher.interval = this.stats_update_interval;
1120
                this.stats_fetcher.maximum_interval = this.stats_update_interval;
1121
                this.stats_fetcher.stop();
1122
                this.stats_fetcher.start(false);
1123
            }
1124
        },
1125

    
1126
        // helper method that sets the do_update_stats
1127
        // in the future this method could also make an api call
1128
        // immediaetly if needed
1129
        enable_stats_update: function() {
1130
            this.do_update_stats = true;
1131
        },
1132
        
1133
        handle_destroy: function() {
1134
            this.stats_fetcher.stop();
1135
        },
1136

    
1137
        require_reboot: function() {
1138
            if (this.is_active()) {
1139
                this.set({'reboot_required': true});
1140
            }
1141
        },
1142
        
1143
        set_pending_action: function(data) {
1144
            this.pending_action = data;
1145
            return data;
1146
        },
1147

    
1148
        // machine has pending action
1149
        update_pending_action: function(action, force) {
1150
            this.set({pending_action: action});
1151
        },
1152

    
1153
        clear_pending_action: function() {
1154
            this.set({pending_action: undefined});
1155
        },
1156

    
1157
        has_pending_action: function() {
1158
            return this.get("pending_action") ? this.get("pending_action") : false;
1159
        },
1160
        
1161
        // machine is active
1162
        is_active: function() {
1163
            return models.VM.ACTIVE_STATES.indexOf(this.state()) > -1;
1164
        },
1165
        
1166
        // machine is building 
1167
        is_building: function() {
1168
            return models.VM.BUILDING_STATES.indexOf(this.state()) > -1;
1169
        },
1170
        
1171
        in_error_state: function() {
1172
            return this.state() === "ERROR"
1173
        },
1174

    
1175
        // user can connect to machine
1176
        is_connectable: function() {
1177
            // check if ips exist
1178
            if (!this.get_addresses().ip4 && !this.get_addresses().ip6) {
1179
                return false;
1180
            }
1181
            return models.VM.CONNECT_STATES.indexOf(this.state()) > -1;
1182
        },
1183
        
1184
        remove_meta: function(key, complete, error) {
1185
            var url = this.api_path() + "/metadata/" + key;
1186
            this.api_call(url, "delete", undefined, complete, error);
1187
        },
1188

    
1189
        save_meta: function(meta, complete, error) {
1190
            var url = this.api_path() + "/metadata/" + meta.key;
1191
            var payload = {meta:{}};
1192
            payload.meta[meta.key] = meta.value;
1193
            payload._options = {
1194
                critical:false, 
1195
                error_params: {
1196
                    title: "Machine metadata error",
1197
                    extra_details: {"Machine id": this.id}
1198
            }};
1199

    
1200
            this.api_call(url, "update", payload, complete, error);
1201
        },
1202

    
1203

    
1204
        // update/get the state of the machine
1205
        state: function() {
1206
            var args = slice.call(arguments);
1207
                
1208
            // TODO: it might not be a good idea to set the state in set_state method
1209
            if (args.length > 0 && models.VM.STATES.indexOf(args[0]) > -1) {
1210
                this.set({'state': args[0]});
1211
            }
1212

    
1213
            return this.get('state');
1214
        },
1215
        
1216
        // get the state that the api status corresponds to
1217
        state_for_api_status: function(status) {
1218
            return this.state_transition(this.state(), status);
1219
        },
1220
        
1221
        // get transition state for the corresponging api status
1222
        state_transition: function(state, new_status) {
1223
            var statuses = models.VM.STATES_TRANSITIONS[state];
1224
            if (statuses) {
1225
                if (statuses.indexOf(new_status) > -1) {
1226
                    return new_status;
1227
                } else {
1228
                    return state;
1229
                }
1230
            } else {
1231
                return new_status;
1232
            }
1233
        },
1234
        
1235
        // the current vm state is a transition state
1236
        in_transition: function() {
1237
            return models.VM.TRANSITION_STATES.indexOf(this.state()) > -1 || 
1238
                models.VM.TRANSITION_STATES.indexOf(this.get('status')) > -1;
1239
        },
1240
        
1241
        // get image object
1242
        get_image: function(callback) {
1243
            if (callback == undefined) { callback = function(){} }
1244
            var image = storage.images.get(this.get('image'));
1245
            if (!image) {
1246
                storage.images.update_unknown_id(this.get('image'), callback);
1247
                return;
1248
            }
1249
            callback(image);
1250
            return image;
1251
        },
1252
        
1253
        // get flavor object
1254
        get_flavor: function() {
1255
            var flv = storage.flavors.get(this.get('flavor'));
1256
            if (!flv) {
1257
                storage.flavors.update_unknown_id(this.get('flavor'));
1258
                flv = storage.flavors.get(this.get('flavor'));
1259
            }
1260
            return flv;
1261
        },
1262

    
1263
        get_resize_flavors: function() {
1264
          var vm_flavor = this.get_flavor();
1265
          var flavors = synnefo.storage.flavors.filter(function(f){
1266
              return f.get('disk_template') ==
1267
              vm_flavor.get('disk_template') && f.get('disk') ==
1268
              vm_flavor.get('disk');
1269
          });
1270
          return flavors;
1271
        },
1272

    
1273
        get_flavor_quotas: function() {
1274
          var flavor = this.get_flavor();
1275
          return {
1276
            cpu: flavor.get('cpu') + 1, 
1277
            ram: flavor.get_ram_size() + 1, 
1278
            disk:flavor.get_disk_size() + 1
1279
          }
1280
        },
1281

    
1282
        get_meta: function(key, deflt) {
1283
            if (this.get('metadata') && this.get('metadata')) {
1284
                if (!this.get('metadata')[key]) { return deflt }
1285
                return _.escape(this.get('metadata')[key]);
1286
            } else {
1287
                return deflt;
1288
            }
1289
        },
1290

    
1291
        get_meta_keys: function() {
1292
            if (this.get('metadata') && this.get('metadata')) {
1293
                return _.keys(this.get('metadata'));
1294
            } else {
1295
                return [];
1296
            }
1297
        },
1298
        
1299
        // get metadata OS value
1300
        get_os: function() {
1301
            var image = this.get_image();
1302
            return this.get_meta('OS') || (image ? 
1303
                                            image.get_os() || "okeanos" : "okeanos");
1304
        },
1305

    
1306
        get_gui: function() {
1307
            return this.get_meta('GUI');
1308
        },
1309
        
1310
        connected_to: function(net) {
1311
            return this.get('linked_to').indexOf(net.id) > -1;
1312
        },
1313

    
1314
        connected_with_nic_id: function(nic_id) {
1315
            return _.keys(this.get('nics')).indexOf(nic_id) > -1;
1316
        },
1317

    
1318
        get_nics: function(filter) {
1319
            ret = synnefo.storage.nics.filter(function(nic) {
1320
                return parseInt(nic.get('vm_id')) == this.id;
1321
            }, this);
1322

    
1323
            if (filter) {
1324
                return _.filter(ret, filter);
1325
            }
1326

    
1327
            return ret;
1328
        },
1329

    
1330
        get_net_nics: function(net_id) {
1331
            return this.get_nics(function(n){return n.get('network_id') == net_id});
1332
        },
1333

    
1334
        get_public_nic: function() {
1335
            return this.get_nics(function(n){ return n.get_network().is_public() === true })[0];
1336
        },
1337

    
1338
        get_hostname: function() {
1339
          var hostname = this.get_meta('hostname');
1340
          if (!hostname) {
1341
            if (synnefo.config.vm_hostname_format) {
1342
              hostname = synnefo.config.vm_hostname_format.format(this.id);
1343
            } else {
1344
              hostname = this.get_public_nic().get('ipv4');
1345
            }
1346
          }
1347
          return hostname;
1348
        },
1349

    
1350
        get_nic: function(net_id) {
1351
        },
1352

    
1353
        has_firewall: function() {
1354
            var nic = this.get_public_nic();
1355
            if (nic) {
1356
                var profile = nic.get('firewallProfile'); 
1357
                return ['ENABLED', 'PROTECTED'].indexOf(profile) > -1;
1358
            }
1359
            return false;
1360
        },
1361

    
1362
        get_firewall_profile: function() {
1363
            var nic = this.get_public_nic();
1364
            if (nic) {
1365
                return nic.get('firewallProfile');
1366
            }
1367
            return null;
1368
        },
1369

    
1370
        get_addresses: function() {
1371
            var pnic = this.get_public_nic();
1372
            if (!pnic) { return {'ip4': undefined, 'ip6': undefined }};
1373
            return {'ip4': pnic.get('ipv4'), 'ip6': pnic.get('ipv6')};
1374
        },
1375
    
1376
        // get actions that the user can execute
1377
        // depending on the vm state/status
1378
        get_available_actions: function() {
1379
            return models.VM.AVAILABLE_ACTIONS[this.state()];
1380
        },
1381

    
1382
        set_profile: function(profile, net_id) {
1383
        },
1384
        
1385
        // call rename api
1386
        rename: function(new_name) {
1387
            //this.set({'name': new_name});
1388
            this.sync("update", this, {
1389
                critical: true,
1390
                data: {
1391
                    'server': {
1392
                        'name': new_name
1393
                    }
1394
                }, 
1395
                // do the rename after the method succeeds
1396
                success: _.bind(function(){
1397
                    //this.set({name: new_name});
1398
                    snf.api.trigger("call");
1399
                }, this)
1400
            });
1401
        },
1402
        
1403
        get_console_url: function(data) {
1404
            var url_params = {
1405
                machine: this.get("name"),
1406
                host_ip: this.get_addresses().ip4,
1407
                host_ip_v6: this.get_addresses().ip6,
1408
                host: data.host,
1409
                port: data.port,
1410
                password: data.password
1411
            }
1412
            return synnefo.config.ui_console_url + '?' + $.param(url_params);
1413
        },
1414

    
1415
        // action helper
1416
        call: function(action_name, success, error, params) {
1417
            var id_param = [this.id];
1418
            
1419
            params = params || {};
1420
            success = success || function() {};
1421
            error = error || function() {};
1422

    
1423
            var self = this;
1424

    
1425
            switch(action_name) {
1426
                case 'start':
1427
                    this.__make_api_call(this.get_action_url(), // vm actions url
1428
                                         "create", // create so that sync later uses POST to make the call
1429
                                         {start:{}}, // payload
1430
                                         function() {
1431
                                             // set state after successful call
1432
                                             self.state("START"); 
1433
                                             success.apply(this, arguments);
1434
                                             snf.api.trigger("call");
1435
                                         },  
1436
                                         error, 'start', params);
1437
                    break;
1438
                case 'reboot':
1439
                    this.__make_api_call(this.get_action_url(), // vm actions url
1440
                                         "create", // create so that sync later uses POST to make the call
1441
                                         {reboot:{type:"HARD"}}, // payload
1442
                                         function() {
1443
                                             // set state after successful call
1444
                                             self.state("REBOOT"); 
1445
                                             success.apply(this, arguments)
1446
                                             snf.api.trigger("call");
1447
                                             self.set({'reboot_required': false});
1448
                                         },
1449
                                         error, 'reboot', params);
1450
                    break;
1451
                case 'shutdown':
1452
                    this.__make_api_call(this.get_action_url(), // vm actions url
1453
                                         "create", // create so that sync later uses POST to make the call
1454
                                         {shutdown:{}}, // payload
1455
                                         function() {
1456
                                             // set state after successful call
1457
                                             self.state("SHUTDOWN"); 
1458
                                             success.apply(this, arguments)
1459
                                             snf.api.trigger("call");
1460
                                         },  
1461
                                         error, 'shutdown', params);
1462
                    break;
1463
                case 'console':
1464
                    this.__make_api_call(this.url() + "/action", "create", 
1465
                                         {'console': {'type':'vnc'}}, 
1466
                                         function(data) {
1467
                        var cons_data = data.console;
1468
                        success.apply(this, [cons_data]);
1469
                    }, undefined, 'console', params)
1470
                    break;
1471
                case 'destroy':
1472
                    this.__make_api_call(this.url(), // vm actions url
1473
                                         "delete", // create so that sync later uses POST to make the call
1474
                                         undefined, // payload
1475
                                         function() {
1476
                                             // set state after successful call
1477
                                             self.state('DESTROY');
1478
                                             success.apply(this, arguments);
1479
                                             synnefo.storage.quotas.get('cyclades.vm').decrease();
1480

    
1481
                                         },  
1482
                                         error, 'destroy', params);
1483
                    break;
1484
                case 'resize':
1485
                    this.__make_api_call(this.get_action_url(), // vm actions url
1486
                                         "create", // create so that sync later uses POST to make the call
1487
                                         {resize: {flavorRef:params.flavor}}, // payload
1488
                                         function() {
1489
                                             self.state('RESIZE');
1490
                                             success.apply(this, arguments);
1491
                                             snf.api.trigger("call");
1492
                                         },  
1493
                                         error, 'resize', params);
1494
                    break;
1495
                case 'addFloatingIp':
1496
                    this.__make_api_call(this.get_action_url(), // vm actions url
1497
                                         "create", // create so that sync later uses POST to make the call
1498
                                         {addFloatingIp: {address:params.address}}, // payload
1499
                                         function() {
1500
                                             self.state('CONNECT');
1501
                                             success.apply(this, arguments);
1502
                                             snf.api.trigger("call");
1503
                                         },  
1504
                                         error, 'addFloatingIp', params);
1505
                    break;
1506
                case 'removeFloatingIp':
1507
                    this.__make_api_call(this.get_action_url(), // vm actions url
1508
                                         "create", // create so that sync later uses POST to make the call
1509
                                         {removeFloatingIp: {address:params.address}}, // payload
1510
                                         function() {
1511
                                             self.state('DISCONNECT');
1512
                                             success.apply(this, arguments);
1513
                                             snf.api.trigger("call");
1514
                                         },  
1515
                                         error, 'addFloatingIp', params);
1516
                    break;
1517
                case 'destroy':
1518
                    this.__make_api_call(this.url(), // vm actions url
1519
                                         "delete", // create so that sync later uses POST to make the call
1520
                                         undefined, // payload
1521
                                         function() {
1522
                                             // set state after successful call
1523
                                             self.state('DESTROY');
1524
                                             success.apply(this, arguments);
1525
                                             synnefo.storage.quotas.get('cyclades.vm').decrease();
1526

    
1527
                                         },  
1528
                                         error, 'destroy', params);
1529
                    break;
1530
                default:
1531
                    throw "Invalid VM action ("+action_name+")";
1532
            }
1533
        },
1534
        
1535
        __make_api_call: function(url, method, data, success, error, action, 
1536
                                  extra_params) {
1537
            var self = this;
1538
            error = error || function(){};
1539
            success = success || function(){};
1540

    
1541
            var params = {
1542
                url: url,
1543
                data: data,
1544
                success: function() { 
1545
                  self.handle_action_succeed.apply(self, arguments); 
1546
                  success.apply(this, arguments)
1547
                },
1548
                error: function(){ self.handle_action_fail.apply(self, arguments); error.apply(this, arguments)},
1549
                error_params: { ns: "Machines actions", 
1550
                                title: "'" + this.get("name") + "'" + " " + action + " failed", 
1551
                                extra_details: {'Machine ID': this.id, 
1552
                                                'URL': url, 
1553
                                                'Action': action || "undefined" },
1554
                                allow_reload: false
1555
                              },
1556
                display: false,
1557
                critical: false
1558
            }
1559
            _.extend(params, extra_params);
1560
            this.sync(method, this, params);
1561
        },
1562

    
1563
        handle_action_succeed: function() {
1564
            this.trigger("action:success", arguments);
1565
        },
1566
        
1567
        reset_action_error: function() {
1568
            this.action_error = false;
1569
            this.trigger("action:fail:reset", this.action_error);
1570
        },
1571

    
1572
        handle_action_fail: function() {
1573
            this.action_error = arguments;
1574
            this.trigger("action:fail", arguments);
1575
        },
1576

    
1577
        get_action_url: function(name) {
1578
            return this.url() + "/action";
1579
        },
1580

    
1581
        get_diagnostics_url: function() {
1582
            return this.url() + "/diagnostics";
1583
        },
1584

    
1585
        get_users: function() {
1586
            var image;
1587
            var users = [];
1588
            try {
1589
              var users = this.get_meta('users').split(" ");
1590
            } catch (err) { users = null }
1591
            if (!users) {
1592
              image = this.get_image();
1593
              if (image) {
1594
                  users = image.get_created_users();
1595
              }
1596
            }
1597
            return users;
1598
        },
1599

    
1600
        get_connection_info: function(host_os, success, error) {
1601
            var url = synnefo.config.ui_connect_url;
1602
            var users = this.get_users();
1603

    
1604
            params = {
1605
                ip_address: this.get_public_nic().get('ipv4'),
1606
                hostname: this.get_hostname(),
1607
                os: this.get_os(),
1608
                host_os: host_os,
1609
                srv: this.id
1610
            }
1611
            
1612
            if (users.length) { 
1613
                params['username'] = _.last(users)
1614
            }
1615

    
1616
            url = url + "?" + $.param(params);
1617

    
1618
            var ajax = snf.api.sync("read", undefined, { url: url, 
1619
                                                         error:error, 
1620
                                                         success:success, 
1621
                                                         handles_error:1});
1622
        }
1623
    })
1624
    
1625
    models.VM.ACTIONS = [
1626
        'start',
1627
        'shutdown',
1628
        'reboot',
1629
        'console',
1630
        'destroy',
1631
        'resize'
1632
    ]
1633

    
1634
    models.VM.TASK_STATE_STATUS_MAP = {
1635
      'BULDING': 'BUILD',
1636
      'REBOOTING': 'REBOOT',
1637
      'STOPPING': 'SHUTDOWN',
1638
      'STARTING': 'START',
1639
      'RESIZING': 'RESIZE',
1640
      'CONNECTING': 'CONNECT',
1641
      'DISCONNECTING': 'DISCONNECT',
1642
      'DESTROYING': 'DESTROY'
1643
    }
1644

    
1645
    models.VM.AVAILABLE_ACTIONS = {
1646
        'UNKNWON'       : ['destroy'],
1647
        'BUILD'         : ['destroy'],
1648
        'REBOOT'        : ['destroy'],
1649
        'STOPPED'       : ['start', 'destroy'],
1650
        'ACTIVE'        : ['shutdown', 'destroy', 'reboot', 'console'],
1651
        'ERROR'         : ['destroy'],
1652
        'DELETED'       : ['destroy'],
1653
        'DESTROY'       : ['destroy'],
1654
        'SHUTDOWN'      : ['destroy'],
1655
        'START'         : ['destroy'],
1656
        'CONNECT'       : ['destroy'],
1657
        'DISCONNECT'    : ['destroy'],
1658
        'RESIZE'        : ['destroy']
1659
    }
1660

    
1661
    // api status values
1662
    models.VM.STATUSES = [
1663
        'UNKNWON',
1664
        'BUILD',
1665
        'REBOOT',
1666
        'STOPPED',
1667
        'ACTIVE',
1668
        'ERROR',
1669
        'DELETED',
1670
        'RESIZE'
1671
    ]
1672

    
1673
    // api status values
1674
    models.VM.CONNECT_STATES = [
1675
        'ACTIVE',
1676
        'REBOOT',
1677
        'SHUTDOWN'
1678
    ]
1679

    
1680
    // vm states
1681
    models.VM.STATES = models.VM.STATUSES.concat([
1682
        'DESTROY',
1683
        'SHUTDOWN',
1684
        'START',
1685
        'CONNECT',
1686
        'DISCONNECT',
1687
        'FIREWALL',
1688
        'RESIZE'
1689
    ]);
1690
    
1691
    models.VM.STATES_TRANSITIONS = {
1692
        'DESTROY' : ['DELETED'],
1693
        'SHUTDOWN': ['ERROR', 'STOPPED', 'DESTROY'],
1694
        'STOPPED': ['ERROR', 'ACTIVE', 'DESTROY'],
1695
        'ACTIVE': ['ERROR', 'STOPPED', 'REBOOT', 'SHUTDOWN', 'DESTROY'],
1696
        'START': ['ERROR', 'ACTIVE', 'DESTROY'],
1697
        'REBOOT': ['ERROR', 'ACTIVE', 'STOPPED', 'DESTROY'],
1698
        'BUILD': ['ERROR', 'ACTIVE', 'DESTROY'],
1699
        'RESIZE': ['ERROR', 'STOPPED']
1700
    }
1701

    
1702
    models.VM.TRANSITION_STATES = [
1703
        'DESTROY',
1704
        'SHUTDOWN',
1705
        'START',
1706
        'REBOOT',
1707
        'BUILD',
1708
        'RESIZE'
1709
    ]
1710

    
1711
    models.VM.ACTIVE_STATES = [
1712
        'BUILD', 'REBOOT', 'ACTIVE',
1713
        'SHUTDOWN', 'CONNECT', 'DISCONNECT'
1714
    ]
1715

    
1716
    models.VM.BUILDING_STATES = [
1717
        'BUILD'
1718
    ]
1719

    
1720
    models.Networks = models.Collection.extend({
1721
        model: models.Network,
1722
        path: 'networks',
1723
        details: true,
1724
        //noUpdate: true,
1725
        defaults: {'nics':[],'linked_to':[]},
1726
        
1727
        parse: function (resp, xhr) {
1728
            // FIXME: depricated global var
1729
            if (!resp) { return []};
1730
            var data = _.filter(_.map(resp.networks, _.bind(this.parse_net_api_data, this)),
1731
                               function(e){ return e });
1732
            return data;
1733
        },
1734

    
1735
        add: function() {
1736
            ret = models.Networks.__super__.add.apply(this, arguments);
1737
            // update nics after each network addition
1738
            ret.each(function(r){
1739
                synnefo.storage.nics.update_net_nics(r);
1740
            });
1741
        },
1742

    
1743
        reset_pending_actions: function() {
1744
            this.each(function(net) {
1745
                net.get("actions").reset();
1746
            });
1747
        },
1748

    
1749
        do_all_pending_actions: function() {
1750
            this.each(function(net) {
1751
                net.do_all_pending_actions();
1752
            })
1753
        },
1754

    
1755
        parse_net_api_data: function(data) {
1756
            // append nic metadata
1757
            // net.get('nics') contains a list of vm/index objects 
1758
            // e.g. {'vm_id':12231, 'index':1}
1759
            // net.get('linked_to') contains a list of vms the network is 
1760
            // connected to e.g. [1001, 1002]
1761
            if (data.attachments && data.attachments) {
1762
                data['nics'] = {};
1763
                data['linked_to'] = [];
1764
                _.each(data.attachments, function(nic_id){
1765
                  
1766
                  var vm_id = NIC_REGEX.exec(nic_id)[1];
1767
                  var nic_index = parseInt(NIC_REGEX.exec(nic_id)[2]);
1768

    
1769
                  if (vm_id !== undefined && nic_index !== undefined) {
1770
                      data['nics'][nic_id] = {
1771
                          'vm_id': vm_id, 
1772
                          'index': nic_index, 
1773
                          'id': nic_id
1774
                      };
1775
                      if (data['linked_to'].indexOf(vm_id) == -1) {
1776
                        data['linked_to'].push(vm_id);
1777
                      }
1778
                  }
1779
                });
1780
            }
1781

    
1782
            if (data.status == "DELETED" && !this.get(parseInt(data.id))) {
1783
              return false;
1784
            }
1785
            return data;
1786
        },
1787

    
1788
        create: function (name, type, cidr, dhcp, callback) {
1789
            var params = {
1790
                network:{
1791
                    name:name
1792
                }
1793
            };
1794

    
1795
            if (!type) {
1796
                throw "Network type cannot be empty";
1797
            }
1798
            params.network.type = type;
1799
            if (cidr) {
1800
                params.network.cidr = cidr;
1801
            }
1802
            if (dhcp) {
1803
                params.network.dhcp = dhcp;
1804
            }
1805

    
1806
            if (dhcp === false) {
1807
                params.network.dhcp = false;
1808
            }
1809
            
1810
            var cb = function() {
1811
              callback();
1812
              synnefo.storage.quotas.get('cyclades.network.private').increase();
1813
            }
1814
            return this.api_call(this.path, "create", params, cb);
1815
        },
1816

    
1817
        get_public: function(){
1818
          return this.filter(function(n){return n.get('public')});
1819
        }
1820
    })
1821

    
1822
    models.Images = models.Collection.extend({
1823
        model: models.Image,
1824
        path: 'images',
1825
        details: true,
1826
        noUpdate: true,
1827
        supportIncUpdates: false,
1828
        meta_keys_as_attrs: ["OS", "description", "kernel", "size", "GUI"],
1829
        meta_labels: {},
1830
        read_method: 'read',
1831

    
1832
        // update collection model with id passed
1833
        // making a direct call to the image
1834
        // api url
1835
        update_unknown_id: function(id, callback) {
1836
            var url = getUrl.call(this) + "/" + id;
1837
            this.api_call(this.path + "/" + id, this.read_method, {
1838
              _options:{
1839
                async:true, 
1840
                skip_api_error:true}
1841
              }, undefined, 
1842
            _.bind(function() {
1843
                if (!this.get(id)) {
1844
                            if (this.fallback_service) {
1845
                        // if current service has fallback_service attribute set
1846
                        // use this service to retrieve the missing image model
1847
                        var tmpservice = new this.fallback_service();
1848
                        tmpservice.update_unknown_id(id, _.bind(function(img){
1849
                            img.attributes.status = "DELETED";
1850
                            this.add(img.attributes);
1851
                            callback(this.get(id));
1852
                        }, this));
1853
                    } else {
1854
                        var title = synnefo.config.image_deleted_title || 'Deleted';
1855
                        // else add a dummy DELETED state image entry
1856
                        this.add({id:id, name:title, size:-1, 
1857
                                  progress:100, status:"DELETED"});
1858
                        callback(this.get(id));
1859
                    }   
1860
                } else {
1861
                    callback(this.get(id));
1862
                }
1863
            }, this), _.bind(function(image, msg, xhr) {
1864
                if (!image) {
1865
                    var title = synnefo.config.image_deleted_title || 'Deleted';
1866
                    this.add({id:id, name:title, size:-1, 
1867
                              progress:100, status:"DELETED"});
1868
                    callback(this.get(id));
1869
                    return;
1870
                }
1871
                var img_data = this._read_image_from_request(image, msg, xhr);
1872
                this.add(img_data);
1873
                callback(this.get(id));
1874
            }, this));
1875
        },
1876

    
1877
        _read_image_from_request: function(image, msg, xhr) {
1878
            return image.image;
1879
        },
1880

    
1881
        parse: function (resp, xhr) {
1882
            var parsed = _.map(resp.images, _.bind(this.parse_meta, this));
1883
            parsed = this.fill_owners(parsed);
1884
            return parsed;
1885
        },
1886

    
1887
        fill_owners: function(images) {
1888
            // do translate uuid->displayname if needed
1889
            // store display name in owner attribute for compatibility
1890
            var uuids = [];
1891

    
1892
            var images = _.map(images, function(img, index) {
1893
                if (synnefo.config.translate_uuids) {
1894
                    uuids.push(img['owner']);
1895
                }
1896
                img['owner_uuid'] = img['owner'];
1897
                return img;
1898
            });
1899
            
1900
            if (uuids.length > 0) {
1901
                var handle_results = function(data) {
1902
                    _.each(images, function (img) {
1903
                        img['owner'] = data.uuid_catalog[img['owner_uuid']];
1904
                    });
1905
                }
1906
                // notice the async false
1907
                var uuid_map = this.translate_uuids(uuids, false, 
1908
                                                    handle_results)
1909
            }
1910
            return images;
1911
        },
1912

    
1913
        translate_uuids: function(uuids, async, cb) {
1914
            var url = synnefo.config.user_catalog_url;
1915
            var data = JSON.stringify({'uuids': uuids});
1916
          
1917
            // post to user_catalogs api
1918
            snf.api.sync('create', undefined, {
1919
                url: url,
1920
                data: data,
1921
                async: async,
1922
                success:  cb
1923
            });
1924
        },
1925

    
1926
        get_meta_key: function(img, key) {
1927
            if (img.metadata && img.metadata && img.metadata[key]) {
1928
                return _.escape(img.metadata[key]);
1929
            }
1930
            return undefined;
1931
        },
1932

    
1933
        comparator: function(img) {
1934
            return -img.get_sort_order("sortorder") || 1000 * img.id;
1935
        },
1936

    
1937
        parse_meta: function(img) {
1938
            _.each(this.meta_keys_as_attrs, _.bind(function(key){
1939
                if (img[key]) { return };
1940
                img[key] = this.get_meta_key(img, key) || "";
1941
            }, this));
1942
            return img;
1943
        },
1944

    
1945
        active: function() {
1946
            return this.filter(function(img){return img.get('status') != "DELETED"});
1947
        },
1948

    
1949
        predefined: function() {
1950
            return _.filter(this.active(), function(i) { return !i.get("serverRef")});
1951
        },
1952
        
1953
        fetch_for_type: function(type, complete, error) {
1954
            this.fetch({update:true, 
1955
                        success: complete, 
1956
                        error: error, 
1957
                        skip_api_error: true });
1958
        },
1959
        
1960
        get_images_for_type: function(type) {
1961
            if (this['get_{0}_images'.format(type)]) {
1962
                return this['get_{0}_images'.format(type)]();
1963
            }
1964

    
1965
            return this.active();
1966
        },
1967

    
1968
        update_images_for_type: function(type, onStart, onComplete, onError, force_load) {
1969
            var load = false;
1970
            error = onError || function() {};
1971
            function complete(collection) { 
1972
                onComplete(collection.get_images_for_type(type)); 
1973
            }
1974
            
1975
            // do we need to fetch/update current collection entries
1976
            if (load) {
1977
                onStart();
1978
                this.fetch_for_type(type, complete, error);
1979
            } else {
1980
                // fallback to complete
1981
                complete(this);
1982
            }
1983
        }
1984
    })
1985

    
1986
    models.Flavors = models.Collection.extend({
1987
        model: models.Flavor,
1988
        path: 'flavors',
1989
        details: true,
1990
        noUpdate: true,
1991
        supportIncUpdates: false,
1992
        // update collection model with id passed
1993
        // making a direct call to the flavor
1994
        // api url
1995
        update_unknown_id: function(id, callback) {
1996
            var url = getUrl.call(this) + "/" + id;
1997
            this.api_call(this.path + "/" + id, "read", {_options:{async:false, skip_api_error:true}}, undefined, 
1998
            _.bind(function() {
1999
                this.add({id:id, cpu:"Unknown", ram:"Unknown", disk:"Unknown", name: "Unknown", status:"DELETED"})
2000
            }, this), _.bind(function(flv) {
2001
                if (!flv.flavor.status) { flv.flavor.status = "DELETED" };
2002
                this.add(flv.flavor);
2003
            }, this));
2004
        },
2005

    
2006
        parse: function (resp, xhr) {
2007
            return _.map(resp.flavors, function(o) {
2008
              o.cpu = o['vcpus'];
2009
              o.disk_template = o['SNF:disk_template'];
2010
              return o
2011
            });
2012
        },
2013

    
2014
        comparator: function(flv) {
2015
            return flv.get("disk") * flv.get("cpu") * flv.get("ram");
2016
        },
2017
          
2018
        unavailable_values_for_quotas: function(quotas, flavors, extra) {
2019
            var flavors = flavors || this.active();
2020
            var index = {cpu:[], disk:[], ram:[]};
2021
            var extra = extra == undefined ? {cpu:0, disk:0, ram:0} : extra;
2022
            
2023
            _.each(flavors, function(el) {
2024

    
2025
                var disk_available = quotas['disk'] + extra.disk;
2026
                var disk_size = el.get_disk_size();
2027
                if (index.disk.indexOf(disk_size) == -1) {
2028
                  var disk = el.disk_to_bytes();
2029
                  if (disk > disk_available) {
2030
                    index.disk.push(disk_size);
2031
                  }
2032
                }
2033
                
2034
                var ram_available = quotas['ram'] + extra.ram * 1024 * 1024;
2035
                var ram_size = el.get_ram_size();
2036
                if (index.ram.indexOf(ram_size) == -1) {
2037
                  var ram = el.ram_to_bytes();
2038
                  if (ram > ram_available) {
2039
                    index.ram.push(el.get('ram'))
2040
                  }
2041
                }
2042

    
2043
                var cpu = el.get('cpu');
2044
                var cpu_available = quotas['cpu'] + extra.cpu;
2045
                if (index.cpu.indexOf(cpu) == -1) {
2046
                  if (cpu > cpu_available) {
2047
                    index.cpu.push(el.get('cpu'))
2048
                  }
2049
                }
2050
            });
2051
            return index;
2052
        },
2053

    
2054
        unavailable_values_for_image: function(img, flavors) {
2055
            var flavors = flavors || this.active();
2056
            var size = img.get_size();
2057
            
2058
            var index = {cpu:[], disk:[], ram:[]};
2059

    
2060
            _.each(this.active(), function(el) {
2061
                var img_size = size;
2062
                var flv_size = el.get_disk_size();
2063
                if (flv_size < img_size) {
2064
                    if (index.disk.indexOf(flv_size) == -1) {
2065
                        index.disk.push(flv_size);
2066
                    }
2067
                };
2068
            });
2069
            
2070
            return index;
2071
        },
2072

    
2073
        get_flavor: function(cpu, mem, disk, disk_template, filter_list) {
2074
            if (!filter_list) { filter_list = this.models };
2075
            
2076
            return this.select(function(flv){
2077
                if (flv.get("cpu") == cpu + "" &&
2078
                   flv.get("ram") == mem + "" &&
2079
                   flv.get("disk") == disk + "" &&
2080
                   flv.get("disk_template") == disk_template &&
2081
                   filter_list.indexOf(flv) > -1) { return true; }
2082
            })[0];
2083
        },
2084
        
2085
        get_data: function(lst) {
2086
            var data = {'cpu': [], 'mem':[], 'disk':[], 'disk_template':[]};
2087

    
2088
            _.each(lst, function(flv) {
2089
                if (data.cpu.indexOf(flv.get("cpu")) == -1) {
2090
                    data.cpu.push(flv.get("cpu"));
2091
                }
2092
                if (data.mem.indexOf(flv.get("ram")) == -1) {
2093
                    data.mem.push(flv.get("ram"));
2094
                }
2095
                if (data.disk.indexOf(flv.get("disk")) == -1) {
2096
                    data.disk.push(flv.get("disk"));
2097
                }
2098
                if (data.disk_template.indexOf(flv.get("disk_template")) == -1) {
2099
                    data.disk_template.push(flv.get("disk_template"));
2100
                }
2101
            })
2102
            
2103
            return data;
2104
        },
2105

    
2106
        active: function() {
2107
            return this.filter(function(flv){return flv.get('status') != "DELETED"});
2108
        }
2109
            
2110
    })
2111

    
2112
    models.VMS = models.Collection.extend({
2113
        model: models.VM,
2114
        path: 'servers',
2115
        details: true,
2116
        copy_image_meta: true,
2117

    
2118
        parse: function (resp, xhr) {
2119
            var data = resp;
2120
            if (!resp) { return [] };
2121
            data = _.filter(_.map(resp.servers, _.bind(this.parse_vm_api_data, this)), function(v){return v});
2122
            return data;
2123
        },
2124

    
2125
        parse_vm_api_data: function(data) {
2126
            // do not add non existing DELETED entries
2127
            if (data.status && data.status == "DELETED") {
2128
                if (!this.get(data.id)) {
2129
                    return false;
2130
                }
2131
            }
2132
            
2133
            if ('SNF:task_state' in data) { 
2134
                data['task_state'] = data['SNF:task_state'];
2135
                if (data['task_state']) {
2136
                    var status = models.VM.TASK_STATE_STATUS_MAP[data['task_state']];
2137
                    if (status) { data['status'] = status }
2138
                }
2139
            }
2140

    
2141
            // OS attribute
2142
            if (this.has_meta(data)) {
2143
                data['OS'] = data.metadata.OS || snf.config.unknown_os;
2144
            }
2145
            
2146
            if (!data.diagnostics) {
2147
                data.diagnostics = [];
2148
            }
2149

    
2150
            // network metadata
2151
            data['firewalls'] = {};
2152
            data['nics'] = {};
2153
            data['linked_to'] = [];
2154

    
2155
            if (data['attachments'] && data['attachments']) {
2156
                var nics = data['attachments'];
2157
                _.each(nics, function(nic) {
2158
                    var net_id = nic.network_id;
2159
                    var index = parseInt(NIC_REGEX.exec(nic.id)[2]);
2160
                    if (data['linked_to'].indexOf(net_id) == -1) {
2161
                        data['linked_to'].push(net_id);
2162
                    }
2163

    
2164
                    data['nics'][nic.id] = nic;
2165
                })
2166
            }
2167
            
2168
            // if vm has no metadata, no metadata object
2169
            // is in json response, reset it to force
2170
            // value update
2171
            if (!data['metadata']) {
2172
                data['metadata'] = {};
2173
            }
2174
            
2175
            // v2.0 API returns objects
2176
            data.image_obj = data.image;
2177
            data.image = data.image_obj.id;
2178
            data.flavor_obj = data.flavor;
2179
            data.flavor = data.flavor_obj.id;
2180

    
2181
            return data;
2182
        },
2183

    
2184
        add: function() {
2185
            ret = models.VMS.__super__.add.apply(this, arguments);
2186
            ret.each(function(r){
2187
                synnefo.storage.nics.update_vm_nics(r);
2188
            });
2189
        },
2190
        
2191
        get_reboot_required: function() {
2192
            return this.filter(function(vm){return vm.get("reboot_required") == true})
2193
        },
2194

    
2195
        has_pending_actions: function() {
2196
            return this.filter(function(vm){return vm.pending_action}).length > 0;
2197
        },
2198

    
2199
        reset_pending_actions: function() {
2200
            this.each(function(vm) {
2201
                vm.clear_pending_action();
2202
            })
2203
        },
2204

    
2205
        do_all_pending_actions: function(success, error) {
2206
            this.each(function(vm) {
2207
                if (vm.has_pending_action()) {
2208
                    vm.call(vm.pending_action, success, error);
2209
                    vm.clear_pending_action();
2210
                }
2211
            })
2212
        },
2213
        
2214
        do_all_reboots: function(success, error) {
2215
            this.each(function(vm) {
2216
                if (vm.get("reboot_required")) {
2217
                    vm.call("reboot", success, error);
2218
                }
2219
            });
2220
        },
2221

    
2222
        reset_reboot_required: function() {
2223
            this.each(function(vm) {
2224
                vm.set({'reboot_required': undefined});
2225
            })
2226
        },
2227
        
2228
        stop_stats_update: function(exclude) {
2229
            var exclude = exclude || [];
2230
            this.each(function(vm) {
2231
                if (exclude.indexOf(vm) > -1) {
2232
                    return;
2233
                }
2234
                vm.stop_stats_update();
2235
            })
2236
        },
2237
        
2238
        has_meta: function(vm_data) {
2239
            return vm_data.metadata && vm_data.metadata
2240
        },
2241

    
2242
        has_addresses: function(vm_data) {
2243
            return vm_data.metadata && vm_data.metadata
2244
        },
2245

    
2246
        create: function (name, image, flavor, meta, extra, callback) {
2247

    
2248
            if (this.copy_image_meta) {
2249
                if (synnefo.config.vm_image_common_metadata) {
2250
                    _.each(synnefo.config.vm_image_common_metadata, 
2251
                        function(key){
2252
                            if (image.get_meta(key)) {
2253
                                meta[key] = image.get_meta(key);
2254
                            }
2255
                    });
2256
                }
2257

    
2258
                if (image.get("OS")) {
2259
                    meta['OS'] = image.get("OS");
2260
                }
2261
            }
2262
            
2263
            opts = {name: name, imageRef: image.id, flavorRef: flavor.id, 
2264
                    metadata:meta}
2265
            opts = _.extend(opts, extra);
2266
            
2267
            var cb = function(data) {
2268
              synnefo.storage.quotas.get('cyclades.vm').increase();
2269
              callback(data);
2270
            }
2271

    
2272
            this.api_call(this.path, "create", {'server': opts}, undefined, 
2273
                          undefined, cb, {critical: true});
2274
        },
2275

    
2276
        load_missing_images: function(callback) {
2277
          var missing_ids = [];
2278
          var resolved = 0;
2279

    
2280
          // fill missing_ids
2281
          this.each(function(el) {
2282
            var imgid = el.get("image");
2283
            var existing = synnefo.storage.images.get(imgid);
2284
            if (!existing && missing_ids.indexOf(imgid) == -1) {
2285
              missing_ids.push(imgid);
2286
            }
2287
          });
2288
          var check = function() {
2289
            // once all missing ids where resolved continue calling the 
2290
            // callback
2291
            resolved++;
2292
            if (resolved == missing_ids.length) {
2293
              callback(missing_ids)
2294
            }
2295
          }
2296
          if (missing_ids.length == 0) {
2297
            callback(missing_ids);
2298
            return;
2299
          }
2300
          // start resolving missing image ids
2301
          _(missing_ids).each(function(imgid){
2302
            synnefo.storage.images.update_unknown_id(imgid, check);
2303
          });
2304
        },
2305

    
2306
        get_connectable: function() {
2307
            return storage.vms.filter(function(vm){
2308
                return !vm.in_error_state() && !vm.is_building();
2309
            });
2310
        }
2311
    })
2312
    
2313
    models.NIC = models.Model.extend({
2314
        
2315
        initialize: function() {
2316
            models.NIC.__super__.initialize.apply(this, arguments);
2317
            this.pending_for_firewall = false;
2318
            this.bind("change:firewallProfile", _.bind(this.check_firewall, this));
2319
            this.bind("change:pending_firewall", function(nic) {
2320
                nic.get_network().update_state();
2321
            });
2322
            this.get_vm().bind("remove", function(){
2323
                try {
2324
                    this.collection.remove(this);
2325
                } catch (err) {};
2326
            }, this);
2327
            this.get_network().bind("remove", function(){
2328
                try {
2329
                    this.collection.remove(this);
2330
                } catch (err) {};
2331
            }, this);
2332

    
2333
        },
2334

    
2335
        get_vm: function() {
2336
            return synnefo.storage.vms.get(parseInt(this.get('vm_id')));
2337
        },
2338

    
2339
        get_network: function() {
2340
            return synnefo.storage.networks.get(this.get('network_id'));
2341
        },
2342

    
2343
        get_v6_address: function() {
2344
            return this.get("ipv6");
2345
        },
2346

    
2347
        get_v4_address: function() {
2348
            return this.get("ipv4");
2349
        },
2350

    
2351
        set_firewall: function(value, callback, error, options) {
2352
            var net_id = this.get('network_id');
2353
            var self = this;
2354

    
2355
            // api call data
2356
            var payload = {"firewallProfile":{"profile":value}};
2357
            payload._options = _.extend({critical: false}, options);
2358
            
2359
            this.set({'pending_firewall': value});
2360
            this.set({'pending_firewall_sending': true});
2361
            this.set({'pending_firewall_from': this.get('firewallProfile')});
2362

    
2363
            var success_cb = function() {
2364
                if (callback) {
2365
                    callback();
2366
                }
2367
                self.set({'pending_firewall_sending': false});
2368
            };
2369

    
2370
            var error_cb = function() {
2371
                self.reset_pending_firewall();
2372
            }
2373
            
2374
            this.get_vm().api_call(this.get_vm().api_path() + "/action", "create", payload, success_cb, error_cb);
2375
        },
2376

    
2377
        reset_pending_firewall: function() {
2378
            this.set({'pending_firewall': false});
2379
            this.set({'pending_firewall': false});
2380
        },
2381

    
2382
        check_firewall: function() {
2383
            var firewall = this.get('firewallProfile');
2384
            var pending = this.get('pending_firewall');
2385
            var previous = this.get('pending_firewall_from');
2386
            if (previous != firewall) { this.get_vm().require_reboot() };
2387
            this.reset_pending_firewall();
2388
        }
2389
        
2390
    });
2391

    
2392
    models.NICs = models.Collection.extend({
2393
        model: models.NIC,
2394
        
2395
        add_or_update: function(nic_id, data, vm) {
2396
            var params = _.clone(data);
2397
            var vm;
2398
            params.attachment_id = params.id;
2399
            params.id = params.id + '-' + params.network_id;
2400
            params.vm_id = parseInt(NIC_REGEX.exec(nic_id)[1]);
2401

    
2402
            if (!this.get(params.id)) {
2403
                this.add(params);
2404
                var nic = this.get(params.id);
2405
                vm = nic.get_vm();
2406
                nic.get_network().decrease_connecting();
2407
                nic.bind("remove", function() {
2408
                    nic.set({"removing": 0});
2409
                    if (this.get_network()) {
2410
                        // network might got removed before nic
2411
                        nic.get_network().update_state();
2412
                    }
2413
                });
2414

    
2415
            } else {
2416
                this.get(params.id).set(params);
2417
                vm = this.get(params.id).get_vm();
2418
            }
2419
            
2420
            // vm nics changed, trigger vm update
2421
            if (vm) { vm.trigger("change", vm)};
2422
        },
2423
        
2424
        reset_nics: function(nics, filter_attr, filter_val) {
2425
            var nics_to_check = this.filter(function(nic) {
2426
                return nic.get(filter_attr) == filter_val;
2427
            });
2428
            
2429
            _.each(nics_to_check, function(nic) {
2430
                if (nics.indexOf(nic.get('id')) == -1) {
2431
                    this.remove(nic);
2432
                } else {
2433
                }
2434
            }, this);
2435
        },
2436

    
2437
        update_vm_nics: function(vm) {
2438
            var nics = vm.get('nics');
2439
            this.reset_nics(_.map(nics, function(nic, key){
2440
                return key + "-" + nic.network_id;
2441
            }), 'vm_id', vm.id);
2442

    
2443
            _.each(nics, function(val, key) {
2444
                var net = synnefo.storage.networks.get(val.network_id);
2445
                if (net && net.connected_with_nic_id(key) && vm.connected_with_nic_id(key)) {
2446
                    this.add_or_update(key, vm.get('nics')[key], vm);
2447
                }
2448
            }, this);
2449
        },
2450

    
2451
        update_net_nics: function(net) {
2452
            var nics = net.get('nics');
2453
            this.reset_nics(_.map(nics, function(nic, key){
2454
                return key + "-" + net.get('id');
2455
            }), 'network_id', net.id);
2456

    
2457
            _.each(nics, function(val, key) {
2458
                var vm = synnefo.storage.vms.get(val.vm_id);
2459
                if (vm && net.connected_with_nic_id(key) && vm.connected_with_nic_id(key)) {
2460
                    this.add_or_update(key, vm.get('nics')[key], vm);
2461
                }
2462
            }, this);
2463
        }
2464
    });
2465

    
2466
    models.PublicKey = models.Model.extend({
2467
        path: 'keys',
2468
        api_type: 'userdata',
2469
        details: false,
2470
        noUpdate: true,
2471

    
2472

    
2473
        get_public_key: function() {
2474
            return cryptico.publicKeyFromString(this.get("content"));
2475
        },
2476

    
2477
        get_filename: function() {
2478
            return "{0}.pub".format(this.get("name"));
2479
        },
2480

    
2481
        identify_type: function() {
2482
            try {
2483
                var cont = snf.util.validatePublicKey(this.get("content"));
2484
                var type = cont.split(" ")[0];
2485
                return synnefo.util.publicKeyTypesMap[type];
2486
            } catch (err) { return false };
2487
        }
2488

    
2489
    })
2490
    
2491
    models.PublicPool = models.Model.extend({});
2492
    models.PublicPools = models.Collection.extend({
2493
      model: models.PublicPool,
2494
      path: 'os-floating-ip-pools',
2495
      api_type: 'compute',
2496
      noUpdate: true,
2497

    
2498
      parse: function(data) {
2499
        return _.map(data.floating_ip_pools, function(pool) {
2500
          pool.id = pool.name;
2501
          return pool;
2502
        });
2503
      }
2504
    });
2505

    
2506
    models.PublicIP = models.Model.extend({
2507
        path: 'os-floating-ips',
2508
        has_status: false,
2509
        
2510
        initialize: function() {
2511
            models.PublicIP.__super__.initialize.apply(this, arguments);
2512
            this.bind('change:instance_id', _.bind(this.handle_status_change, this));
2513
        },
2514

    
2515
        handle_status_change: function() {
2516
            this.set({state: null});
2517
        },
2518

    
2519
        get_vm: function() {
2520
            if (this.get('instance_id')) {
2521
                return synnefo.storage.vms.get(parseInt(this.get('instance_id')));
2522
            }
2523
            return null;
2524
        },
2525

    
2526
        connect_to: function(vm) {
2527
        }
2528
    });
2529

    
2530
    models.PublicIPs = models.Collection.extend({
2531
        model: models.PublicIP,
2532
        path: 'os-floating-ips',
2533
        api_type: 'compute',
2534
        noUpdate: true,
2535

    
2536
        parse: function(resp) {
2537
            resp = _.map(resp.floating_ips, function(ip) {
2538
              return ip;
2539
            });
2540

    
2541
            return resp;
2542
        }
2543
    });
2544

    
2545
    models.PublicKeys = models.Collection.extend({
2546
        model: models.PublicKey,
2547
        details: false,
2548
        path: 'keys',
2549
        api_type: 'userdata',
2550
        noUpdate: true,
2551

    
2552
        generate_new: function(success, error) {
2553
            snf.api.sync('create', undefined, {
2554
                url: getUrl.call(this, this.base_url) + "/generate", 
2555
                success: success, 
2556
                error: error,
2557
                skip_api_error: true
2558
            });
2559
        },
2560

    
2561
        add_crypto_key: function(key, success, error, options) {
2562
            var options = options || {};
2563
            var m = new models.PublicKey();
2564

    
2565
            // guess a name
2566
            var name_tpl = "my generated public key";
2567
            var name = name_tpl;
2568
            var name_count = 1;
2569
            
2570
            while(this.filter(function(m){ return m.get("name") == name }).length > 0) {
2571
                name = name_tpl + " " + name_count;
2572
                name_count++;
2573
            }
2574
            
2575
            m.set({name: name});
2576
            m.set({content: key});
2577
            
2578
            options.success = function () { return success(m) };
2579
            options.errror = error;
2580
            options.skip_api_error = true;
2581
            
2582
            this.create(m.attributes, options);
2583
        }
2584
    });
2585

    
2586
  
2587
    models.Quota = models.Model.extend({
2588

    
2589
        initialize: function() {
2590
            models.Quota.__super__.initialize.apply(this, arguments);
2591
            this.bind("change", this.check, this);
2592
            this.check();
2593
        },
2594
        
2595
        check: function() {
2596
            var usage, limit;
2597
            usage = this.get('usage');
2598
            limit = this.get('limit');
2599
            if (usage >= limit) {
2600
                this.trigger("available");
2601
            } else {
2602
                this.trigger("unavailable");
2603
            }
2604
        },
2605

    
2606
        increase: function(val) {
2607
            if (val === undefined) { val = 1};
2608
            this.set({'usage': this.get('usage') + val})
2609
        },
2610

    
2611
        decrease: function(val) {
2612
            if (val === undefined) { val = 1};
2613
            this.set({'usage': this.get('usage') - val})
2614
        },
2615

    
2616
        can_consume: function() {
2617
            var usage, limit;
2618
            usage = this.get('usage');
2619
            limit = this.get('limit');
2620
            if (usage >= limit) {
2621
                return false
2622
            } else {
2623
                return true
2624
            }
2625
        },
2626
        
2627
        is_bytes: function() {
2628
            return this.get('resource').get('unit') == 'bytes';
2629
        },
2630
        
2631
        get_available: function(active) {
2632
            suffix = '';
2633
            if (active) { suffix = '_active'}
2634
            var value = this.get('limit'+suffix) - this.get('usage'+suffix);
2635
            if (active) {
2636
              if (this.get('available') <= value) {
2637
                value = this.get('available');
2638
              }
2639
            }
2640
            if (value < 0) { return value }
2641
            return value
2642
        },
2643

    
2644
        get_readable: function(key, active) {
2645
            var value;
2646
            if (key == 'available') {
2647
                value = this.get_available(active);
2648
            } else {
2649
                value = this.get(key)
2650
            }
2651
            if (value <= 0) { value = 0 }
2652
            if (!this.is_bytes()) {
2653
              return value + "";
2654
            }
2655
            return snf.util.readablizeBytes(value);
2656
        }
2657
    });
2658

    
2659
    models.Quotas = models.Collection.extend({
2660
        model: models.Quota,
2661
        api_type: 'accounts',
2662
        path: 'quotas',
2663
        parse: function(resp) {
2664
            filtered = _.map(resp.system, function(value, key) {
2665
                var available = (value.limit - value.usage) || 0;
2666
                var available_active = available;
2667
                var keysplit = key.split(".");
2668
                var limit_active = value.limit;
2669
                var usage_active = value.usage;
2670
                keysplit[keysplit.length-1] = "active_" + keysplit[keysplit.length-1];
2671
                var activekey = keysplit.join(".");
2672
                var exists = resp.system[activekey];
2673
                if (exists) {
2674
                    available_active = exists.limit - exists.usage;
2675
                    limit_active = exists.limit;
2676
                    usage_active = exists.usage;
2677
                }
2678
                return _.extend(value, {'name': key, 'id': key, 
2679
                          'available': available,
2680
                          'available_active': available_active,
2681
                          'limit_active': limit_active,
2682
                          'usage_active': usage_active,
2683
                          'resource': snf.storage.resources.get(key)});
2684
            });
2685
            return filtered;
2686
        },
2687
        
2688
        get_by_id: function(k) {
2689
          return this.filter(function(q) { return q.get('name') == k})[0]
2690
        },
2691

    
2692
        get_available_for_vm: function(options) {
2693
          var quotas = synnefo.storage.quotas;
2694
          var key = 'available';
2695
          var available_quota = {};
2696
          _.each(['cyclades.ram', 'cyclades.cpu', 'cyclades.disk'], 
2697
            function (key) {
2698
              var value = quotas.get(key).get_available(true);
2699
              available_quota[key.replace('cyclades.', '')] = value;
2700
          });
2701
          return available_quota;
2702
        }
2703
    })
2704

    
2705
    models.Resource = models.Model.extend({
2706
        api_type: 'accounts',
2707
        path: 'resources'
2708
    });
2709

    
2710
    models.Resources = models.Collection.extend({
2711
        api_type: 'accounts',
2712
        path: 'resources',
2713
        model: models.Network,
2714

    
2715
        parse: function(resp) {
2716
            return _.map(resp, function(value, key) {
2717
                return _.extend(value, {'name': key, 'id': key});
2718
            })
2719
        }
2720
    });
2721
    
2722
    // storage initialization
2723
    snf.storage.images = new models.Images();
2724
    snf.storage.flavors = new models.Flavors();
2725
    snf.storage.networks = new models.Networks();
2726
    snf.storage.vms = new models.VMS();
2727
    snf.storage.keys = new models.PublicKeys();
2728
    snf.storage.nics = new models.NICs();
2729
    snf.storage.resources = new models.Resources();
2730
    snf.storage.quotas = new models.Quotas();
2731
    snf.storage.public_ips = new models.PublicIPs();
2732
    snf.storage.public_pools = new models.PublicPools();
2733

    
2734
})(this);