Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (77.6 kB)

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

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

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

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

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

    
65
    // Base object for all our models
66
    models.Model = bb.Model.extend({
67
        sync: snf.api.sync,
68
        api: snf.api,
69
        api_type: 'compute',
70
        has_status: false,
71

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

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

    
107
        url: function(options) {
108
            return getUrl.call(this, this.base_url) + "/" + this.id;
109
        },
110

    
111
        api_path: function(options) {
112
            return this.path + "/" + this.id;
113
        },
114

    
115
        parse: function(resp, xhr) {
116
        },
117

    
118
        remove: function(complete, error, success) {
119
            this.api_call(this.api_path(), "delete", undefined, complete, error, success);
120
        },
121

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

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

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

    
155
        initialize: function() {
156
            models.Collection.__super__.initialize.apply(this, arguments);
157
            this.api_call = _.bind(this.api.call, this);
158
        },
159

    
160
        url: function(options, method) {
161
            return getUrl.call(this, this.base_url) + (
162
                    options.details || this.details && method != 'create' ? '/detail' : '');
163
        },
164

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

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

    
193
        get_fetcher: function(interval, increase, fast, increase_after_calls, max, initial_call, params) {
194
            var fetch_params = params || {};
195
            var handler_options = {};
196

    
197
            fetch_params.skips_timeouts = true;
198
            handler_options.interval = interval;
199
            handler_options.increase = increase;
200
            handler_options.fast = fast;
201
            handler_options.increase_after_calls = increase_after_calls;
202
            handler_options.max= max;
203
            handler_options.id = "collection id";
204

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

    
223
            var updater = new snf.api.updateHandler(_.clone(_.extend(handler_options, fetch_params)));
224
            snf.api.bind("call", _.throttle(_.bind(function(){ updater.faster(true)}, this)), 1000);
225
            return updater;
226
        }
227
    });
228
    
229
    // Image model
230
    models.Image = models.Model.extend({
231
        path: 'images',
232

    
233
        get_size: function() {
234
            return parseInt(this.get('metadata') ? this.get('metadata').values.size : -1)
235
        },
236

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

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

    
252
        get_meta_keys: function() {
253
            if (this.get('metadata') && this.get('metadata').values) {
254
                return _.keys(this.get('metadata').values);
255
            } else {
256
                return [];
257
            }
258
        },
259

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

    
264
        is_system_image: function() {
265
          var owner = this.get_owner();
266
          return _.include(_.keys(synnefo.config.system_images_owners), owner)
267
        },
268

    
269
        owned_by: function(user) {
270
          if (!user) { user = synnefo.user }
271
          return user.username == this.get_owner();
272
        },
273

    
274
        display_owner: function() {
275
            var owner = this.get_owner();
276
            if (_.include(_.keys(synnefo.config.system_images_owners), owner)) {
277
                return synnefo.config.system_images_owners[owner];
278
            } else {
279
                return owner;
280
            }
281
        },
282
    
283
        get_readable_size: function() {
284
            if (this.is_deleted()) {
285
                return synnefo.config.image_deleted_size_title || '(none)';
286
            }
287
            return this.get_size() > 0 ? util.readablizeBytes(this.get_size() * 1024 * 1024) : '(none)';
288
        },
289

    
290
        get_os: function() {
291
            return this.get_meta('OS');
292
        },
293

    
294
        get_gui: function() {
295
            return this.get_meta('GUI');
296
        },
297

    
298
        get_created_users: function() {
299
            try {
300
              var users = this.get_meta('users').split(" ");
301
            } catch (err) { users = null }
302
            if (!users) { users = [synnefo.config.os_created_users[this.get_os()] || "root"]}
303
            return users;
304
        },
305

    
306
        get_sort_order: function() {
307
            return parseInt(this.get('metadata') ? this.get('metadata').values.sortorder : -1)
308
        },
309

    
310
        get_vm: function() {
311
            var vm_id = this.get("serverRef");
312
            var vm = undefined;
313
            vm = storage.vms.get(vm_id);
314
            return vm;
315
        },
316

    
317
        is_public: function() {
318
            return this.get('is_public') == undefined ? true : this.get('is_public');
319
        },
320

    
321
        is_deleted: function() {
322
            return this.get('status') == "DELETED"
323
        },
324
        
325
        ssh_keys_paths: function() {
326
            return _.map(this.get_created_users(), function(username) {
327
                prepend = '';
328
                if (username != 'root') {
329
                    prepend = '/home'
330
                }
331
                return {'user': username, 'path': '{1}/{0}/.ssh/authorized_keys'.format(username, 
332
                                                             prepend)};
333
            });
334
        },
335

    
336
        _supports_ssh: function() {
337
            if (synnefo.config.support_ssh_os_list.indexOf(this.get_os()) > -1) {
338
                return true;
339
            }
340
            if (this.get_meta('osfamily') == 'linux') {
341
              return true;
342
            }
343
            return false;
344
        },
345

    
346
        supports: function(feature) {
347
            if (feature == "ssh") {
348
                return this._supports_ssh()
349
            }
350
            return false;
351
        },
352

    
353
        personality_data_for_keys: function(keys) {
354
            return _.map(this.ssh_keys_paths(), function(pathinfo) {
355
                var contents = '';
356
                _.each(keys, function(key){
357
                    contents = contents + key.get("content") + "\n"
358
                });
359
                contents = $.base64.encode(contents);
360

    
361
                return {
362
                    path: pathinfo.path,
363
                    contents: contents,
364
                    mode: 0600,
365
                    owner: pathinfo.user,
366
                    group: pathinfo.user
367
                }
368
            });
369
        }
370
    });
371

    
372
    // Flavor model
373
    models.Flavor = models.Model.extend({
374
        path: 'flavors',
375

    
376
        details_string: function() {
377
            return "{0} CPU, {1}MB, {2}GB".format(this.get('cpu'), this.get('ram'), this.get('disk'));
378
        },
379

    
380
        get_disk_size: function() {
381
            return parseInt(this.get("disk") * 1000)
382
        },
383

    
384
        get_disk_template_info: function() {
385
            var info = snf.config.flavors_disk_templates_info[this.get("disk_template")];
386
            if (!info) {
387
                info = { name: this.get("disk_template"), description:'' };
388
            }
389
            return info
390
        }
391

    
392
    });
393
    
394
    models.ParamsList = function(){this.initialize.apply(this, arguments)};
395
    _.extend(models.ParamsList.prototype, bb.Events, {
396

    
397
        initialize: function(parent, param_name) {
398
            this.parent = parent;
399
            this.actions = {};
400
            this.param_name = param_name;
401
            this.length = 0;
402
        },
403
        
404
        has_action: function(action) {
405
            return this.actions[action] ? true : false;
406
        },
407
            
408
        _parse_params: function(arguments) {
409
            if (arguments.length <= 1) {
410
                return [];
411
            }
412

    
413
            var args = _.toArray(arguments);
414
            return args.splice(1);
415
        },
416

    
417
        contains: function(action, params) {
418
            params = this._parse_params(arguments);
419
            var has_action = this.has_action(action);
420
            if (!has_action) { return false };
421

    
422
            var paramsEqual = false;
423
            _.each(this.actions[action], function(action_params) {
424
                if (_.isEqual(action_params, params)) {
425
                    paramsEqual = true;
426
                }
427
            });
428
                
429
            return paramsEqual;
430
        },
431
        
432
        is_empty: function() {
433
            return _.isEmpty(this.actions);
434
        },
435

    
436
        add: function(action, params) {
437
            params = this._parse_params(arguments);
438
            if (this.contains.apply(this, arguments)) { return this };
439
            var isnew = false
440
            if (!this.has_action(action)) {
441
                this.actions[action] = [];
442
                isnew = true;
443
            };
444

    
445
            this.actions[action].push(params);
446
            this.parent.trigger("change:" + this.param_name, this.parent, this);
447
            if (isnew) {
448
                this.trigger("add", action, params);
449
            } else {
450
                this.trigger("change", action, params);
451
            }
452
            return this;
453
        },
454
        
455
        remove_all: function(action) {
456
            if (this.has_action(action)) {
457
                delete this.actions[action];
458
                this.parent.trigger("change:" + this.param_name, this.parent, this);
459
                this.trigger("remove", action);
460
            }
461
            return this;
462
        },
463

    
464
        reset: function() {
465
            this.actions = {};
466
            this.parent.trigger("change:" + this.param_name, this.parent, this);
467
            this.trigger("reset");
468
            this.trigger("remove");
469
        },
470

    
471
        remove: function(action, params) {
472
            params = this._parse_params(arguments);
473
            if (!this.has_action(action)) { return this };
474
            var index = -1;
475
            _.each(this.actions[action], _.bind(function(action_params) {
476
                if (_.isEqual(action_params, params)) {
477
                    index = this.actions[action].indexOf(action_params);
478
                }
479
            }, this));
480
            
481
            if (index > -1) {
482
                this.actions[action].splice(index, 1);
483
                if (_.isEmpty(this.actions[action])) {
484
                    delete this.actions[action];
485
                }
486
                this.parent.trigger("change:" + this.param_name, this.parent, this);
487
                this.trigger("remove", action, params);
488
            }
489
        }
490

    
491
    });
492

    
493
    // Image model
494
    models.Network = models.Model.extend({
495
        path: 'networks',
496
        has_status: true,
497
        defaults: {'connecting':0},
498
        
499
        initialize: function() {
500
            var ret = models.Network.__super__.initialize.apply(this, arguments);
501
            this.set({"actions": new models.ParamsList(this, "actions")});
502
            this.update_state();
503
            this.bind("change:nics", _.bind(synnefo.storage.nics.update_net_nics, synnefo.storage.nics));
504
            this.bind("change:status", _.bind(this.update_state, this));
505
            return ret;
506
        },
507
        
508
        is_deleted: function() {
509
          return this.get('status') == 'DELETED';
510
        },
511

    
512
        toJSON: function() {
513
            var attrs = _.clone(this.attributes);
514
            attrs.actions = _.clone(this.get("actions").actions);
515
            return attrs;
516
        },
517
        
518
        set_state: function(val) {
519
            if (val == "PENDING" && this.get("state") == "DESTORY") {
520
                return "DESTROY";
521
            }
522
            return val;
523
        },
524

    
525
        update_state: function() {
526
            if (this.get("connecting") > 0) {
527
                this.set({state: "CONNECTING"});
528
                return
529
            }
530
            
531
            if (this.get_nics(function(nic){ return nic.get("removing") == 1}).length > 0) {
532
                this.set({state: "DISCONNECTING"});
533
                return
534
            }   
535
            
536
            if (this.contains_firewalling_nics() > 0) {
537
                this.set({state: "FIREWALLING"});
538
                return
539
            }   
540
            
541
            if (this.get("state") == "DESTROY") { 
542
                this.set({"destroyed":1});
543
            }
544
            
545
            this.set({state:this.get('status')});
546
        },
547

    
548
        is_public: function() {
549
            return this.get("public");
550
        },
551

    
552
        decrease_connecting: function() {
553
            var conn = this.get("connecting");
554
            if (!conn) { conn = 0 };
555
            if (conn > 0) {
556
                conn--;
557
            }
558
            this.set({"connecting": conn});
559
            this.update_state();
560
        },
561

    
562
        increase_connecting: function() {
563
            var conn = this.get("connecting");
564
            if (!conn) { conn = 0 };
565
            conn++;
566
            this.set({"connecting": conn});
567
            this.update_state();
568
        },
569

    
570
        connected_to: function(vm) {
571
            return this.get('linked_to').indexOf(""+vm.id) > -1;
572
        },
573

    
574
        connected_with_nic_id: function(nic_id) {
575
            return _.keys(this.get('nics')).indexOf(nic_id) > -1;
576
        },
577

    
578
        get_nics: function(filter) {
579
            var nics = synnefo.storage.nics.filter(function(nic) {
580
                return nic.get('network_id') == this.id;
581
            }, this);
582

    
583
            if (filter) {
584
                return _.filter(nics, filter);
585
            }
586
            return nics;
587
        },
588

    
589
        contains_firewalling_nics: function() {
590
            return this.get_nics(function(n){return n.get('pending_firewall')}).length
591
        },
592

    
593
        call: function(action, params, success, error) {
594
            if (action == "destroy") {
595
                var previous_state = this.get('state');
596
                var previous_status = this.get('status');
597

    
598
                this.set({state:"DESTROY"});
599

    
600
                var _success = _.bind(function() {
601
                    if (success) { success() };
602
                }, this);
603
                var _error = _.bind(function() {
604
                    this.set({state: previous_state, status: previous_status})
605
                    if (error) { error() };
606
                }, this);
607

    
608
                this.remove(undefined, _error, _success);
609
            }
610
            
611
            if (action == "disconnect") {
612
                if (this.get("state") == "DESTROY") {
613
                    return;
614
                }
615
                
616
                _.each(params, _.bind(function(nic_id) {
617
                    var nic = snf.storage.nics.get(nic_id);
618
                    this.get("actions").remove("disconnect", nic_id);
619
                    if (nic) {
620
                        this.remove_nic(nic, success, error);
621
                    }
622
                }, this));
623
            }
624
        },
625

    
626
        add_vm: function (vm, callback, error, options) {
627
            var payload = {add:{serverRef:"" + vm.id}};
628
            payload._options = options || {};
629
            return this.api_call(this.api_path() + "/action", "create", 
630
                                 payload,
631
                                 undefined,
632
                                 error,
633
                                 _.bind(function(){
634
                                     //this.vms.add_pending(vm.id);
635
                                     this.increase_connecting();
636
                                     if (callback) {callback()}
637
                                 },this), error);
638
        },
639

    
640
        remove_nic: function (nic, callback, error, options) {
641
            var payload = {remove:{attachment:"" + nic.get("attachment_id")}};
642
            payload._options = options || {};
643
            return this.api_call(this.api_path() + "/action", "create", 
644
                                 payload,
645
                                 undefined,
646
                                 error,
647
                                 _.bind(function(){
648
                                     nic.set({"removing": 1});
649
                                     nic.get_network().update_state();
650
                                     //this.vms.add_pending_for_remove(vm.id);
651
                                     if (callback) {callback()}
652
                                 },this), error);
653
        },
654

    
655
        rename: function(name, callback) {
656
            return this.api_call(this.api_path(), "update", {
657
                network:{name:name}, 
658
                _options:{
659
                    critical: false, 
660
                    error_params:{
661
                        title: "Network action failed",
662
                        ns: "Networks",
663
                        extra_details: {"Network id": this.id}
664
                    }
665
                }}, callback);
666
        },
667

    
668
        get_connectable_vms: function() {
669
            return storage.vms.filter(function(vm){
670
                return !vm.in_error_state() && !vm.is_building();
671
            })
672
        },
673

    
674
        state_message: function() {
675
            if (this.get("state") == "ACTIVE" && !this.is_public()) {
676
                if (this.get("cidr") && this.get("dhcp") == true) {
677
                    return this.get("cidr");
678
                } else {
679
                    return "Private network";
680
                }
681
            }
682
            if (this.get("state") == "ACTIVE" && this.is_public()) {
683
                  return "Public network";
684
            }
685

    
686
            return models.Network.STATES[this.get("state")];
687
        },
688

    
689
        in_progress: function() {
690
            return models.Network.STATES_TRANSITIONS[this.get("state")] != undefined;
691
        },
692

    
693
        do_all_pending_actions: function(success, error) {
694
          var params, actions, action_params;
695
          actions = _.clone(this.get("actions").actions);
696
            _.each(actions, _.bind(function(params, action) {
697
                action_params = _.map(actions[action], function(a){ return _.clone(a)});
698
                _.each(action_params, _.bind(function(params) {
699
                    this.call(action, params, success, error);
700
                }, this));
701
            }, this));
702
            this.get("actions").reset();
703
        }
704
    });
705
    
706
    models.Network.STATES = {
707
        'ACTIVE': 'Private network',
708
        'CONNECTING': 'Connecting...',
709
        'DISCONNECTING': 'Disconnecting...',
710
        'FIREWALLING': 'Firewall update...',
711
        'DESTROY': 'Destroying...',
712
        'PENDING': 'Pending...',
713
        'ERROR': 'Error'
714
    }
715

    
716
    models.Network.STATES_TRANSITIONS = {
717
        'CONNECTING': ['ACTIVE'],
718
        'DISCONNECTING': ['ACTIVE'],
719
        'PENDING': ['ACTIVE'],
720
        'FIREWALLING': ['ACTIVE']
721
    }
722

    
723
    // Virtualmachine model
724
    models.VM = models.Model.extend({
725

    
726
        path: 'servers',
727
        has_status: true,
728
        initialize: function(params) {
729
            
730
            this.pending_firewalls = {};
731
            
732
            models.VM.__super__.initialize.apply(this, arguments);
733

    
734
            this.set({state: params.status || "ERROR"});
735
            this.log = new snf.logging.logger("VM " + this.id);
736
            this.pending_action = undefined;
737
            
738
            // init stats parameter
739
            this.set({'stats': undefined}, {silent: true});
740
            // defaults to not update the stats
741
            // each view should handle this vm attribute 
742
            // depending on if it displays stat images or not
743
            this.do_update_stats = false;
744
            
745
            // interval time
746
            // this will dynamicaly change if the server responds that
747
            // images get refreshed on different intervals
748
            this.stats_update_interval = synnefo.config.STATS_INTERVAL || 5000;
749
            this.stats_available = false;
750

    
751
            // initialize interval
752
            this.init_stats_intervals(this.stats_update_interval);
753
            
754
            // handle progress message on instance change
755
            this.bind("change", _.bind(this.update_status_message, this));
756
            // force update of progress message
757
            this.update_status_message(true);
758
            
759
            // default values
760
            this.bind("change:state", _.bind(function(){
761
                if (this.state() == "DESTROY") { 
762
                    this.handle_destroy() 
763
                }
764
            }, this));
765

    
766
            this.bind("change:nics", _.bind(synnefo.storage.nics.update_vm_nics, synnefo.storage.nics));
767
        },
768

    
769
        status: function(st) {
770
            if (!st) { return this.get("status")}
771
            return this.set({status:st});
772
        },
773

    
774
        set_status: function(st) {
775
            var new_state = this.state_for_api_status(st);
776
            var transition = false;
777

    
778
            if (this.state() != new_state) {
779
                if (models.VM.STATES_TRANSITIONS[this.state()]) {
780
                    transition = this.state();
781
                }
782
            }
783
            
784
            // call it silently to avoid double change trigger
785
            this.set({'state': this.state_for_api_status(st)}, {silent: true});
786
            
787
            // trigger transition
788
            if (transition && models.VM.TRANSITION_STATES.indexOf(new_state) == -1) { 
789
                this.trigger("transition", {from:transition, to:new_state}) 
790
            };
791
            return st;
792
        },
793
            
794
        get_diagnostics: function(success) {
795
            this.__make_api_call(this.get_diagnostics_url(),
796
                                 "read", // create so that sync later uses POST to make the call
797
                                 null, // payload
798
                                 function(data) {
799
                                     success(data);
800
                                 },  
801
                                 null, 'diagnostics');
802
        },
803

    
804
        has_diagnostics: function() {
805
            return this.get("diagnostics") && this.get("diagnostics").length;
806
        },
807

    
808
        get_progress_info: function() {
809
            // details about progress message
810
            // contains a list of diagnostic messages
811
            return this.get("status_messages");
812
        },
813

    
814
        get_status_message: function() {
815
            return this.get('status_message');
816
        },
817
        
818
        // extract status message from diagnostics
819
        status_message_from_diagnostics: function(diagnostics) {
820
            var valid_sources_map = synnefo.config.diagnostics_status_messages_map;
821
            var valid_sources = valid_sources_map[this.get('status')];
822
            if (!valid_sources) { return null };
823
            
824
            // filter messsages based on diagnostic source
825
            var messages = _.filter(diagnostics, function(diag) {
826
                return valid_sources.indexOf(diag.source) > -1;
827
            });
828

    
829
            var msg = messages[0];
830
            if (msg) {
831
              var message = msg.message;
832
              var message_tpl = snf.config.diagnostic_messages_tpls[msg.source];
833

    
834
              if (message_tpl) {
835
                  message = message_tpl.replace('MESSAGE', msg.message);
836
              }
837
              return message;
838
            }
839
            
840
            // no message to display, but vm in build state, display
841
            // finalizing message.
842
            if (this.is_building() == 'BUILD') {
843
                return synnefo.config.BUILDING_MESSAGES['FINAL'];
844
            }
845
            return null;
846
        },
847

    
848
        update_status_message: function(force) {
849
            // update only if one of the specified attributes has changed
850
            if (
851
              !this.keysChanged(['diagnostics', 'progress', 'status', 'state'])
852
                && !force
853
            ) { return };
854
            
855
            // if user requested to destroy the vm set the appropriate 
856
            // message.
857
            if (this.get('state') == "DESTROY") { 
858
                message = "Terminating..."
859
                this.set({status_message: message})
860
                return;
861
            }
862
            
863
            // set error message, if vm has diagnostic message display it as
864
            // progress message
865
            if (this.in_error_state()) {
866
                var d = this.get('diagnostics');
867
                if (d && d.length) {
868
                    var message = this.status_message_from_diagnostics(d);
869
                    this.set({status_message: message});
870
                } else {
871
                    this.set({status_message: null});
872
                }
873
                return;
874
            }
875
            
876
            // identify building status message
877
            if (this.is_building()) {
878
                var self = this;
879
                var success = function(msg) {
880
                    self.set({status_message: msg});
881
                }
882
                this.get_building_status_message(success);
883
                return;
884
            }
885

    
886
            this.set({status_message:null});
887
        },
888
            
889
        // get building status message. Asynchronous function since it requires
890
        // access to vm image.
891
        get_building_status_message: function(callback) {
892
            // no progress is set, vm is in initial build status
893
            var progress = this.get("progress");
894
            if (progress == 0 || !progress) {
895
                return callback(BUILDING_MESSAGES['INIT']);
896
            }
897
            
898
            // vm has copy progress, display copy percentage
899
            if (progress > 0 && progress <= 99) {
900
                this.get_copy_details(true, undefined, _.bind(
901
                    function(details){
902
                        callback(BUILDING_MESSAGES['COPY'].format(details.copy, 
903
                                                           details.size, 
904
                                                           details.progress));
905
                }, this));
906
                return;
907
            }
908

    
909
            // copy finished display FINAL message or identify status message
910
            // from diagnostics.
911
            if (progress >= 100) {
912
                if (!this.has_diagnostics()) {
913
                        callback(BUILDING_MESSAGES['FINAL']);
914
                } else {
915
                        var d = this.get("diagnostics");
916
                        var msg = this.status_message_from_diagnostics(d);
917
                        if (msg) {
918
                              callback(msg);
919
                        }
920
                }
921
            }
922
        },
923

    
924
        get_copy_details: function(human, image, callback) {
925
            var human = human || false;
926
            var image = image || this.get_image(_.bind(function(image){
927
                var progress = this.get('progress');
928
                var size = image.get_size();
929
                var size_copied = (size * progress / 100).toFixed(2);
930
                
931
                if (human) {
932
                    size = util.readablizeBytes(size*1024*1024);
933
                    size_copied = util.readablizeBytes(size_copied*1024*1024);
934
                }
935

    
936
                callback({'progress': progress, 'size': size, 'copy': size_copied})
937
            }, this));
938
        },
939

    
940
        start_stats_update: function(force_if_empty) {
941
            var prev_state = this.do_update_stats;
942

    
943
            this.do_update_stats = true;
944
            
945
            // fetcher initialized ??
946
            if (!this.stats_fetcher) {
947
                this.init_stats_intervals();
948
            }
949

    
950

    
951
            // fetcher running ???
952
            if (!this.stats_fetcher.running || !prev_state) {
953
                this.stats_fetcher.start();
954
            }
955

    
956
            if (force_if_empty && this.get("stats") == undefined) {
957
                this.update_stats(true);
958
            }
959
        },
960

    
961
        stop_stats_update: function(stop_calls) {
962
            this.do_update_stats = false;
963

    
964
            if (stop_calls) {
965
                this.stats_fetcher.stop();
966
            }
967
        },
968

    
969
        // clear and reinitialize update interval
970
        init_stats_intervals: function (interval) {
971
            this.stats_fetcher = this.get_stats_fetcher(this.stats_update_interval);
972
            this.stats_fetcher.start();
973
        },
974
        
975
        get_stats_fetcher: function(timeout) {
976
            var cb = _.bind(function(data){
977
                this.update_stats();
978
            }, this);
979
            var fetcher = new snf.api.updateHandler({'callback': cb, interval: timeout, id:'stats'});
980
            return fetcher;
981
        },
982

    
983
        // do the api call
984
        update_stats: function(force) {
985
            // do not update stats if flag not set
986
            if ((!this.do_update_stats && !force) || this.updating_stats) {
987
                return;
988
            }
989

    
990
            // make the api call, execute handle_stats_update on sucess
991
            // TODO: onError handler ???
992
            stats_url = this.url() + "/stats";
993
            this.updating_stats = true;
994
            this.sync("read", this, {
995
                handles_error:true, 
996
                url: stats_url, 
997
                refresh:true, 
998
                success: _.bind(this.handle_stats_update, this),
999
                error: _.bind(this.handle_stats_error, this),
1000
                complete: _.bind(function(){this.updating_stats = false;}, this),
1001
                critical: false,
1002
                log_error: false,
1003
                skips_timeouts: true
1004
            });
1005
        },
1006

    
1007
        get_stats_image: function(stat, type) {
1008
        },
1009
        
1010
        _set_stats: function(stats) {
1011
            var silent = silent === undefined ? false : silent;
1012
            // unavailable stats while building
1013
            if (this.get("status") == "BUILD") { 
1014
                this.stats_available = false;
1015
            } else { this.stats_available = true; }
1016

    
1017
            if (this.get("status") == "DESTROY") { this.stats_available = false; }
1018
            
1019
            this.set({stats: stats}, {silent:true});
1020
            this.trigger("stats:update", stats);
1021
        },
1022

    
1023
        unbind: function() {
1024
            models.VM.__super__.unbind.apply(this, arguments);
1025
        },
1026

    
1027
        handle_stats_error: function() {
1028
            stats = {};
1029
            _.each(['cpuBar', 'cpuTimeSeries', 'netBar', 'netTimeSeries'], function(k) {
1030
                stats[k] = false;
1031
            });
1032

    
1033
            this.set({'stats': stats});
1034
        },
1035

    
1036
        // this method gets executed after a successful vm stats api call
1037
        handle_stats_update: function(data) {
1038
            var self = this;
1039
            // avoid browser caching
1040
            
1041
            if (data.stats && _.size(data.stats) > 0) {
1042
                var ts = $.now();
1043
                var stats = data.stats;
1044
                var images_loaded = 0;
1045
                var images = {};
1046

    
1047
                function check_images_loaded() {
1048
                    images_loaded++;
1049

    
1050
                    if (images_loaded == 4) {
1051
                        self._set_stats(images);
1052
                    }
1053
                }
1054
                _.each(['cpuBar', 'cpuTimeSeries', 'netBar', 'netTimeSeries'], function(k) {
1055
                    
1056
                    stats[k] = stats[k] + "?_=" + ts;
1057
                    
1058
                    var stat = k.slice(0,3);
1059
                    var type = k.slice(3,6) == "Bar" ? "bar" : "time";
1060
                    var img = $("<img />");
1061
                    var val = stats[k];
1062
                    
1063
                    // load stat image to a temporary dom element
1064
                    // update model stats on image load/error events
1065
                    img.load(function() {
1066
                        images[k] = val;
1067
                        check_images_loaded();
1068
                    });
1069

    
1070
                    img.error(function() {
1071
                        images[stat + type] = false;
1072
                        check_images_loaded();
1073
                    });
1074

    
1075
                    img.attr({'src': stats[k]});
1076
                })
1077
                data.stats = stats;
1078
            }
1079

    
1080
            // do we need to change the interval ??
1081
            if (data.stats.refresh * 1000 != this.stats_update_interval) {
1082
                this.stats_update_interval = data.stats.refresh * 1000;
1083
                this.stats_fetcher.interval = this.stats_update_interval;
1084
                this.stats_fetcher.maximum_interval = this.stats_update_interval;
1085
                this.stats_fetcher.stop();
1086
                this.stats_fetcher.start(false);
1087
            }
1088
        },
1089

    
1090
        // helper method that sets the do_update_stats
1091
        // in the future this method could also make an api call
1092
        // immediaetly if needed
1093
        enable_stats_update: function() {
1094
            this.do_update_stats = true;
1095
        },
1096
        
1097
        handle_destroy: function() {
1098
            this.stats_fetcher.stop();
1099
        },
1100

    
1101
        require_reboot: function() {
1102
            if (this.is_active()) {
1103
                this.set({'reboot_required': true});
1104
            }
1105
        },
1106
        
1107
        set_pending_action: function(data) {
1108
            this.pending_action = data;
1109
            return data;
1110
        },
1111

    
1112
        // machine has pending action
1113
        update_pending_action: function(action, force) {
1114
            this.set({pending_action: action});
1115
        },
1116

    
1117
        clear_pending_action: function() {
1118
            this.set({pending_action: undefined});
1119
        },
1120

    
1121
        has_pending_action: function() {
1122
            return this.get("pending_action") ? this.get("pending_action") : false;
1123
        },
1124
        
1125
        // machine is active
1126
        is_active: function() {
1127
            return models.VM.ACTIVE_STATES.indexOf(this.state()) > -1;
1128
        },
1129
        
1130
        // machine is building 
1131
        is_building: function() {
1132
            return models.VM.BUILDING_STATES.indexOf(this.state()) > -1;
1133
        },
1134
        
1135
        in_error_state: function() {
1136
            return this.state() === "ERROR"
1137
        },
1138

    
1139
        // user can connect to machine
1140
        is_connectable: function() {
1141
            // check if ips exist
1142
            if (!this.get_addresses().ip4 && !this.get_addresses().ip6) {
1143
                return false;
1144
            }
1145
            return models.VM.CONNECT_STATES.indexOf(this.state()) > -1;
1146
        },
1147
        
1148
        remove_meta: function(key, complete, error) {
1149
            var url = this.api_path() + "/meta/" + key;
1150
            this.api_call(url, "delete", undefined, complete, error);
1151
        },
1152

    
1153
        save_meta: function(meta, complete, error) {
1154
            var url = this.api_path() + "/meta/" + meta.key;
1155
            var payload = {meta:{}};
1156
            payload.meta[meta.key] = meta.value;
1157
            payload._options = {
1158
                critical:false, 
1159
                error_params: {
1160
                    title: "Machine metadata error",
1161
                    extra_details: {"Machine id": this.id}
1162
            }};
1163

    
1164
            this.api_call(url, "update", payload, complete, error);
1165
        },
1166

    
1167

    
1168
        // update/get the state of the machine
1169
        state: function() {
1170
            var args = slice.call(arguments);
1171
                
1172
            // TODO: it might not be a good idea to set the state in set_state method
1173
            if (args.length > 0 && models.VM.STATES.indexOf(args[0]) > -1) {
1174
                this.set({'state': args[0]});
1175
            }
1176

    
1177
            return this.get('state');
1178
        },
1179
        
1180
        // get the state that the api status corresponds to
1181
        state_for_api_status: function(status) {
1182
            return this.state_transition(this.state(), status);
1183
        },
1184
        
1185
        // vm state equals vm api status
1186
        state_is_status: function(state) {
1187
            return models.VM.STATUSES.indexOf(state) != -1;
1188
        },
1189
        
1190
        // get transition state for the corresponging api status
1191
        state_transition: function(state, new_status) {
1192
            var statuses = models.VM.STATES_TRANSITIONS[state];
1193
            if (statuses) {
1194
                if (statuses.indexOf(new_status) > -1) {
1195
                    return new_status;
1196
                } else {
1197
                    return state;
1198
                }
1199
            } else {
1200
                return new_status;
1201
            }
1202
        },
1203
        
1204
        // the current vm state is a transition state
1205
        in_transition: function() {
1206
            return models.VM.TRANSITION_STATES.indexOf(this.state()) > -1 || 
1207
                models.VM.TRANSITION_STATES.indexOf(this.get('status')) > -1;
1208
        },
1209
        
1210
        // get image object
1211
        get_image: function(callback) {
1212
            if (callback == undefined) { callback = function(){} }
1213
            var image = storage.images.get(this.get('imageRef'));
1214
            if (!image) {
1215
                storage.images.update_unknown_id(this.get('imageRef'), callback);
1216
                return;
1217
            }
1218
            callback(image);
1219
            return image;
1220
        },
1221
        
1222
        // get flavor object
1223
        get_flavor: function() {
1224
            var flv = storage.flavors.get(this.get('flavorRef'));
1225
            if (!flv) {
1226
                storage.flavors.update_unknown_id(this.get('flavorRef'));
1227
                flv = storage.flavors.get(this.get('flavorRef'));
1228
            }
1229
            return flv;
1230
        },
1231

    
1232
        get_meta: function(key, deflt) {
1233
            if (this.get('metadata') && this.get('metadata').values) {
1234
                if (!this.get('metadata').values[key]) { return deflt }
1235
                return _.escape(this.get('metadata').values[key]);
1236
            } else {
1237
                return deflt;
1238
            }
1239
        },
1240

    
1241
        get_meta_keys: function() {
1242
            if (this.get('metadata') && this.get('metadata').values) {
1243
                return _.keys(this.get('metadata').values);
1244
            } else {
1245
                return [];
1246
            }
1247
        },
1248
        
1249
        // get metadata OS value
1250
        get_os: function() {
1251
            var image = this.get_image();
1252
            return this.get_meta('OS') || (image ? 
1253
                                            image.get_os() || "okeanos" : "okeanos");
1254
        },
1255

    
1256
        get_gui: function() {
1257
            return this.get_meta('GUI');
1258
        },
1259
        
1260
        connected_to: function(net) {
1261
            return this.get('linked_to').indexOf(net.id) > -1;
1262
        },
1263

    
1264
        connected_with_nic_id: function(nic_id) {
1265
            return _.keys(this.get('nics')).indexOf(nic_id) > -1;
1266
        },
1267

    
1268
        get_nics: function(filter) {
1269
            ret = synnefo.storage.nics.filter(function(nic) {
1270
                return parseInt(nic.get('vm_id')) == this.id;
1271
            }, this);
1272

    
1273
            if (filter) {
1274
                return _.filter(ret, filter);
1275
            }
1276

    
1277
            return ret;
1278
        },
1279

    
1280
        get_net_nics: function(net_id) {
1281
            return this.get_nics(function(n){return n.get('network_id') == net_id});
1282
        },
1283

    
1284
        get_public_nic: function() {
1285
            return this.get_nics(function(n){ return n.get_network().is_public() === true })[0];
1286
        },
1287

    
1288
        get_hostname: function() {
1289
          var hostname = this.get_meta('hostname');
1290
          if (!hostname) {
1291
            if (synnefo.config.vm_hostname_format) {
1292
              hostname = synnefo.config.vm_hostname_format.format(this.id);
1293
            } else {
1294
              hostname = this.get_public_nic().get('ipv4');
1295
            }
1296
          }
1297
          return hostname;
1298
        },
1299

    
1300
        get_nic: function(net_id) {
1301
        },
1302

    
1303
        has_firewall: function() {
1304
            var nic = this.get_public_nic();
1305
            if (nic) {
1306
                var profile = nic.get('firewallProfile'); 
1307
                return ['ENABLED', 'PROTECTED'].indexOf(profile) > -1;
1308
            }
1309
            return false;
1310
        },
1311

    
1312
        get_firewall_profile: function() {
1313
            var nic = this.get_public_nic();
1314
            if (nic) {
1315
                return nic.get('firewallProfile');
1316
            }
1317
            return null;
1318
        },
1319

    
1320
        get_addresses: function() {
1321
            var pnic = this.get_public_nic();
1322
            if (!pnic) { return {'ip4': undefined, 'ip6': undefined }};
1323
            return {'ip4': pnic.get('ipv4'), 'ip6': pnic.get('ipv6')};
1324
        },
1325
    
1326
        // get actions that the user can execute
1327
        // depending on the vm state/status
1328
        get_available_actions: function() {
1329
            return models.VM.AVAILABLE_ACTIONS[this.state()];
1330
        },
1331

    
1332
        set_profile: function(profile, net_id) {
1333
        },
1334
        
1335
        // call rename api
1336
        rename: function(new_name) {
1337
            //this.set({'name': new_name});
1338
            this.sync("update", this, {
1339
                critical: true,
1340
                data: {
1341
                    'server': {
1342
                        'name': new_name
1343
                    }
1344
                }, 
1345
                // do the rename after the method succeeds
1346
                success: _.bind(function(){
1347
                    //this.set({name: new_name});
1348
                    snf.api.trigger("call");
1349
                }, this)
1350
            });
1351
        },
1352
        
1353
        get_console_url: function(data) {
1354
            var url_params = {
1355
                machine: this.get("name"),
1356
                host_ip: this.get_addresses().ip4,
1357
                host_ip_v6: this.get_addresses().ip6,
1358
                host: data.host,
1359
                port: data.port,
1360
                password: data.password
1361
            }
1362
            return '/machines/console?' + $.param(url_params);
1363
        },
1364

    
1365
        // action helper
1366
        call: function(action_name, success, error, params) {
1367
            var id_param = [this.id];
1368
            
1369
            params = params || {};
1370
            success = success || function() {};
1371
            error = error || function() {};
1372

    
1373
            var self = this;
1374

    
1375
            switch(action_name) {
1376
                case 'start':
1377
                    this.__make_api_call(this.get_action_url(), // vm actions url
1378
                                         "create", // create so that sync later uses POST to make the call
1379
                                         {start:{}}, // payload
1380
                                         function() {
1381
                                             // set state after successful call
1382
                                             self.state("START"); 
1383
                                             success.apply(this, arguments);
1384
                                             snf.api.trigger("call");
1385
                                         },  
1386
                                         error, 'start', params);
1387
                    break;
1388
                case 'reboot':
1389
                    this.__make_api_call(this.get_action_url(), // vm actions url
1390
                                         "create", // create so that sync later uses POST to make the call
1391
                                         {reboot:{type:"HARD"}}, // payload
1392
                                         function() {
1393
                                             // set state after successful call
1394
                                             self.state("REBOOT"); 
1395
                                             success.apply(this, arguments)
1396
                                             snf.api.trigger("call");
1397
                                             self.set({'reboot_required': false});
1398
                                         },
1399
                                         error, 'reboot', params);
1400
                    break;
1401
                case 'shutdown':
1402
                    this.__make_api_call(this.get_action_url(), // vm actions url
1403
                                         "create", // create so that sync later uses POST to make the call
1404
                                         {shutdown:{}}, // payload
1405
                                         function() {
1406
                                             // set state after successful call
1407
                                             self.state("SHUTDOWN"); 
1408
                                             success.apply(this, arguments)
1409
                                             snf.api.trigger("call");
1410
                                         },  
1411
                                         error, 'shutdown', params);
1412
                    break;
1413
                case 'console':
1414
                    this.__make_api_call(this.url() + "/action", "create", {'console': {'type':'vnc'}}, function(data) {
1415
                        var cons_data = data.console;
1416
                        success.apply(this, [cons_data]);
1417
                    }, undefined, 'console', params)
1418
                    break;
1419
                case 'destroy':
1420
                    this.__make_api_call(this.url(), // vm actions url
1421
                                         "delete", // create so that sync later uses POST to make the call
1422
                                         undefined, // payload
1423
                                         function() {
1424
                                             // set state after successful call
1425
                                             self.state('DESTROY');
1426
                                             success.apply(this, arguments)
1427
                                         },  
1428
                                         error, 'destroy', params);
1429
                    break;
1430
                default:
1431
                    throw "Invalid VM action ("+action_name+")";
1432
            }
1433
        },
1434
        
1435
        __make_api_call: function(url, method, data, success, error, action, extra_params) {
1436
            var self = this;
1437
            error = error || function(){};
1438
            success = success || function(){};
1439

    
1440
            var params = {
1441
                url: url,
1442
                data: data,
1443
                success: function(){ self.handle_action_succeed.apply(self, arguments); success.apply(this, arguments)},
1444
                error: function(){ self.handle_action_fail.apply(self, arguments); error.apply(this, arguments)},
1445
                error_params: { ns: "Machines actions", 
1446
                                title: "'" + this.get("name") + "'" + " " + action + " failed", 
1447
                                extra_details: { 'Machine ID': this.id, 'URL': url, 'Action': action || "undefined" },
1448
                                allow_reload: false
1449
                              },
1450
                display: false,
1451
                critical: false
1452
            }
1453
            _.extend(params, extra_params)
1454
            this.sync(method, this, params);
1455
        },
1456

    
1457
        handle_action_succeed: function() {
1458
            this.trigger("action:success", arguments);
1459
        },
1460
        
1461
        reset_action_error: function() {
1462
            this.action_error = false;
1463
            this.trigger("action:fail:reset", this.action_error);
1464
        },
1465

    
1466
        handle_action_fail: function() {
1467
            this.action_error = arguments;
1468
            this.trigger("action:fail", arguments);
1469
        },
1470

    
1471
        get_action_url: function(name) {
1472
            return this.url() + "/action";
1473
        },
1474

    
1475
        get_diagnostics_url: function() {
1476
            return this.url() + "/diagnostics";
1477
        },
1478

    
1479
        get_connection_info: function(host_os, success, error) {
1480
            var url = "/machines/connect";
1481
            params = {
1482
                ip_address: this.get_public_nic().get('ipv4'),
1483
                hostname: this.get_hostname(),
1484
                os: this.get_os(),
1485
                host_os: host_os,
1486
                srv: this.id
1487
            }
1488

    
1489
            url = url + "?" + $.param(params);
1490

    
1491
            var ajax = snf.api.sync("read", undefined, { url: url, 
1492
                                                         error:error, 
1493
                                                         success:success, 
1494
                                                         handles_error:1});
1495
        }
1496
    })
1497
    
1498
    models.VM.ACTIONS = [
1499
        'start',
1500
        'shutdown',
1501
        'reboot',
1502
        'console',
1503
        'destroy'
1504
    ]
1505

    
1506
    models.VM.AVAILABLE_ACTIONS = {
1507
        'UNKNWON'       : ['destroy'],
1508
        'BUILD'         : ['destroy'],
1509
        'REBOOT'        : ['shutdown', 'destroy', 'console'],
1510
        'STOPPED'       : ['start', 'destroy'],
1511
        'ACTIVE'        : ['shutdown', 'destroy', 'reboot', 'console'],
1512
        'ERROR'         : ['destroy'],
1513
        'DELETED'        : [],
1514
        'DESTROY'       : [],
1515
        'BUILD_INIT'    : ['destroy'],
1516
        'BUILD_COPY'    : ['destroy'],
1517
        'BUILD_FINAL'   : ['destroy'],
1518
        'SHUTDOWN'      : ['destroy'],
1519
        'START'         : [],
1520
        'CONNECT'       : [],
1521
        'DISCONNECT'    : []
1522
    }
1523

    
1524
    // api status values
1525
    models.VM.STATUSES = [
1526
        'UNKNWON',
1527
        'BUILD',
1528
        'REBOOT',
1529
        'STOPPED',
1530
        'ACTIVE',
1531
        'ERROR',
1532
        'DELETED'
1533
    ]
1534

    
1535
    // api status values
1536
    models.VM.CONNECT_STATES = [
1537
        'ACTIVE',
1538
        'REBOOT',
1539
        'SHUTDOWN'
1540
    ]
1541

    
1542
    // vm states
1543
    models.VM.STATES = models.VM.STATUSES.concat([
1544
        'DESTROY',
1545
        'BUILD_INIT',
1546
        'BUILD_COPY',
1547
        'BUILD_FINAL',
1548
        'SHUTDOWN',
1549
        'START',
1550
        'CONNECT',
1551
        'DISCONNECT',
1552
        'FIREWALL'
1553
    ]);
1554
    
1555
    models.VM.STATES_TRANSITIONS = {
1556
        'DESTROY' : ['DELETED'],
1557
        'SHUTDOWN': ['ERROR', 'STOPPED', 'DESTROY'],
1558
        'STOPPED': ['ERROR', 'ACTIVE', 'DESTROY'],
1559
        'ACTIVE': ['ERROR', 'STOPPED', 'REBOOT', 'SHUTDOWN', 'DESTROY'],
1560
        'START': ['ERROR', 'ACTIVE', 'DESTROY'],
1561
        'REBOOT': ['ERROR', 'ACTIVE', 'STOPPED', 'DESTROY'],
1562
        'BUILD': ['ERROR', 'ACTIVE', 'DESTROY'],
1563
        'BUILD_COPY': ['ERROR', 'ACTIVE', 'BUILD_FINAL', 'DESTROY'],
1564
        'BUILD_FINAL': ['ERROR', 'ACTIVE', 'DESTROY'],
1565
        'BUILD_INIT': ['ERROR', 'ACTIVE', 'BUILD_COPY', 'BUILD_FINAL', 'DESTROY']
1566
    }
1567

    
1568
    models.VM.TRANSITION_STATES = [
1569
        'DESTROY',
1570
        'SHUTDOWN',
1571
        'START',
1572
        'REBOOT',
1573
        'BUILD'
1574
    ]
1575

    
1576
    models.VM.ACTIVE_STATES = [
1577
        'BUILD', 'REBOOT', 'ACTIVE',
1578
        'BUILD_INIT', 'BUILD_COPY', 'BUILD_FINAL',
1579
        'SHUTDOWN', 'CONNECT', 'DISCONNECT'
1580
    ]
1581

    
1582
    models.VM.BUILDING_STATES = [
1583
        'BUILD', 'BUILD_INIT', 'BUILD_COPY', 'BUILD_FINAL'
1584
    ]
1585

    
1586
    models.Networks = models.Collection.extend({
1587
        model: models.Network,
1588
        path: 'networks',
1589
        details: true,
1590
        //noUpdate: true,
1591
        defaults: {'nics':[],'linked_to':[]},
1592
        
1593
        parse: function (resp, xhr) {
1594
            // FIXME: depricated global var
1595
            if (!resp) { return []};
1596
            var data = _.filter(_.map(resp.networks.values, _.bind(this.parse_net_api_data, this)),
1597
                               function(e){ return e });
1598
            return data;
1599
        },
1600

    
1601
        add: function() {
1602
            ret = models.Networks.__super__.add.apply(this, arguments);
1603
            // update nics after each network addition
1604
            ret.each(function(r){
1605
                synnefo.storage.nics.update_net_nics(r);
1606
            });
1607
        },
1608

    
1609
        reset_pending_actions: function() {
1610
            this.each(function(net) {
1611
                net.get("actions").reset();
1612
            });
1613
        },
1614

    
1615
        do_all_pending_actions: function() {
1616
            this.each(function(net) {
1617
                net.do_all_pending_actions();
1618
            })
1619
        },
1620

    
1621
        parse_net_api_data: function(data) {
1622
            // append nic metadata
1623
            // net.get('nics') contains a list of vm/index objects 
1624
            // e.g. {'vm_id':12231, 'index':1}
1625
            // net.get('linked_to') contains a list of vms the network is 
1626
            // connected to e.g. [1001, 1002]
1627
            if (data.attachments && data.attachments.values) {
1628
                data['nics'] = {};
1629
                data['linked_to'] = [];
1630
                _.each(data.attachments.values, function(nic_id){
1631
                  
1632
                  var vm_id = NIC_REGEX.exec(nic_id)[1];
1633
                  var nic_index = parseInt(NIC_REGEX.exec(nic_id)[2]);
1634

    
1635
                  if (vm_id !== undefined && nic_index !== undefined) {
1636
                      data['nics'][nic_id] = {
1637
                          'vm_id': vm_id, 
1638
                          'index': nic_index, 
1639
                          'id': nic_id
1640
                      };
1641
                      if (data['linked_to'].indexOf(vm_id) == -1) {
1642
                        data['linked_to'].push(vm_id);
1643
                      }
1644
                  }
1645
                });
1646
            }
1647

    
1648
            if (data.status == "DELETED" && !this.get(parseInt(data.id))) {
1649
              return false;
1650
            }
1651
            return data;
1652
        },
1653

    
1654
        create: function (name, type, cidr, dhcp, callback) {
1655
            var params = {
1656
                network:{
1657
                    name:name
1658
                }
1659
            };
1660

    
1661
            if (type) {
1662
                params.network.type = type;
1663
            }
1664
            if (cidr) {
1665
                params.network.cidr = cidr;
1666
            }
1667
            if (dhcp) {
1668
                params.network.dhcp = dhcp;
1669
            }
1670

    
1671
            if (dhcp === false) {
1672
                params.network.dhcp = false;
1673
            }
1674
            
1675
            return this.api_call(this.path, "create", params, callback);
1676
        },
1677

    
1678
        get_public: function(){
1679
          return this.filter(function(n){return n.get('public')});
1680
        }
1681
    })
1682

    
1683
    models.Images = models.Collection.extend({
1684
        model: models.Image,
1685
        path: 'images',
1686
        details: true,
1687
        noUpdate: true,
1688
        supportIncUpdates: false,
1689
        meta_keys_as_attrs: ["OS", "description", "kernel", "size", "GUI"],
1690
        meta_labels: {},
1691
        read_method: 'read',
1692

    
1693
        // update collection model with id passed
1694
        // making a direct call to the image
1695
        // api url
1696
        update_unknown_id: function(id, callback) {
1697
            var url = getUrl.call(this) + "/" + id;
1698
            this.api_call(this.path + "/" + id, this.read_method, {
1699
              _options:{
1700
                async:true, 
1701
                skip_api_error:true}
1702
              }, undefined, 
1703
            _.bind(function() {
1704
                if (!this.get(id)) {
1705
                            if (this.fallback_service) {
1706
                        // if current service has fallback_service attribute set
1707
                        // use this service to retrieve the missing image model
1708
                        var tmpservice = new this.fallback_service();
1709
                        tmpservice.update_unknown_id(id, _.bind(function(img){
1710
                            img.attributes.status = "DELETED";
1711
                            this.add(img.attributes);
1712
                            callback(this.get(id));
1713
                        }, this));
1714
                    } else {
1715
                        var title = synnefo.config.image_deleted_title || 'Deleted';
1716
                        // else add a dummy DELETED state image entry
1717
                        this.add({id:id, name:title, size:-1, 
1718
                                  progress:100, status:"DELETED"});
1719
                        callback(this.get(id));
1720
                    }   
1721
                } else {
1722
                    callback(this.get(id));
1723
                }
1724
            }, this), _.bind(function(image, msg, xhr) {
1725
                if (!image) {
1726
                    var title = synnefo.config.image_deleted_title || 'Deleted';
1727
                    this.add({id:id, name:title, size:-1, 
1728
                              progress:100, status:"DELETED"});
1729
                    callback(this.get(id));
1730
                    return;
1731
                }
1732
                var img_data = this._read_image_from_request(image, msg, xhr);
1733
                this.add(img_data);
1734
                callback(this.get(id));
1735
            }, this));
1736
        },
1737

    
1738
        _read_image_from_request: function(image, msg, xhr) {
1739
            return image.image;
1740
        },
1741

    
1742
        parse: function (resp, xhr) {
1743
            var data = _.map(resp.images.values, _.bind(this.parse_meta, this));
1744
            return resp.images.values;
1745
        },
1746

    
1747
        get_meta_key: function(img, key) {
1748
            if (img.metadata && img.metadata.values && img.metadata.values[key]) {
1749
                return _.escape(img.metadata.values[key]);
1750
            }
1751
            return undefined;
1752
        },
1753

    
1754
        comparator: function(img) {
1755
            return -img.get_sort_order("sortorder") || 1000 * img.id;
1756
        },
1757

    
1758
        parse_meta: function(img) {
1759
            _.each(this.meta_keys_as_attrs, _.bind(function(key){
1760
                if (img[key]) { return };
1761
                img[key] = this.get_meta_key(img, key) || "";
1762
            }, this));
1763
            return img;
1764
        },
1765

    
1766
        active: function() {
1767
            return this.filter(function(img){return img.get('status') != "DELETED"});
1768
        },
1769

    
1770
        predefined: function() {
1771
            return _.filter(this.active(), function(i) { return !i.get("serverRef")});
1772
        },
1773
        
1774
        fetch_for_type: function(type, complete, error) {
1775
            this.fetch({update:true, 
1776
                        success: complete, 
1777
                        error: error, 
1778
                        skip_api_error: true });
1779
        },
1780
        
1781
        get_images_for_type: function(type) {
1782
            if (this['get_{0}_images'.format(type)]) {
1783
                return this['get_{0}_images'.format(type)]();
1784
            }
1785

    
1786
            return this.active();
1787
        },
1788

    
1789
        update_images_for_type: function(type, onStart, onComplete, onError, force_load) {
1790
            var load = false;
1791
            error = onError || function() {};
1792
            function complete(collection) { 
1793
                onComplete(collection.get_images_for_type(type)); 
1794
            }
1795
            
1796
            // do we need to fetch/update current collection entries
1797
            if (load) {
1798
                onStart();
1799
                this.fetch_for_type(type, complete, error);
1800
            } else {
1801
                // fallback to complete
1802
                complete(this);
1803
            }
1804
        }
1805
    })
1806

    
1807
    models.Flavors = models.Collection.extend({
1808
        model: models.Flavor,
1809
        path: 'flavors',
1810
        details: true,
1811
        noUpdate: true,
1812
        supportIncUpdates: false,
1813
        // update collection model with id passed
1814
        // making a direct call to the flavor
1815
        // api url
1816
        update_unknown_id: function(id, callback) {
1817
            var url = getUrl.call(this) + "/" + id;
1818
            this.api_call(this.path + "/" + id, "read", {_options:{async:false, skip_api_error:true}}, undefined, 
1819
            _.bind(function() {
1820
                this.add({id:id, cpu:"Unknown", ram:"Unknown", disk:"Unknown", name: "Unknown", status:"DELETED"})
1821
            }, this), _.bind(function(flv) {
1822
                if (!flv.flavor.status) { flv.flavor.status = "DELETED" };
1823
                this.add(flv.flavor);
1824
            }, this));
1825
        },
1826

    
1827
        parse: function (resp, xhr) {
1828
            return _.map(resp.flavors.values, function(o) { o.disk_template = o['SNF:disk_template']; return o});
1829
        },
1830

    
1831
        comparator: function(flv) {
1832
            return flv.get("disk") * flv.get("cpu") * flv.get("ram");
1833
        },
1834

    
1835
        unavailable_values_for_image: function(img, flavors) {
1836
            var flavors = flavors || this.active();
1837
            var size = img.get_size();
1838
            
1839
            var index = {cpu:[], disk:[], ram:[]};
1840

    
1841
            _.each(this.active(), function(el) {
1842
                var img_size = size;
1843
                var flv_size = el.get_disk_size();
1844
                if (flv_size < img_size) {
1845
                    if (index.disk.indexOf(flv_size) == -1) {
1846
                        index.disk.push(flv_size);
1847
                    }
1848
                };
1849
            });
1850
            
1851
            return index;
1852
        },
1853

    
1854
        get_flavor: function(cpu, mem, disk, disk_template, filter_list) {
1855
            if (!filter_list) { filter_list = this.models };
1856
            
1857
            return this.select(function(flv){
1858
                if (flv.get("cpu") == cpu + "" &&
1859
                   flv.get("ram") == mem + "" &&
1860
                   flv.get("disk") == disk + "" &&
1861
                   flv.get("disk_template") == disk_template &&
1862
                   filter_list.indexOf(flv) > -1) { return true; }
1863
            })[0];
1864
        },
1865
        
1866
        get_data: function(lst) {
1867
            var data = {'cpu': [], 'mem':[], 'disk':[]};
1868

    
1869
            _.each(lst, function(flv) {
1870
                if (data.cpu.indexOf(flv.get("cpu")) == -1) {
1871
                    data.cpu.push(flv.get("cpu"));
1872
                }
1873
                if (data.mem.indexOf(flv.get("ram")) == -1) {
1874
                    data.mem.push(flv.get("ram"));
1875
                }
1876
                if (data.disk.indexOf(flv.get("disk")) == -1) {
1877
                    data.disk.push(flv.get("disk"));
1878
                }
1879
            })
1880
            
1881
            return data;
1882
        },
1883

    
1884
        active: function() {
1885
            return this.filter(function(flv){return flv.get('status') != "DELETED"});
1886
        }
1887
            
1888
    })
1889

    
1890
    models.VMS = models.Collection.extend({
1891
        model: models.VM,
1892
        path: 'servers',
1893
        details: true,
1894
        copy_image_meta: true,
1895

    
1896
        parse: function (resp, xhr) {
1897
            var data = resp;
1898
            if (!resp) { return [] };
1899
            data = _.filter(_.map(resp.servers.values, _.bind(this.parse_vm_api_data, this)), function(v){return v});
1900
            return data;
1901
        },
1902

    
1903
        parse_vm_api_data: function(data) {
1904
            // do not add non existing DELETED entries
1905
            if (data.status && data.status == "DELETED") {
1906
                if (!this.get(data.id)) {
1907
                    return false;
1908
                }
1909
            }
1910

    
1911
            // OS attribute
1912
            if (this.has_meta(data)) {
1913
                data['OS'] = data.metadata.values.OS || "okeanos";
1914
            }
1915
            
1916
            if (!data.diagnostics) {
1917
                data.diagnostics = [];
1918
            }
1919

    
1920
            // network metadata
1921
            data['firewalls'] = {};
1922
            data['nics'] = {};
1923
            data['linked_to'] = [];
1924

    
1925
            if (data['attachments'] && data['attachments'].values) {
1926
                var nics = data['attachments'].values;
1927
                _.each(nics, function(nic) {
1928
                    var net_id = nic.network_id;
1929
                    var index = parseInt(NIC_REGEX.exec(nic.id)[2]);
1930
                    if (data['linked_to'].indexOf(net_id) == -1) {
1931
                        data['linked_to'].push(net_id);
1932
                    }
1933

    
1934
                    data['nics'][nic.id] = nic;
1935
                })
1936
            }
1937
            
1938
            // if vm has no metadata, no metadata object
1939
            // is in json response, reset it to force
1940
            // value update
1941
            if (!data['metadata']) {
1942
                data['metadata'] = {values:{}};
1943
            }
1944

    
1945
            return data;
1946
        },
1947

    
1948
        add: function() {
1949
            ret = models.VMS.__super__.add.apply(this, arguments);
1950
            ret.each(function(r){
1951
                synnefo.storage.nics.update_vm_nics(r);
1952
            });
1953
        },
1954
        
1955
        get_reboot_required: function() {
1956
            return this.filter(function(vm){return vm.get("reboot_required") == true})
1957
        },
1958

    
1959
        has_pending_actions: function() {
1960
            return this.filter(function(vm){return vm.pending_action}).length > 0;
1961
        },
1962

    
1963
        reset_pending_actions: function() {
1964
            this.each(function(vm) {
1965
                vm.clear_pending_action();
1966
            })
1967
        },
1968

    
1969
        do_all_pending_actions: function(success, error) {
1970
            this.each(function(vm) {
1971
                if (vm.has_pending_action()) {
1972
                    vm.call(vm.pending_action, success, error);
1973
                    vm.clear_pending_action();
1974
                }
1975
            })
1976
        },
1977
        
1978
        do_all_reboots: function(success, error) {
1979
            this.each(function(vm) {
1980
                if (vm.get("reboot_required")) {
1981
                    vm.call("reboot", success, error);
1982
                }
1983
            });
1984
        },
1985

    
1986
        reset_reboot_required: function() {
1987
            this.each(function(vm) {
1988
                vm.set({'reboot_required': undefined});
1989
            })
1990
        },
1991
        
1992
        stop_stats_update: function(exclude) {
1993
            var exclude = exclude || [];
1994
            this.each(function(vm) {
1995
                if (exclude.indexOf(vm) > -1) {
1996
                    return;
1997
                }
1998
                vm.stop_stats_update();
1999
            })
2000
        },
2001
        
2002
        has_meta: function(vm_data) {
2003
            return vm_data.metadata && vm_data.metadata.values
2004
        },
2005

    
2006
        has_addresses: function(vm_data) {
2007
            return vm_data.metadata && vm_data.metadata.values
2008
        },
2009

    
2010
        create: function (name, image, flavor, meta, extra, callback) {
2011

    
2012
            if (this.copy_image_meta) {
2013
                if (synnefo.config.vm_image_common_metadata) {
2014
                    _.each(synnefo.config.vm_image_common_metadata, 
2015
                        function(key){
2016
                            if (image.get_meta(key)) {
2017
                                meta[key] = image.get_meta(key);
2018
                            }
2019
                    });
2020
                }
2021

    
2022
                if (image.get("OS")) {
2023
                    meta['OS'] = image.get("OS");
2024
                }
2025
            }
2026
            
2027
            opts = {name: name, imageRef: image.id, flavorRef: flavor.id, metadata:meta}
2028
            opts = _.extend(opts, extra);
2029

    
2030
            this.api_call(this.path, "create", {'server': opts}, undefined, undefined, callback, {critical: true});
2031
        }
2032

    
2033
    })
2034
    
2035
    models.NIC = models.Model.extend({
2036
        
2037
        initialize: function() {
2038
            models.NIC.__super__.initialize.apply(this, arguments);
2039
            this.pending_for_firewall = false;
2040
            this.bind("change:firewallProfile", _.bind(this.check_firewall, this));
2041
            this.bind("change:pending_firewall", function(nic) {
2042
                nic.get_network().update_state();
2043
            });
2044
            this.get_vm().bind("remove", function(){
2045
                try {
2046
                    this.collection.remove(this);
2047
                } catch (err) {};
2048
            }, this);
2049
            this.get_network().bind("remove", function(){
2050
                try {
2051
                    this.collection.remove(this);
2052
                } catch (err) {};
2053
            }, this);
2054

    
2055
        },
2056

    
2057
        get_vm: function() {
2058
            return synnefo.storage.vms.get(parseInt(this.get('vm_id')));
2059
        },
2060

    
2061
        get_network: function() {
2062
            return synnefo.storage.networks.get(this.get('network_id'));
2063
        },
2064

    
2065
        get_v6_address: function() {
2066
            return this.get("ipv6");
2067
        },
2068

    
2069
        get_v4_address: function() {
2070
            return this.get("ipv4");
2071
        },
2072

    
2073
        set_firewall: function(value, callback, error, options) {
2074
            var net_id = this.get('network_id');
2075
            var self = this;
2076

    
2077
            // api call data
2078
            var payload = {"firewallProfile":{"profile":value}};
2079
            payload._options = _.extend({critical: false}, options);
2080
            
2081
            this.set({'pending_firewall': value});
2082
            this.set({'pending_firewall_sending': true});
2083
            this.set({'pending_firewall_from': this.get('firewallProfile')});
2084

    
2085
            var success_cb = function() {
2086
                if (callback) {
2087
                    callback();
2088
                }
2089
                self.set({'pending_firewall_sending': false});
2090
            };
2091

    
2092
            var error_cb = function() {
2093
                self.reset_pending_firewall();
2094
            }
2095
            
2096
            this.get_vm().api_call(this.get_vm().api_path() + "/action", "create", payload, success_cb, error_cb);
2097
        },
2098

    
2099
        reset_pending_firewall: function() {
2100
            this.set({'pending_firewall': false});
2101
            this.set({'pending_firewall': false});
2102
        },
2103

    
2104
        check_firewall: function() {
2105
            var firewall = this.get('firewallProfile');
2106
            var pending = this.get('pending_firewall');
2107
            var previous = this.get('pending_firewall_from');
2108
            if (previous != firewall) { this.get_vm().require_reboot() };
2109
            this.reset_pending_firewall();
2110
        }
2111
        
2112
    });
2113

    
2114
    models.NICs = models.Collection.extend({
2115
        model: models.NIC,
2116
        
2117
        add_or_update: function(nic_id, data, vm) {
2118
            var params = _.clone(data);
2119
            var vm;
2120
            params.attachment_id = params.id;
2121
            params.id = params.id + '-' + params.network_id;
2122
            params.vm_id = parseInt(NIC_REGEX.exec(nic_id)[1]);
2123

    
2124
            if (!this.get(params.id)) {
2125
                this.add(params);
2126
                var nic = this.get(params.id);
2127
                vm = nic.get_vm();
2128
                nic.get_network().decrease_connecting();
2129
                nic.bind("remove", function() {
2130
                    nic.set({"removing": 0});
2131
                    if (this.get_network()) {
2132
                        // network might got removed before nic
2133
                        nic.get_network().update_state();
2134
                    }
2135
                });
2136

    
2137
            } else {
2138
                this.get(params.id).set(params);
2139
                vm = this.get(params.id).get_vm();
2140
            }
2141
            
2142
            // vm nics changed, trigger vm update
2143
            if (vm) { vm.trigger("change", vm)};
2144
        },
2145
        
2146
        reset_nics: function(nics, filter_attr, filter_val) {
2147
            var nics_to_check = this.filter(function(nic) {
2148
                return nic.get(filter_attr) == filter_val;
2149
            });
2150
            
2151
            _.each(nics_to_check, function(nic) {
2152
                if (nics.indexOf(nic.get('id')) == -1) {
2153
                    this.remove(nic);
2154
                } else {
2155
                }
2156
            }, this);
2157
        },
2158

    
2159
        update_vm_nics: function(vm) {
2160
            var nics = vm.get('nics');
2161
            this.reset_nics(_.map(nics, function(nic, key){
2162
                return key + "-" + nic.network_id;
2163
            }), 'vm_id', vm.id);
2164

    
2165
            _.each(nics, function(val, key) {
2166
                var net = synnefo.storage.networks.get(val.network_id);
2167
                if (net && net.connected_with_nic_id(key) && vm.connected_with_nic_id(key)) {
2168
                    this.add_or_update(key, vm.get('nics')[key], vm);
2169
                }
2170
            }, this);
2171
        },
2172

    
2173
        update_net_nics: function(net) {
2174
            var nics = net.get('nics');
2175
            this.reset_nics(_.map(nics, function(nic, key){
2176
                return key + "-" + net.get('id');
2177
            }), 'network_id', net.id);
2178

    
2179
            _.each(nics, function(val, key) {
2180
                var vm = synnefo.storage.vms.get(val.vm_id);
2181
                if (vm && net.connected_with_nic_id(key) && vm.connected_with_nic_id(key)) {
2182
                    this.add_or_update(key, vm.get('nics')[key], vm);
2183
                }
2184
            }, this);
2185
        }
2186
    });
2187

    
2188
    models.PublicKey = models.Model.extend({
2189
        path: 'keys',
2190
        base_url: '/ui/userdata',
2191
        details: false,
2192
        noUpdate: true,
2193

    
2194

    
2195
        get_public_key: function() {
2196
            return cryptico.publicKeyFromString(this.get("content"));
2197
        },
2198

    
2199
        get_filename: function() {
2200
            return "{0}.pub".format(this.get("name"));
2201
        },
2202

    
2203
        identify_type: function() {
2204
            try {
2205
                var cont = snf.util.validatePublicKey(this.get("content"));
2206
                var type = cont.split(" ")[0];
2207
                return synnefo.util.publicKeyTypesMap[type];
2208
            } catch (err) { return false };
2209
        }
2210

    
2211
    })
2212
    
2213
    models.PublicKeys = models.Collection.extend({
2214
        model: models.PublicKey,
2215
        details: false,
2216
        path: 'keys',
2217
        base_url: '/ui/userdata',
2218
        noUpdate: true,
2219

    
2220
        generate_new: function(success, error) {
2221
            snf.api.sync('create', undefined, {
2222
                url: getUrl.call(this, this.base_url) + "/generate", 
2223
                success: success, 
2224
                error: error,
2225
                skip_api_error: true
2226
            });
2227
        },
2228

    
2229
        add_crypto_key: function(key, success, error, options) {
2230
            var options = options || {};
2231
            var m = new models.PublicKey();
2232

    
2233
            // guess a name
2234
            var name_tpl = "my generated public key";
2235
            var name = name_tpl;
2236
            var name_count = 1;
2237
            
2238
            while(this.filter(function(m){ return m.get("name") == name }).length > 0) {
2239
                name = name_tpl + " " + name_count;
2240
                name_count++;
2241
            }
2242
            
2243
            m.set({name: name});
2244
            m.set({content: key});
2245
            
2246
            options.success = function () { return success(m) };
2247
            options.errror = error;
2248
            options.skip_api_error = true;
2249
            
2250
            this.create(m.attributes, options);
2251
        }
2252
    })
2253
    
2254
    // storage initialization
2255
    snf.storage.images = new models.Images();
2256
    snf.storage.flavors = new models.Flavors();
2257
    snf.storage.networks = new models.Networks();
2258
    snf.storage.vms = new models.VMS();
2259
    snf.storage.keys = new models.PublicKeys();
2260
    snf.storage.nics = new models.NICs();
2261

    
2262
    //snf.storage.vms.fetch({update:true});
2263
    //snf.storage.images.fetch({update:true});
2264
    //snf.storage.flavors.fetch({update:true});
2265

    
2266
})(this);