Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (88.9 kB)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
510
    });
511

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
970

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

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

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

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

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

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

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

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

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

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

    
1047
        can_resize: function() {
1048
          return this.get('status') == 'STOPPED';
1049
        },
1050

    
1051
        handle_stats_error: function() {
1052
            stats = {};
1053
            _.each(['cpuBar', 'cpuTimeSeries', 'netBar', 'netTimeSeries'], function(k) {
1054
                stats[k] = false;
1055
            });
1056

    
1057
            this.set({'stats': stats});
1058
        },
1059

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

    
1071
                function check_images_loaded() {
1072
                    images_loaded++;
1073

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

    
1094
                    img.error(function() {
1095
                        images[stat + type] = false;
1096
                        check_images_loaded();
1097
                    });
1098

    
1099
                    img.attr({'src': stats[k]});
1100
                })
1101
                data.stats = stats;
1102
            }
1103

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

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

    
1125
        require_reboot: function() {
1126
            if (this.is_active()) {
1127
                this.set({'reboot_required': true});
1128
            }
1129
        },
1130
        
1131
        set_pending_action: function(data) {
1132
            this.pending_action = data;
1133
            return data;
1134
        },
1135

    
1136
        // machine has pending action
1137
        update_pending_action: function(action, force) {
1138
            this.set({pending_action: action});
1139
        },
1140

    
1141
        clear_pending_action: function() {
1142
            this.set({pending_action: undefined});
1143
        },
1144

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

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

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

    
1188
            this.api_call(url, "update", payload, complete, error);
1189
        },
1190

    
1191

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

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

    
1256
        get_resize_flavors: function() {
1257
          var vm_flavor = this.get_flavor();
1258
          var flavors = synnefo.storage.flavors.filter(function(f){
1259
              return f.get('disk_template') ==
1260
              vm_flavor.get('disk_template') && f.get('disk') ==
1261
              vm_flavor.get('disk');
1262
          });
1263
          return flavors;
1264
        },
1265

    
1266
        get_flavor_quotas: function() {
1267
          var flavor = this.get_flavor();
1268
          return {
1269
            cpu: flavor.get('cpu') + 1, 
1270
            ram: flavor.get_ram_size() + 1, 
1271
            disk:flavor.get_disk_size() + 1
1272
          }
1273
        },
1274

    
1275
        get_meta: function(key, deflt) {
1276
            if (this.get('metadata') && this.get('metadata')) {
1277
                if (!this.get('metadata')[key]) { return deflt }
1278
                return _.escape(this.get('metadata')[key]);
1279
            } else {
1280
                return deflt;
1281
            }
1282
        },
1283

    
1284
        get_meta_keys: function() {
1285
            if (this.get('metadata') && this.get('metadata')) {
1286
                return _.keys(this.get('metadata'));
1287
            } else {
1288
                return [];
1289
            }
1290
        },
1291
        
1292
        // get metadata OS value
1293
        get_os: function() {
1294
            var image = this.get_image();
1295
            return this.get_meta('OS') || (image ? 
1296
                                            image.get_os() || "okeanos" : "okeanos");
1297
        },
1298

    
1299
        get_gui: function() {
1300
            return this.get_meta('GUI');
1301
        },
1302
        
1303
        connected_to: function(net) {
1304
            return this.get('linked_to').indexOf(net.id) > -1;
1305
        },
1306

    
1307
        connected_with_nic_id: function(nic_id) {
1308
            return _.keys(this.get('nics')).indexOf(nic_id) > -1;
1309
        },
1310

    
1311
        get_nics: function(filter) {
1312
            ret = synnefo.storage.nics.filter(function(nic) {
1313
                return parseInt(nic.get('vm_id')) == this.id;
1314
            }, this);
1315

    
1316
            if (filter) {
1317
                return _.filter(ret, filter);
1318
            }
1319

    
1320
            return ret;
1321
        },
1322

    
1323
        get_net_nics: function(net_id) {
1324
            return this.get_nics(function(n){return n.get('network_id') == net_id});
1325
        },
1326

    
1327
        get_public_nic: function() {
1328
            return this.get_nics(function(n){ return n.get_network().is_public() === true })[0];
1329
        },
1330

    
1331
        get_hostname: function() {
1332
          var hostname = this.get_meta('hostname');
1333
          if (!hostname) {
1334
            if (synnefo.config.vm_hostname_format) {
1335
              hostname = synnefo.config.vm_hostname_format.format(this.id);
1336
            } else {
1337
              hostname = this.get_public_nic().get('ipv4');
1338
            }
1339
          }
1340
          return hostname;
1341
        },
1342

    
1343
        get_nic: function(net_id) {
1344
        },
1345

    
1346
        has_firewall: function() {
1347
            var nic = this.get_public_nic();
1348
            if (nic) {
1349
                var profile = nic.get('firewallProfile'); 
1350
                return ['ENABLED', 'PROTECTED'].indexOf(profile) > -1;
1351
            }
1352
            return false;
1353
        },
1354

    
1355
        get_firewall_profile: function() {
1356
            var nic = this.get_public_nic();
1357
            if (nic) {
1358
                return nic.get('firewallProfile');
1359
            }
1360
            return null;
1361
        },
1362

    
1363
        get_addresses: function() {
1364
            var pnic = this.get_public_nic();
1365
            if (!pnic) { return {'ip4': undefined, 'ip6': undefined }};
1366
            return {'ip4': pnic.get('ipv4'), 'ip6': pnic.get('ipv6')};
1367
        },
1368
    
1369
        // get actions that the user can execute
1370
        // depending on the vm state/status
1371
        get_available_actions: function() {
1372
            return models.VM.AVAILABLE_ACTIONS[this.state()];
1373
        },
1374

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

    
1408
        // action helper
1409
        call: function(action_name, success, error, params) {
1410
            var id_param = [this.id];
1411
            
1412
            params = params || {};
1413
            success = success || function() {};
1414
            error = error || function() {};
1415

    
1416
            var self = this;
1417

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

    
1472
                                         },  
1473
                                         error, 'destroy', params);
1474
                    break;
1475
                case 'resize':
1476
                    this.__make_api_call(this.get_action_url(), // vm actions url
1477
                                         "create", // create so that sync later uses POST to make the call
1478
                                         {resize: {flavorRef:params.flavor}}, // payload
1479
                                         function() {
1480
                                             success.apply(this, arguments)
1481
                                             snf.api.trigger("call");
1482
                                         },  
1483
                                         error, 'resize', params);
1484
                    break;
1485
                case 'destroy':
1486
                    this.__make_api_call(this.url(), // vm actions url
1487
                                         "delete", // create so that sync later uses POST to make the call
1488
                                         undefined, // payload
1489
                                         function() {
1490
                                             // set state after successful call
1491
                                             self.state('DESTROY');
1492
                                             success.apply(this, arguments);
1493
                                             synnefo.storage.quotas.get('cyclades.vm').decrease();
1494

    
1495
                                         },  
1496
                                         error, 'destroy', params);
1497
                    break;
1498
                default:
1499
                    throw "Invalid VM action ("+action_name+")";
1500
            }
1501
        },
1502
        
1503
        __make_api_call: function(url, method, data, success, error, action, extra_params) {
1504
            var self = this;
1505
            error = error || function(){};
1506
            success = success || function(){};
1507

    
1508
            var params = {
1509
                url: url,
1510
                data: data,
1511
                success: function(){ self.handle_action_succeed.apply(self, arguments); success.apply(this, arguments)},
1512
                error: function(){ self.handle_action_fail.apply(self, arguments); error.apply(this, arguments)},
1513
                error_params: { ns: "Machines actions", 
1514
                                title: "'" + this.get("name") + "'" + " " + action + " failed", 
1515
                                extra_details: { 'Machine ID': this.id, 'URL': url, 'Action': action || "undefined" },
1516
                                allow_reload: false
1517
                              },
1518
                display: false,
1519
                critical: false
1520
            }
1521
            _.extend(params, extra_params)
1522
            this.sync(method, this, params);
1523
        },
1524

    
1525
        handle_action_succeed: function() {
1526
            this.trigger("action:success", arguments);
1527
        },
1528
        
1529
        reset_action_error: function() {
1530
            this.action_error = false;
1531
            this.trigger("action:fail:reset", this.action_error);
1532
        },
1533

    
1534
        handle_action_fail: function() {
1535
            this.action_error = arguments;
1536
            this.trigger("action:fail", arguments);
1537
        },
1538

    
1539
        get_action_url: function(name) {
1540
            return this.url() + "/action";
1541
        },
1542

    
1543
        get_diagnostics_url: function() {
1544
            return this.url() + "/diagnostics";
1545
        },
1546

    
1547
        get_connection_info: function(host_os, success, error) {
1548
            var url = synnefo.config.ui_connect_url;
1549
            params = {
1550
                ip_address: this.get_public_nic().get('ipv4'),
1551
                hostname: this.get_hostname(),
1552
                os: this.get_os(),
1553
                host_os: host_os,
1554
                srv: this.id
1555
            }
1556

    
1557
            url = url + "?" + $.param(params);
1558

    
1559
            var ajax = snf.api.sync("read", undefined, { url: url, 
1560
                                                         error:error, 
1561
                                                         success:success, 
1562
                                                         handles_error:1});
1563
        }
1564
    })
1565
    
1566
    models.VM.ACTIONS = [
1567
        'start',
1568
        'shutdown',
1569
        'reboot',
1570
        'console',
1571
        'destroy'
1572
    ]
1573

    
1574
    models.VM.AVAILABLE_ACTIONS = {
1575
        'UNKNWON'       : ['destroy'],
1576
        'BUILD'         : ['destroy'],
1577
        'REBOOT'        : ['shutdown', 'destroy', 'console'],
1578
        'STOPPED'       : ['start', 'destroy'],
1579
        'ACTIVE'        : ['shutdown', 'destroy', 'reboot', 'console'],
1580
        'ERROR'         : ['destroy'],
1581
        'DELETED'        : [],
1582
        'DESTROY'       : [],
1583
        'BUILD_INIT'    : ['destroy'],
1584
        'BUILD_COPY'    : ['destroy'],
1585
        'BUILD_FINAL'   : ['destroy'],
1586
        'SHUTDOWN'      : ['destroy'],
1587
        'START'         : [],
1588
        'CONNECT'       : [],
1589
        'DISCONNECT'    : []
1590
    }
1591

    
1592
    // api status values
1593
    models.VM.STATUSES = [
1594
        'UNKNWON',
1595
        'BUILD',
1596
        'REBOOT',
1597
        'STOPPED',
1598
        'ACTIVE',
1599
        'ERROR',
1600
        'DELETED'
1601
    ]
1602

    
1603
    // api status values
1604
    models.VM.CONNECT_STATES = [
1605
        'ACTIVE',
1606
        'REBOOT',
1607
        'SHUTDOWN'
1608
    ]
1609

    
1610
    // vm states
1611
    models.VM.STATES = models.VM.STATUSES.concat([
1612
        'DESTROY',
1613
        'BUILD_INIT',
1614
        'BUILD_COPY',
1615
        'BUILD_FINAL',
1616
        'SHUTDOWN',
1617
        'START',
1618
        'CONNECT',
1619
        'DISCONNECT',
1620
        'FIREWALL'
1621
    ]);
1622
    
1623
    models.VM.STATES_TRANSITIONS = {
1624
        'DESTROY' : ['DELETED'],
1625
        'SHUTDOWN': ['ERROR', 'STOPPED', 'DESTROY'],
1626
        'STOPPED': ['ERROR', 'ACTIVE', 'DESTROY'],
1627
        'ACTIVE': ['ERROR', 'STOPPED', 'REBOOT', 'SHUTDOWN', 'DESTROY'],
1628
        'START': ['ERROR', 'ACTIVE', 'DESTROY'],
1629
        'REBOOT': ['ERROR', 'ACTIVE', 'STOPPED', 'DESTROY'],
1630
        'BUILD': ['ERROR', 'ACTIVE', 'DESTROY'],
1631
        'BUILD_COPY': ['ERROR', 'ACTIVE', 'BUILD_FINAL', 'DESTROY'],
1632
        'BUILD_FINAL': ['ERROR', 'ACTIVE', 'DESTROY'],
1633
        'BUILD_INIT': ['ERROR', 'ACTIVE', 'BUILD_COPY', 'BUILD_FINAL', 'DESTROY']
1634
    }
1635

    
1636
    models.VM.TRANSITION_STATES = [
1637
        'DESTROY',
1638
        'SHUTDOWN',
1639
        'START',
1640
        'REBOOT',
1641
        'BUILD'
1642
    ]
1643

    
1644
    models.VM.ACTIVE_STATES = [
1645
        'BUILD', 'REBOOT', 'ACTIVE',
1646
        'BUILD_INIT', 'BUILD_COPY', 'BUILD_FINAL',
1647
        'SHUTDOWN', 'CONNECT', 'DISCONNECT'
1648
    ]
1649

    
1650
    models.VM.BUILDING_STATES = [
1651
        'BUILD', 'BUILD_INIT', 'BUILD_COPY', 'BUILD_FINAL'
1652
    ]
1653

    
1654
    models.Networks = models.Collection.extend({
1655
        model: models.Network,
1656
        path: 'networks',
1657
        details: true,
1658
        //noUpdate: true,
1659
        defaults: {'nics':[],'linked_to':[]},
1660
        
1661
        parse: function (resp, xhr) {
1662
            // FIXME: depricated global var
1663
            if (!resp) { return []};
1664
            var data = _.filter(_.map(resp.networks, _.bind(this.parse_net_api_data, this)),
1665
                               function(e){ return e });
1666
            return data;
1667
        },
1668

    
1669
        add: function() {
1670
            ret = models.Networks.__super__.add.apply(this, arguments);
1671
            // update nics after each network addition
1672
            ret.each(function(r){
1673
                synnefo.storage.nics.update_net_nics(r);
1674
            });
1675
        },
1676

    
1677
        reset_pending_actions: function() {
1678
            this.each(function(net) {
1679
                net.get("actions").reset();
1680
            });
1681
        },
1682

    
1683
        do_all_pending_actions: function() {
1684
            this.each(function(net) {
1685
                net.do_all_pending_actions();
1686
            })
1687
        },
1688

    
1689
        parse_net_api_data: function(data) {
1690
            // append nic metadata
1691
            // net.get('nics') contains a list of vm/index objects 
1692
            // e.g. {'vm_id':12231, 'index':1}
1693
            // net.get('linked_to') contains a list of vms the network is 
1694
            // connected to e.g. [1001, 1002]
1695
            if (data.attachments && data.attachments) {
1696
                data['nics'] = {};
1697
                data['linked_to'] = [];
1698
                _.each(data.attachments, function(nic_id){
1699
                  
1700
                  var vm_id = NIC_REGEX.exec(nic_id)[1];
1701
                  var nic_index = parseInt(NIC_REGEX.exec(nic_id)[2]);
1702

    
1703
                  if (vm_id !== undefined && nic_index !== undefined) {
1704
                      data['nics'][nic_id] = {
1705
                          'vm_id': vm_id, 
1706
                          'index': nic_index, 
1707
                          'id': nic_id
1708
                      };
1709
                      if (data['linked_to'].indexOf(vm_id) == -1) {
1710
                        data['linked_to'].push(vm_id);
1711
                      }
1712
                  }
1713
                });
1714
            }
1715

    
1716
            if (data.status == "DELETED" && !this.get(parseInt(data.id))) {
1717
              return false;
1718
            }
1719
            return data;
1720
        },
1721

    
1722
        create: function (name, type, cidr, dhcp, callback) {
1723
            var params = {
1724
                network:{
1725
                    name:name
1726
                }
1727
            };
1728

    
1729
            if (!type) {
1730
                throw "Network type cannot be empty";
1731
            }
1732
            params.network.type = type;
1733
            if (cidr) {
1734
                params.network.cidr = cidr;
1735
            }
1736
            if (dhcp) {
1737
                params.network.dhcp = dhcp;
1738
            }
1739

    
1740
            if (dhcp === false) {
1741
                params.network.dhcp = false;
1742
            }
1743
            
1744
            var cb = function() {
1745
              callback();
1746
              synnefo.storage.quotas.get('cyclades.network.private').increase();
1747
            }
1748
            return this.api_call(this.path, "create", params, cb);
1749
        },
1750

    
1751
        get_public: function(){
1752
          return this.filter(function(n){return n.get('public')});
1753
        }
1754
    })
1755

    
1756
    models.Images = models.Collection.extend({
1757
        model: models.Image,
1758
        path: 'images',
1759
        details: true,
1760
        noUpdate: true,
1761
        supportIncUpdates: false,
1762
        meta_keys_as_attrs: ["OS", "description", "kernel", "size", "GUI"],
1763
        meta_labels: {},
1764
        read_method: 'read',
1765

    
1766
        // update collection model with id passed
1767
        // making a direct call to the image
1768
        // api url
1769
        update_unknown_id: function(id, callback) {
1770
            var url = getUrl.call(this) + "/" + id;
1771
            this.api_call(this.path + "/" + id, this.read_method, {
1772
              _options:{
1773
                async:true, 
1774
                skip_api_error:true}
1775
              }, undefined, 
1776
            _.bind(function() {
1777
                if (!this.get(id)) {
1778
                            if (this.fallback_service) {
1779
                        // if current service has fallback_service attribute set
1780
                        // use this service to retrieve the missing image model
1781
                        var tmpservice = new this.fallback_service();
1782
                        tmpservice.update_unknown_id(id, _.bind(function(img){
1783
                            img.attributes.status = "DELETED";
1784
                            this.add(img.attributes);
1785
                            callback(this.get(id));
1786
                        }, this));
1787
                    } else {
1788
                        var title = synnefo.config.image_deleted_title || 'Deleted';
1789
                        // else add a dummy DELETED state image entry
1790
                        this.add({id:id, name:title, size:-1, 
1791
                                  progress:100, status:"DELETED"});
1792
                        callback(this.get(id));
1793
                    }   
1794
                } else {
1795
                    callback(this.get(id));
1796
                }
1797
            }, this), _.bind(function(image, msg, xhr) {
1798
                if (!image) {
1799
                    var title = synnefo.config.image_deleted_title || 'Deleted';
1800
                    this.add({id:id, name:title, size:-1, 
1801
                              progress:100, status:"DELETED"});
1802
                    callback(this.get(id));
1803
                    return;
1804
                }
1805
                var img_data = this._read_image_from_request(image, msg, xhr);
1806
                this.add(img_data);
1807
                callback(this.get(id));
1808
            }, this));
1809
        },
1810

    
1811
        _read_image_from_request: function(image, msg, xhr) {
1812
            return image.image;
1813
        },
1814

    
1815
        parse: function (resp, xhr) {
1816
            var parsed = _.map(resp.images, _.bind(this.parse_meta, this));
1817
            parsed = this.fill_owners(parsed);
1818
            return parsed;
1819
        },
1820

    
1821
        fill_owners: function(images) {
1822
            // do translate uuid->displayname if needed
1823
            // store display name in owner attribute for compatibility
1824
            var uuids = [];
1825

    
1826
            var images = _.map(images, function(img, index) {
1827
                if (synnefo.config.translate_uuids) {
1828
                    uuids.push(img['owner']);
1829
                }
1830
                img['owner_uuid'] = img['owner'];
1831
                return img;
1832
            });
1833
            
1834
            if (uuids.length > 0) {
1835
                var handle_results = function(data) {
1836
                    _.each(images, function (img) {
1837
                        img['owner'] = data.uuid_catalog[img['owner_uuid']];
1838
                    });
1839
                }
1840
                // notice the async false
1841
                var uuid_map = this.translate_uuids(uuids, false, 
1842
                                                    handle_results)
1843
            }
1844
            return images;
1845
        },
1846

    
1847
        translate_uuids: function(uuids, async, cb) {
1848
            var url = synnefo.config.user_catalog_url;
1849
            var data = JSON.stringify({'uuids': uuids});
1850
          
1851
            // post to user_catalogs api
1852
            snf.api.sync('create', undefined, {
1853
                url: url,
1854
                data: data,
1855
                async: async,
1856
                success:  cb
1857
            });
1858
        },
1859

    
1860
        get_meta_key: function(img, key) {
1861
            if (img.metadata && img.metadata && img.metadata[key]) {
1862
                return _.escape(img.metadata[key]);
1863
            }
1864
            return undefined;
1865
        },
1866

    
1867
        comparator: function(img) {
1868
            return -img.get_sort_order("sortorder") || 1000 * img.id;
1869
        },
1870

    
1871
        parse_meta: function(img) {
1872
            _.each(this.meta_keys_as_attrs, _.bind(function(key){
1873
                if (img[key]) { return };
1874
                img[key] = this.get_meta_key(img, key) || "";
1875
            }, this));
1876
            return img;
1877
        },
1878

    
1879
        active: function() {
1880
            return this.filter(function(img){return img.get('status') != "DELETED"});
1881
        },
1882

    
1883
        predefined: function() {
1884
            return _.filter(this.active(), function(i) { return !i.get("serverRef")});
1885
        },
1886
        
1887
        fetch_for_type: function(type, complete, error) {
1888
            this.fetch({update:true, 
1889
                        success: complete, 
1890
                        error: error, 
1891
                        skip_api_error: true });
1892
        },
1893
        
1894
        get_images_for_type: function(type) {
1895
            if (this['get_{0}_images'.format(type)]) {
1896
                return this['get_{0}_images'.format(type)]();
1897
            }
1898

    
1899
            return this.active();
1900
        },
1901

    
1902
        update_images_for_type: function(type, onStart, onComplete, onError, force_load) {
1903
            var load = false;
1904
            error = onError || function() {};
1905
            function complete(collection) { 
1906
                onComplete(collection.get_images_for_type(type)); 
1907
            }
1908
            
1909
            // do we need to fetch/update current collection entries
1910
            if (load) {
1911
                onStart();
1912
                this.fetch_for_type(type, complete, error);
1913
            } else {
1914
                // fallback to complete
1915
                complete(this);
1916
            }
1917
        }
1918
    })
1919

    
1920
    models.Flavors = models.Collection.extend({
1921
        model: models.Flavor,
1922
        path: 'flavors',
1923
        details: true,
1924
        noUpdate: true,
1925
        supportIncUpdates: false,
1926
        // update collection model with id passed
1927
        // making a direct call to the flavor
1928
        // api url
1929
        update_unknown_id: function(id, callback) {
1930
            var url = getUrl.call(this) + "/" + id;
1931
            this.api_call(this.path + "/" + id, "read", {_options:{async:false, skip_api_error:true}}, undefined, 
1932
            _.bind(function() {
1933
                this.add({id:id, cpu:"Unknown", ram:"Unknown", disk:"Unknown", name: "Unknown", status:"DELETED"})
1934
            }, this), _.bind(function(flv) {
1935
                if (!flv.flavor.status) { flv.flavor.status = "DELETED" };
1936
                this.add(flv.flavor);
1937
            }, this));
1938
        },
1939

    
1940
        parse: function (resp, xhr) {
1941
            return _.map(resp.flavors, function(o) {
1942
              o.cpu = o['vcpus'];
1943
              o.disk_template = o['SNF:disk_template'];
1944
              return o
1945
            });
1946
        },
1947

    
1948
        comparator: function(flv) {
1949
            return flv.get("disk") * flv.get("cpu") * flv.get("ram");
1950
        },
1951
          
1952
        unavailable_values_for_quotas: function(quotas, flavors, extra) {
1953
            var flavors = flavors || this.active();
1954
            var index = {cpu:[], disk:[], ram:[]};
1955
            var extra = extra == undefined ? {cpu:0, disk:0, ram:0} : extra;
1956
            
1957
            _.each(flavors, function(el) {
1958

    
1959
                var disk_available = quotas['disk'] + extra.disk;
1960
                var disk_size = el.get_disk_size();
1961
                if (index.disk.indexOf(disk_size) == -1) {
1962
                  var disk = el.disk_to_bytes();
1963
                  if (disk > disk_available) {
1964
                    index.disk.push(disk_size);
1965
                  }
1966
                }
1967
                
1968
                var ram_available = quotas['ram'] + extra.ram * 1024 * 1024;
1969
                var ram_size = el.get_ram_size();
1970
                if (index.ram.indexOf(ram_size) == -1) {
1971
                  var ram = el.ram_to_bytes();
1972
                  if (ram > ram_available) {
1973
                    index.ram.push(el.get('ram'))
1974
                  }
1975
                }
1976

    
1977
                var cpu = el.get('cpu');
1978
                var cpu_available = quotas['cpu'] + extra.cpu;
1979
                if (index.cpu.indexOf(cpu) == -1) {
1980
                  if (cpu > cpu_available) {
1981
                    index.cpu.push(el.get('cpu'))
1982
                  }
1983
                }
1984
            });
1985
            return index;
1986
        },
1987

    
1988
        unavailable_values_for_image: function(img, flavors) {
1989
            var flavors = flavors || this.active();
1990
            var size = img.get_size();
1991
            
1992
            var index = {cpu:[], disk:[], ram:[]};
1993

    
1994
            _.each(this.active(), function(el) {
1995
                var img_size = size;
1996
                var flv_size = el.get_disk_size();
1997
                if (flv_size < img_size) {
1998
                    if (index.disk.indexOf(flv_size) == -1) {
1999
                        index.disk.push(flv_size);
2000
                    }
2001
                };
2002
            });
2003
            
2004
            return index;
2005
        },
2006

    
2007
        get_flavor: function(cpu, mem, disk, disk_template, filter_list) {
2008
            if (!filter_list) { filter_list = this.models };
2009
            
2010
            return this.select(function(flv){
2011
                if (flv.get("cpu") == cpu + "" &&
2012
                   flv.get("ram") == mem + "" &&
2013
                   flv.get("disk") == disk + "" &&
2014
                   flv.get("disk_template") == disk_template &&
2015
                   filter_list.indexOf(flv) > -1) { return true; }
2016
            })[0];
2017
        },
2018
        
2019
        get_data: function(lst) {
2020
            var data = {'cpu': [], 'mem':[], 'disk':[], 'disk_template':[]};
2021

    
2022
            _.each(lst, function(flv) {
2023
                if (data.cpu.indexOf(flv.get("cpu")) == -1) {
2024
                    data.cpu.push(flv.get("cpu"));
2025
                }
2026
                if (data.mem.indexOf(flv.get("ram")) == -1) {
2027
                    data.mem.push(flv.get("ram"));
2028
                }
2029
                if (data.disk.indexOf(flv.get("disk")) == -1) {
2030
                    data.disk.push(flv.get("disk"));
2031
                }
2032
                if (data.disk_template.indexOf(flv.get("disk_template")) == -1) {
2033
                    data.disk_template.push(flv.get("disk_template"));
2034
                }
2035
            })
2036
            
2037
            return data;
2038
        },
2039

    
2040
        active: function() {
2041
            return this.filter(function(flv){return flv.get('status') != "DELETED"});
2042
        }
2043
            
2044
    })
2045

    
2046
    models.VMS = models.Collection.extend({
2047
        model: models.VM,
2048
        path: 'servers',
2049
        details: true,
2050
        copy_image_meta: true,
2051

    
2052
        parse: function (resp, xhr) {
2053
            var data = resp;
2054
            if (!resp) { return [] };
2055
            data = _.filter(_.map(resp.servers, _.bind(this.parse_vm_api_data, this)), function(v){return v});
2056
            return data;
2057
        },
2058

    
2059
        parse_vm_api_data: function(data) {
2060
            // do not add non existing DELETED entries
2061
            if (data.status && data.status == "DELETED") {
2062
                if (!this.get(data.id)) {
2063
                    return false;
2064
                }
2065
            }
2066

    
2067
            // OS attribute
2068
            if (this.has_meta(data)) {
2069
                data['OS'] = data.metadata.OS || snf.config.unknown_os;
2070
            }
2071
            
2072
            if (!data.diagnostics) {
2073
                data.diagnostics = [];
2074
            }
2075

    
2076
            // network metadata
2077
            data['firewalls'] = {};
2078
            data['nics'] = {};
2079
            data['linked_to'] = [];
2080

    
2081
            if (data['attachments'] && data['attachments']) {
2082
                var nics = data['attachments'];
2083
                _.each(nics, function(nic) {
2084
                    var net_id = nic.network_id;
2085
                    var index = parseInt(NIC_REGEX.exec(nic.id)[2]);
2086
                    if (data['linked_to'].indexOf(net_id) == -1) {
2087
                        data['linked_to'].push(net_id);
2088
                    }
2089

    
2090
                    data['nics'][nic.id] = nic;
2091
                })
2092
            }
2093
            
2094
            // if vm has no metadata, no metadata object
2095
            // is in json response, reset it to force
2096
            // value update
2097
            if (!data['metadata']) {
2098
                data['metadata'] = {};
2099
            }
2100
            
2101
            // v2.0 API returns objects
2102
            data.image_obj = data.image;
2103
            data.image = data.image_obj.id;
2104
            data.flavor_obj = data.flavor;
2105
            data.flavor = data.flavor_obj.id;
2106

    
2107
            return data;
2108
        },
2109

    
2110
        add: function() {
2111
            ret = models.VMS.__super__.add.apply(this, arguments);
2112
            ret.each(function(r){
2113
                synnefo.storage.nics.update_vm_nics(r);
2114
            });
2115
        },
2116
        
2117
        get_reboot_required: function() {
2118
            return this.filter(function(vm){return vm.get("reboot_required") == true})
2119
        },
2120

    
2121
        has_pending_actions: function() {
2122
            return this.filter(function(vm){return vm.pending_action}).length > 0;
2123
        },
2124

    
2125
        reset_pending_actions: function() {
2126
            this.each(function(vm) {
2127
                vm.clear_pending_action();
2128
            })
2129
        },
2130

    
2131
        do_all_pending_actions: function(success, error) {
2132
            this.each(function(vm) {
2133
                if (vm.has_pending_action()) {
2134
                    vm.call(vm.pending_action, success, error);
2135
                    vm.clear_pending_action();
2136
                }
2137
            })
2138
        },
2139
        
2140
        do_all_reboots: function(success, error) {
2141
            this.each(function(vm) {
2142
                if (vm.get("reboot_required")) {
2143
                    vm.call("reboot", success, error);
2144
                }
2145
            });
2146
        },
2147

    
2148
        reset_reboot_required: function() {
2149
            this.each(function(vm) {
2150
                vm.set({'reboot_required': undefined});
2151
            })
2152
        },
2153
        
2154
        stop_stats_update: function(exclude) {
2155
            var exclude = exclude || [];
2156
            this.each(function(vm) {
2157
                if (exclude.indexOf(vm) > -1) {
2158
                    return;
2159
                }
2160
                vm.stop_stats_update();
2161
            })
2162
        },
2163
        
2164
        has_meta: function(vm_data) {
2165
            return vm_data.metadata && vm_data.metadata
2166
        },
2167

    
2168
        has_addresses: function(vm_data) {
2169
            return vm_data.metadata && vm_data.metadata
2170
        },
2171

    
2172
        create: function (name, image, flavor, meta, extra, callback) {
2173

    
2174
            if (this.copy_image_meta) {
2175
                if (synnefo.config.vm_image_common_metadata) {
2176
                    _.each(synnefo.config.vm_image_common_metadata, 
2177
                        function(key){
2178
                            if (image.get_meta(key)) {
2179
                                meta[key] = image.get_meta(key);
2180
                            }
2181
                    });
2182
                }
2183

    
2184
                if (image.get("OS")) {
2185
                    meta['OS'] = image.get("OS");
2186
                }
2187
            }
2188
            
2189
            opts = {name: name, imageRef: image.id, flavorRef: flavor.id, 
2190
                    metadata:meta}
2191
            opts = _.extend(opts, extra);
2192
            
2193
            var cb = function(data) {
2194
              synnefo.storage.quotas.get('cyclades.vm').increase();
2195
              callback(data);
2196
            }
2197

    
2198
            this.api_call(this.path, "create", {'server': opts}, undefined, 
2199
                          undefined, cb, {critical: true});
2200
        },
2201

    
2202
        load_missing_images: function(callback) {
2203
          var missing_ids = [];
2204
          var resolved = 0;
2205

    
2206
          // fill missing_ids
2207
          this.each(function(el) {
2208
            var imgid = el.get("image");
2209
            var existing = synnefo.storage.images.get(imgid);
2210
            if (!existing && missing_ids.indexOf(imgid) == -1) {
2211
              missing_ids.push(imgid);
2212
            }
2213
          });
2214
          var check = function() {
2215
            // once all missing ids where resolved continue calling the 
2216
            // callback
2217
            resolved++;
2218
            if (resolved == missing_ids.length) {
2219
              callback(missing_ids)
2220
            }
2221
          }
2222
          if (missing_ids.length == 0) {
2223
            callback(missing_ids);
2224
            return;
2225
          }
2226
          // start resolving missing image ids
2227
          _(missing_ids).each(function(imgid){
2228
            synnefo.storage.images.update_unknown_id(imgid, check);
2229
          });
2230
        }
2231
    })
2232
    
2233
    models.NIC = models.Model.extend({
2234
        
2235
        initialize: function() {
2236
            models.NIC.__super__.initialize.apply(this, arguments);
2237
            this.pending_for_firewall = false;
2238
            this.bind("change:firewallProfile", _.bind(this.check_firewall, this));
2239
            this.bind("change:pending_firewall", function(nic) {
2240
                nic.get_network().update_state();
2241
            });
2242
            this.get_vm().bind("remove", function(){
2243
                try {
2244
                    this.collection.remove(this);
2245
                } catch (err) {};
2246
            }, this);
2247
            this.get_network().bind("remove", function(){
2248
                try {
2249
                    this.collection.remove(this);
2250
                } catch (err) {};
2251
            }, this);
2252

    
2253
        },
2254

    
2255
        get_vm: function() {
2256
            return synnefo.storage.vms.get(parseInt(this.get('vm_id')));
2257
        },
2258

    
2259
        get_network: function() {
2260
            return synnefo.storage.networks.get(this.get('network_id'));
2261
        },
2262

    
2263
        get_v6_address: function() {
2264
            return this.get("ipv6");
2265
        },
2266

    
2267
        get_v4_address: function() {
2268
            return this.get("ipv4");
2269
        },
2270

    
2271
        set_firewall: function(value, callback, error, options) {
2272
            var net_id = this.get('network_id');
2273
            var self = this;
2274

    
2275
            // api call data
2276
            var payload = {"firewallProfile":{"profile":value}};
2277
            payload._options = _.extend({critical: false}, options);
2278
            
2279
            this.set({'pending_firewall': value});
2280
            this.set({'pending_firewall_sending': true});
2281
            this.set({'pending_firewall_from': this.get('firewallProfile')});
2282

    
2283
            var success_cb = function() {
2284
                if (callback) {
2285
                    callback();
2286
                }
2287
                self.set({'pending_firewall_sending': false});
2288
            };
2289

    
2290
            var error_cb = function() {
2291
                self.reset_pending_firewall();
2292
            }
2293
            
2294
            this.get_vm().api_call(this.get_vm().api_path() + "/action", "create", payload, success_cb, error_cb);
2295
        },
2296

    
2297
        reset_pending_firewall: function() {
2298
            this.set({'pending_firewall': false});
2299
            this.set({'pending_firewall': false});
2300
        },
2301

    
2302
        check_firewall: function() {
2303
            var firewall = this.get('firewallProfile');
2304
            var pending = this.get('pending_firewall');
2305
            var previous = this.get('pending_firewall_from');
2306
            if (previous != firewall) { this.get_vm().require_reboot() };
2307
            this.reset_pending_firewall();
2308
        }
2309
        
2310
    });
2311

    
2312
    models.NICs = models.Collection.extend({
2313
        model: models.NIC,
2314
        
2315
        add_or_update: function(nic_id, data, vm) {
2316
            var params = _.clone(data);
2317
            var vm;
2318
            params.attachment_id = params.id;
2319
            params.id = params.id + '-' + params.network_id;
2320
            params.vm_id = parseInt(NIC_REGEX.exec(nic_id)[1]);
2321

    
2322
            if (!this.get(params.id)) {
2323
                this.add(params);
2324
                var nic = this.get(params.id);
2325
                vm = nic.get_vm();
2326
                nic.get_network().decrease_connecting();
2327
                nic.bind("remove", function() {
2328
                    nic.set({"removing": 0});
2329
                    if (this.get_network()) {
2330
                        // network might got removed before nic
2331
                        nic.get_network().update_state();
2332
                    }
2333
                });
2334

    
2335
            } else {
2336
                this.get(params.id).set(params);
2337
                vm = this.get(params.id).get_vm();
2338
            }
2339
            
2340
            // vm nics changed, trigger vm update
2341
            if (vm) { vm.trigger("change", vm)};
2342
        },
2343
        
2344
        reset_nics: function(nics, filter_attr, filter_val) {
2345
            var nics_to_check = this.filter(function(nic) {
2346
                return nic.get(filter_attr) == filter_val;
2347
            });
2348
            
2349
            _.each(nics_to_check, function(nic) {
2350
                if (nics.indexOf(nic.get('id')) == -1) {
2351
                    this.remove(nic);
2352
                } else {
2353
                }
2354
            }, this);
2355
        },
2356

    
2357
        update_vm_nics: function(vm) {
2358
            var nics = vm.get('nics');
2359
            this.reset_nics(_.map(nics, function(nic, key){
2360
                return key + "-" + nic.network_id;
2361
            }), 'vm_id', vm.id);
2362

    
2363
            _.each(nics, function(val, key) {
2364
                var net = synnefo.storage.networks.get(val.network_id);
2365
                if (net && net.connected_with_nic_id(key) && vm.connected_with_nic_id(key)) {
2366
                    this.add_or_update(key, vm.get('nics')[key], vm);
2367
                }
2368
            }, this);
2369
        },
2370

    
2371
        update_net_nics: function(net) {
2372
            var nics = net.get('nics');
2373
            this.reset_nics(_.map(nics, function(nic, key){
2374
                return key + "-" + net.get('id');
2375
            }), 'network_id', net.id);
2376

    
2377
            _.each(nics, function(val, key) {
2378
                var vm = synnefo.storage.vms.get(val.vm_id);
2379
                if (vm && net.connected_with_nic_id(key) && vm.connected_with_nic_id(key)) {
2380
                    this.add_or_update(key, vm.get('nics')[key], vm);
2381
                }
2382
            }, this);
2383
        }
2384
    });
2385

    
2386
    models.PublicKey = models.Model.extend({
2387
        path: 'keys',
2388
        api_type: 'userdata',
2389
        details: false,
2390
        noUpdate: true,
2391

    
2392

    
2393
        get_public_key: function() {
2394
            return cryptico.publicKeyFromString(this.get("content"));
2395
        },
2396

    
2397
        get_filename: function() {
2398
            return "{0}.pub".format(this.get("name"));
2399
        },
2400

    
2401
        identify_type: function() {
2402
            try {
2403
                var cont = snf.util.validatePublicKey(this.get("content"));
2404
                var type = cont.split(" ")[0];
2405
                return synnefo.util.publicKeyTypesMap[type];
2406
            } catch (err) { return false };
2407
        }
2408

    
2409
    })
2410
    
2411
    models.PublicKeys = models.Collection.extend({
2412
        model: models.PublicKey,
2413
        details: false,
2414
        path: 'keys',
2415
        api_type: 'userdata',
2416
        noUpdate: true,
2417

    
2418
        generate_new: function(success, error) {
2419
            snf.api.sync('create', undefined, {
2420
                url: getUrl.call(this, this.base_url) + "/generate", 
2421
                success: success, 
2422
                error: error,
2423
                skip_api_error: true
2424
            });
2425
        },
2426

    
2427
        add_crypto_key: function(key, success, error, options) {
2428
            var options = options || {};
2429
            var m = new models.PublicKey();
2430

    
2431
            // guess a name
2432
            var name_tpl = "my generated public key";
2433
            var name = name_tpl;
2434
            var name_count = 1;
2435
            
2436
            while(this.filter(function(m){ return m.get("name") == name }).length > 0) {
2437
                name = name_tpl + " " + name_count;
2438
                name_count++;
2439
            }
2440
            
2441
            m.set({name: name});
2442
            m.set({content: key});
2443
            
2444
            options.success = function () { return success(m) };
2445
            options.errror = error;
2446
            options.skip_api_error = true;
2447
            
2448
            this.create(m.attributes, options);
2449
        }
2450
    });
2451

    
2452
  
2453
    models.Quota = models.Model.extend({
2454

    
2455
        initialize: function() {
2456
            models.Quota.__super__.initialize.apply(this, arguments);
2457
            this.bind("change", this.check, this);
2458
            this.check();
2459
        },
2460
        
2461
        check: function() {
2462
            var usage, limit;
2463
            usage = this.get('usage');
2464
            limit = this.get('limit');
2465
            if (usage >= limit) {
2466
                this.trigger("available");
2467
            } else {
2468
                this.trigger("unavailable");
2469
            }
2470
        },
2471

    
2472
        increase: function(val) {
2473
            if (val === undefined) { val = 1};
2474
            this.set({'usage': this.get('usage') + val})
2475
        },
2476

    
2477
        decrease: function(val) {
2478
            if (val === undefined) { val = 1};
2479
            this.set({'usage': this.get('usage') - val})
2480
        },
2481

    
2482
        can_consume: function() {
2483
            var usage, limit;
2484
            usage = this.get('usage');
2485
            limit = this.get('limit');
2486
            if (usage >= limit) {
2487
                return false
2488
            } else {
2489
                return true
2490
            }
2491
        },
2492
        
2493
        is_bytes: function() {
2494
            return this.get('resource').get('unit') == 'bytes';
2495
        },
2496
        
2497
        get_available: function(active) {
2498
            suffix = '';
2499
            if (active) { suffix = '_active'}
2500
            var value = this.get('limit'+suffix) - this.get('usage'+suffix);
2501
            if (value < 0) { return value }
2502
            return value
2503
        },
2504

    
2505
        get_readable: function(key, active) {
2506
            var value;
2507
            if (key == 'available') {
2508
                value = this.get_available(active);
2509
            } else {
2510
                value = this.get(key)
2511
            }
2512
            if (!this.is_bytes()) {
2513
              return value + "";
2514
            }
2515
            return snf.util.readablizeBytes(value);
2516
        }
2517
    });
2518

    
2519
    models.Quotas = models.Collection.extend({
2520
        model: models.Quota,
2521
        api_type: 'accounts',
2522
        path: 'quotas',
2523
        parse: function(resp) {
2524
            filtered = _.map(resp.system, function(value, key) {
2525
                var available = (value.limit - value.usage) || 0;
2526
                var available_active = available;
2527
                var keysplit = key.split(".");
2528
                var limit_active = value.limit;
2529
                var usage_active = value.usage;
2530
                keysplit[keysplit.length-1] = "active_" + keysplit[keysplit.length-1];
2531
                var activekey = keysplit.join(".");
2532
                var exists = resp.system[activekey];
2533
                if (exists) {
2534
                    available_active = exists.limit - exists.usage;
2535
                    limit_active = exists.limit;
2536
                    usage_active = exists.usage;
2537
                }
2538
                return _.extend(value, {'name': key, 'id': key, 
2539
                          'available': available,
2540
                          'available_active': available_active,
2541
                          'limit_active': limit_active,
2542
                          'usage_active': usage_active,
2543
                          'resource': snf.storage.resources.get(key)});
2544
            });
2545
            return filtered;
2546
        },
2547
        
2548
        get_by_id: function(k) {
2549
          return this.filter(function(q) { return q.get('name') == k})[0]
2550
        },
2551

    
2552
        get_available_for_vm: function(active) {
2553
          var quotas = synnefo.storage.quotas;
2554
          var key = 'available';
2555
          if (active) { key = 'available_active'; }
2556
          var quota = {
2557
            'ram': quotas.get('cyclades.ram').get(key),
2558
            'cpu': quotas.get('cyclades.cpu').get(key),
2559
            'disk': quotas.get('cyclades.disk').get(key)
2560
          }
2561
          return quota;
2562
        }
2563
    })
2564

    
2565
    models.Resource = models.Model.extend({
2566
        api_type: 'accounts',
2567
        path: 'resources'
2568
    });
2569

    
2570
    models.Resources = models.Collection.extend({
2571
        api_type: 'accounts',
2572
        path: 'resources',
2573
        model: models.Network,
2574

    
2575
        parse: function(resp) {
2576
            return _.map(resp, function(value, key) {
2577
                return _.extend(value, {'name': key, 'id': key});
2578
            })
2579
        }
2580
    });
2581
    
2582
    // storage initialization
2583
    snf.storage.images = new models.Images();
2584
    snf.storage.flavors = new models.Flavors();
2585
    snf.storage.networks = new models.Networks();
2586
    snf.storage.vms = new models.VMS();
2587
    snf.storage.keys = new models.PublicKeys();
2588
    snf.storage.nics = new models.NICs();
2589
    snf.storage.resources = new models.Resources();
2590
    snf.storage.quotas = new models.Quotas();
2591

    
2592
})(this);