Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (75.2 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
            return resp.server;
117
        },
118

    
119
        remove: function() {
120
            this.api_call(this.api_path(), "delete");
121
        },
122

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
265
        display_owner: function() {
266
            var owner = this.get_owner();
267
            if (_.include(_.keys(synnefo.config.system_images_owners), owner)) {
268
                return synnefo.config.system_images_owners[owner];
269
            } else {
270
                return owner;
271
            }
272
        },
273
    
274
        get_readable_size: function() {
275
            if (this.is_deleted()) {
276
                return synnefo.config.image_deleted_size_title || '(none)';
277
            }
278
            return this.get_size() > 0 ? util.readablizeBytes(this.get_size() * 1024 * 1024) : '(none)';
279
        },
280

    
281
        get_os: function() {
282
            return this.get_meta('OS');
283
        },
284

    
285
        get_gui: function() {
286
            return this.get_meta('GUI');
287
        },
288

    
289
        get_created_user: function() {
290
            return synnefo.config.os_created_users[this.get_os()] || "root";
291
        },
292

    
293
        get_sort_order: function() {
294
            return parseInt(this.get('metadata') ? this.get('metadata').values.sortorder : -1)
295
        },
296

    
297
        get_vm: function() {
298
            var vm_id = this.get("serverRef");
299
            var vm = undefined;
300
            vm = storage.vms.get(vm_id);
301
            return vm;
302
        },
303

    
304
        is_public: function() {
305
            return this.get('is_public') || true;
306
        },
307

    
308
        is_deleted: function() {
309
            return this.get('status') == "DELETED"
310
        },
311
        
312
        ssh_keys_path: function() {
313
            prepend = '';
314
            if (this.get_created_user() != 'root') {
315
                prepend = '/home'
316
            }
317
            return '{1}/{0}/.ssh/authorized_keys'.format(this.get_created_user(), prepend);
318
        },
319

    
320
        _supports_ssh: function() {
321
            if (synnefo.config.support_ssh_os_list.indexOf(this.get_os()) > -1) {
322
                return true;
323
            }
324
            return false;
325
        },
326

    
327
        supports: function(feature) {
328
            if (feature == "ssh") {
329
                return this._supports_ssh()
330
            }
331
            return false;
332
        },
333

    
334
        personality_data_for_keys: function(keys) {
335
            contents = '';
336
            _.each(keys, function(key){
337
                contents = contents + key.get("content") + "\n"
338
            });
339
            contents = $.base64.encode(contents);
340

    
341
            return {
342
                path: this.ssh_keys_path(),
343
                contents: contents
344
            }
345
        }
346
    });
347

    
348
    // Flavor model
349
    models.Flavor = models.Model.extend({
350
        path: 'flavors',
351

    
352
        details_string: function() {
353
            return "{0} CPU, {1}MB, {2}GB".format(this.get('cpu'), this.get('ram'), this.get('disk'));
354
        },
355

    
356
        get_disk_size: function() {
357
            return parseInt(this.get("disk") * 1000)
358
        },
359

    
360
        get_disk_template_info: function() {
361
            var info = snf.config.flavors_disk_templates_info[this.get("disk_template")];
362
            if (!info) {
363
                info = { name: this.get("disk_template"), description:'' };
364
            }
365
            return info
366
        }
367

    
368
    });
369
    
370
    models.ParamsList = function(){this.initialize.apply(this, arguments)};
371
    _.extend(models.ParamsList.prototype, bb.Events, {
372

    
373
        initialize: function(parent, param_name) {
374
            this.parent = parent;
375
            this.actions = {};
376
            this.param_name = param_name;
377
            this.length = 0;
378
        },
379
        
380
        has_action: function(action) {
381
            return this.actions[action] ? true : false;
382
        },
383
            
384
        _parse_params: function(arguments) {
385
            if (arguments.length <= 1) {
386
                return [];
387
            }
388

    
389
            var args = _.toArray(arguments);
390
            return args.splice(1);
391
        },
392

    
393
        contains: function(action, params) {
394
            params = this._parse_params(arguments);
395
            var has_action = this.has_action(action);
396
            if (!has_action) { return false };
397

    
398
            var paramsEqual = false;
399
            _.each(this.actions[action], function(action_params) {
400
                if (_.isEqual(action_params, params)) {
401
                    paramsEqual = true;
402
                }
403
            });
404
                
405
            return paramsEqual;
406
        },
407
        
408
        is_empty: function() {
409
            return _.isEmpty(this.actions);
410
        },
411

    
412
        add: function(action, params) {
413
            params = this._parse_params(arguments);
414
            if (this.contains.apply(this, arguments)) { return this };
415
            var isnew = false
416
            if (!this.has_action(action)) {
417
                this.actions[action] = [];
418
                isnew = true;
419
            };
420

    
421
            this.actions[action].push(params);
422
            this.parent.trigger("change:" + this.param_name, this.parent, this);
423
            if (isnew) {
424
                this.trigger("add", action, params);
425
            } else {
426
                this.trigger("change", action, params);
427
            }
428
            return this;
429
        },
430
        
431
        remove_all: function(action) {
432
            if (this.has_action(action)) {
433
                delete this.actions[action];
434
                this.parent.trigger("change:" + this.param_name, this.parent, this);
435
                this.trigger("remove", action);
436
            }
437
            return this;
438
        },
439

    
440
        reset: function() {
441
            this.actions = {};
442
            this.parent.trigger("change:" + this.param_name, this.parent, this);
443
            this.trigger("reset");
444
            this.trigger("remove");
445
        },
446

    
447
        remove: function(action, params) {
448
            params = this._parse_params(arguments);
449
            if (!this.has_action(action)) { return this };
450
            var index = -1;
451
            _.each(this.actions[action], _.bind(function(action_params) {
452
                if (_.isEqual(action_params, params)) {
453
                    index = this.actions[action].indexOf(action_params);
454
                }
455
            }, this));
456
            
457
            if (index > -1) {
458
                this.actions[action].splice(index, 1);
459
                if (_.isEmpty(this.actions[action])) {
460
                    delete this.actions[action];
461
                }
462
                this.parent.trigger("change:" + this.param_name, this.parent, this);
463
                this.trigger("remove", action, params);
464
            }
465
        }
466

    
467
    });
468

    
469
    // Image model
470
    models.Network = models.Model.extend({
471
        path: 'networks',
472
        has_status: true,
473
        defaults: {'connecting':0},
474
        
475
        initialize: function() {
476
            var ret = models.Network.__super__.initialize.apply(this, arguments);
477
            this.set({"actions": new models.ParamsList(this, "actions")});
478
            this.update_state();
479
            this.bind("change:nics", _.bind(synnefo.storage.nics.update_net_nics, synnefo.storage.nics));
480
            this.bind("change:status", _.bind(this.update_state, this));
481
            return ret;
482
        },
483

    
484
        toJSON: function() {
485
            var attrs = _.clone(this.attributes);
486
            attrs.actions = _.clone(this.get("actions").actions);
487
            return attrs;
488
        },
489
        
490
        set_state: function(val) {
491
            if (val == "PENDING" && this.get("state") == "DESTORY") {
492
                return "DESTROY";
493
            }
494
            return val;
495
        },
496

    
497
        update_state: function() {
498
            if (this.get("connecting") > 0) {
499
                this.set({state: "CONNECTING"});
500
                return
501
            }
502
            
503
            if (this.get_nics(function(nic){ return nic.get("removing") == 1}).length > 0) {
504
                this.set({state: "DISCONNECTING"});
505
                return
506
            }   
507
            
508
            if (this.contains_firewalling_nics() > 0) {
509
                this.set({state: "FIREWALLING"});
510
                return
511
            }   
512
            
513
            if (this.get("state") == "DESTROY") { 
514
                this.set({"destroyed":1});
515
            }
516
            
517
            this.set({state:this.get('status')});
518
        },
519

    
520
        is_public: function() {
521
            return this.get("public");
522
        },
523

    
524
        decrease_connecting: function() {
525
            var conn = this.get("connecting");
526
            if (!conn) { conn = 0 };
527
            if (conn > 0) {
528
                conn--;
529
            }
530
            this.set({"connecting": conn});
531
            this.update_state();
532
        },
533

    
534
        increase_connecting: function() {
535
            var conn = this.get("connecting");
536
            if (!conn) { conn = 0 };
537
            conn++;
538
            this.set({"connecting": conn});
539
            this.update_state();
540
        },
541

    
542
        connected_to: function(vm) {
543
            return this.get('linked_to').indexOf(""+vm.id) > -1;
544
        },
545

    
546
        connected_with_nic_id: function(nic_id) {
547
            return _.keys(this.get('nics')).indexOf(nic_id) > -1;
548
        },
549

    
550
        get_nics: function(filter) {
551
            var nics = synnefo.storage.nics.filter(function(nic) {
552
                return nic.get('network_id') == this.id;
553
            }, this);
554

    
555
            if (filter) {
556
                return _.filter(nics, filter);
557
            }
558
            return nics;
559
        },
560

    
561
        contains_firewalling_nics: function() {
562
            return this.get_nics(function(n){return n.get('pending_firewall')}).length
563
        },
564

    
565
        call: function(action, params, success, error) {
566
            if (action == "destroy") {
567
                this.set({state:"DESTROY"});
568
                this.get("actions").remove("destroy", params);
569
                this.remove(_.bind(function(){
570
                    success();
571
                }, this), error);
572
            }
573
            
574
            if (action == "disconnect") {
575
                if (this.get("state") == "DESTROY") {
576
                    return;
577
                }
578

    
579
                _.each(params, _.bind(function(nic_id) {
580
                    var nic = snf.storage.nics.get(nic_id);
581
                    this.get("actions").remove("disconnect", nic_id);
582
                    if (nic) {
583
                        this.remove_nic(nic, success, error);
584
                    }
585
                }, this));
586
            }
587
        },
588

    
589
        add_vm: function (vm, callback, error, options) {
590
            var payload = {add:{serverRef:"" + vm.id}};
591
            payload._options = options || {};
592
            return this.api_call(this.api_path() + "/action", "create", 
593
                                 payload,
594
                                 _.bind(function(){
595
                                     //this.vms.add_pending(vm.id);
596
                                     this.increase_connecting();
597
                                     if (callback) {callback()}
598
                                 },this), error);
599
        },
600

    
601
        remove_nic: function (nic, callback, error, options) {
602
            var payload = {remove:{attachment:"" + nic.get("attachment_id")}};
603
            payload._options = options || {};
604
            return this.api_call(this.api_path() + "/action", "create", 
605
                                 payload,
606
                                 _.bind(function(){
607
                                     nic.set({"removing": 1});
608
                                     nic.get_network().update_state();
609
                                     //this.vms.add_pending_for_remove(vm.id);
610
                                     if (callback) {callback()}
611
                                 },this), error);
612
        },
613

    
614
        rename: function(name, callback) {
615
            return this.api_call(this.api_path(), "update", {
616
                network:{name:name}, 
617
                _options:{
618
                    critical: false, 
619
                    error_params:{
620
                        title: "Network action failed",
621
                        ns: "Networks",
622
                        extra_details: {"Network id": this.id}
623
                    }
624
                }}, callback);
625
        },
626

    
627
        get_connectable_vms: function() {
628
            return storage.vms.filter(function(vm){
629
                return !vm.in_error_state() && !vm.is_building();
630
            })
631
        },
632

    
633
        state_message: function() {
634
            if (this.get("state") == "ACTIVE" && !this.is_public()) {
635
                if (this.get("cidr") && this.get("dhcp") == true) {
636
                    return this.get("cidr");
637
                } else {
638
                    return "Private network";
639
                }
640
            }
641
            if (this.get("state") == "ACTIVE" && this.is_public()) {
642
                  return "Public network";
643
            }
644

    
645
            return models.Network.STATES[this.get("state")];
646
        },
647

    
648
        in_progress: function() {
649
            return models.Network.STATES_TRANSITIONS[this.get("state")] != undefined;
650
        },
651

    
652
        do_all_pending_actions: function(success, error) {
653
            var destroy = this.get("actions").has_action("destroy");
654
            _.each(this.get("actions").actions, _.bind(function(params, action) {
655
                _.each(params, _.bind(function(with_params) {
656
                    this.call(action, with_params, success, error);
657
                }, this));
658
            }, this));
659
            this.get("actions").reset();
660
        }
661
    });
662
    
663
    models.Network.STATES = {
664
        'ACTIVE': 'Private network',
665
        'CONNECTING': 'Connecting...',
666
        'DISCONNECTING': 'Disconnecting...',
667
        'FIREWALLING': 'Firewall update...',
668
        'DESTROY': 'Destroying...',
669
        'PENDING': 'Pending...',
670
        'ERROR': 'Error'
671
    }
672

    
673
    models.Network.STATES_TRANSITIONS = {
674
        'CONNECTING': ['ACTIVE'],
675
        'DISCONNECTING': ['ACTIVE'],
676
        'PENDING': ['ACTIVE'],
677
        'FIREWALLING': ['ACTIVE']
678
    }
679

    
680
    // Virtualmachine model
681
    models.VM = models.Model.extend({
682

    
683
        path: 'servers',
684
        has_status: true,
685
        initialize: function(params) {
686
            
687
            this.pending_firewalls = {};
688
            
689
            models.VM.__super__.initialize.apply(this, arguments);
690

    
691
            this.set({state: params.status || "ERROR"});
692
            this.log = new snf.logging.logger("VM " + this.id);
693
            this.pending_action = undefined;
694
            
695
            // init stats parameter
696
            this.set({'stats': undefined}, {silent: true});
697
            // defaults to not update the stats
698
            // each view should handle this vm attribute 
699
            // depending on if it displays stat images or not
700
            this.do_update_stats = false;
701
            
702
            // interval time
703
            // this will dynamicaly change if the server responds that
704
            // images get refreshed on different intervals
705
            this.stats_update_interval = synnefo.config.STATS_INTERVAL || 5000;
706
            this.stats_available = false;
707

    
708
            // initialize interval
709
            this.init_stats_intervals(this.stats_update_interval);
710
            
711
            // handle progress message on instance change
712
            this.bind("change", _.bind(this.update_status_message, this));
713
            // force update of progress message
714
            this.update_status_message(true);
715
            
716
            // default values
717
            this.bind("change:state", _.bind(function(){
718
                if (this.state() == "DESTROY") { 
719
                    this.handle_destroy() 
720
                }
721
            }, this));
722

    
723
            this.bind("change:nics", _.bind(synnefo.storage.nics.update_vm_nics, synnefo.storage.nics));
724
        },
725

    
726
        status: function(st) {
727
            if (!st) { return this.get("status")}
728
            return this.set({status:st});
729
        },
730

    
731
        set_status: function(st) {
732
            var new_state = this.state_for_api_status(st);
733
            var transition = false;
734

    
735
            if (this.state() != new_state) {
736
                if (models.VM.STATES_TRANSITIONS[this.state()]) {
737
                    transition = this.state();
738
                }
739
            }
740
            
741
            // call it silently to avoid double change trigger
742
            this.set({'state': this.state_for_api_status(st)}, {silent: true});
743
            
744
            // trigger transition
745
            if (transition && models.VM.TRANSITION_STATES.indexOf(new_state) == -1) { 
746
                this.trigger("transition", {from:transition, to:new_state}) 
747
            };
748
            return st;
749
        },
750
            
751
        get_diagnostics: function(success) {
752
            this.__make_api_call(this.get_diagnostics_url(),
753
                                 "read", // create so that sync later uses POST to make the call
754
                                 null, // payload
755
                                 function(data) {
756
                                     success(data);
757
                                 },  
758
                                 null, 'diagnostics');
759
        },
760

    
761
        has_diagnostics: function() {
762
            return this.get("diagnostics") && this.get("diagnostics").length;
763
        },
764

    
765
        get_progress_info: function() {
766
            // details about progress message
767
            // contains a list of diagnostic messages
768
            return this.get("status_messages");
769
        },
770

    
771
        get_status_message: function() {
772
            return this.get('status_message');
773
        },
774
        
775
        // extract status message from diagnostics
776
        status_message_from_diagnostics: function(diagnostics) {
777
            var valid_sources_map = synnefo.config.diagnostics_status_messages_map;
778
            var valid_sources = valid_sources_map[this.get('status')];
779
            if (!valid_sources) { return null };
780
            
781
            // filter messsages based on diagnostic source
782
            var messages = _.filter(diagnostics, function(diag) {
783
                return valid_sources.indexOf(diag.source) > -1;
784
            });
785

    
786
            var msg = messages[0];
787
            if (msg) {
788
              var message = msg.message;
789
              var message_tpl = snf.config.diagnostic_messages_tpls[msg.source];
790

    
791
              if (message_tpl) {
792
                  message = message_tpl.replace('MESSAGE', msg.message);
793
              }
794
              return message;
795
            }
796
            
797
            // no message to display, but vm in build state, display
798
            // finalizing message.
799
            if (this.is_building() == 'BUILD') {
800
                return synnefo.config.BUILDING_MESSAGES['FINAL'];
801
            }
802
            return null;
803
        },
804

    
805
        update_status_message: function(force) {
806
            // update only if one of the specified attributes has changed
807
            if (
808
              !this.keysChanged(['diagnostics', 'progress', 'status', 'state'])
809
                && !force
810
            ) { return };
811
            
812
            // if user requested to destroy the vm set the appropriate 
813
            // message.
814
            if (this.get('state') == "DESTROY") { 
815
                message = "Terminating..."
816
                this.set({status_message: message})
817
                return;
818
            }
819
            
820
            // set error message, if vm has diagnostic message display it as
821
            // progress message
822
            if (this.in_error_state()) {
823
                var d = this.get('diagnostics');
824
                if (d && d.length) {
825
                    var message = this.status_message_from_diagnostics(d);
826
                    this.set({status_message: message});
827
                } else {
828
                    this.set({status_message: null});
829
                }
830
                return;
831
            }
832
            
833
            // identify building status message
834
            if (this.is_building()) {
835
                var self = this;
836
                var success = function(msg) {
837
                    self.set({status_message: msg});
838
                }
839
                this.get_building_status_message(success);
840
                return;
841
            }
842

    
843
            this.set({status_message:null});
844
        },
845
            
846
        // get building status message. Asynchronous function since it requires
847
        // access to vm image.
848
        get_building_status_message: function(callback) {
849
            // no progress is set, vm is in initial build status
850
            var progress = this.get("progress");
851
            if (progress == 0 || !progress) {
852
                return callback(BUILDING_MESSAGES['INIT']);
853
            }
854
            
855
            // vm has copy progress, display copy percentage
856
            if (progress > 0 && progress <= 99) {
857
                this.get_copy_details(true, undefined, _.bind(
858
                    function(details){
859
                        callback(BUILDING_MESSAGES['COPY'].format(details.copy, 
860
                                                           details.size, 
861
                                                           details.progress));
862
                }, this));
863
                return;
864
            }
865

    
866
            // copy finished display FINAL message or identify status message
867
            // from diagnostics.
868
            if (progress >= 100) {
869
                if (!this.has_diagnostics()) {
870
                        callback(BUILDING_MESSAGES['FINAL']);
871
                } else {
872
                        var d = this.get("diagnostics");
873
                        var msg = this.status_message_from_diagnostics(d);
874
                        if (msg) {
875
                              callback(msg);
876
                        }
877
                }
878
            }
879
        },
880

    
881
        get_copy_details: function(human, image, callback) {
882
            var human = human || false;
883
            var image = image || this.get_image(_.bind(function(image){
884
                var progress = this.get('progress');
885
                var size = image.get_size();
886
                var size_copied = (size * progress / 100).toFixed(2);
887
                
888
                if (human) {
889
                    size = util.readablizeBytes(size*1024*1024);
890
                    size_copied = util.readablizeBytes(size_copied*1024*1024);
891
                }
892

    
893
                callback({'progress': progress, 'size': size, 'copy': size_copied})
894
            }, this));
895
        },
896

    
897
        start_stats_update: function(force_if_empty) {
898
            var prev_state = this.do_update_stats;
899

    
900
            this.do_update_stats = true;
901
            
902
            // fetcher initialized ??
903
            if (!this.stats_fetcher) {
904
                this.init_stats_intervals();
905
            }
906

    
907

    
908
            // fetcher running ???
909
            if (!this.stats_fetcher.running || !prev_state) {
910
                this.stats_fetcher.start();
911
            }
912

    
913
            if (force_if_empty && this.get("stats") == undefined) {
914
                this.update_stats(true);
915
            }
916
        },
917

    
918
        stop_stats_update: function(stop_calls) {
919
            this.do_update_stats = false;
920

    
921
            if (stop_calls) {
922
                this.stats_fetcher.stop();
923
            }
924
        },
925

    
926
        // clear and reinitialize update interval
927
        init_stats_intervals: function (interval) {
928
            this.stats_fetcher = this.get_stats_fetcher(this.stats_update_interval);
929
            this.stats_fetcher.start();
930
        },
931
        
932
        get_stats_fetcher: function(timeout) {
933
            var cb = _.bind(function(data){
934
                this.update_stats();
935
            }, this);
936
            var fetcher = new snf.api.updateHandler({'callback': cb, interval: timeout, id:'stats'});
937
            return fetcher;
938
        },
939

    
940
        // do the api call
941
        update_stats: function(force) {
942
            // do not update stats if flag not set
943
            if ((!this.do_update_stats && !force) || this.updating_stats) {
944
                return;
945
            }
946

    
947
            // make the api call, execute handle_stats_update on sucess
948
            // TODO: onError handler ???
949
            stats_url = this.url() + "/stats";
950
            this.updating_stats = true;
951
            this.sync("read", this, {
952
                handles_error:true, 
953
                url: stats_url, 
954
                refresh:true, 
955
                success: _.bind(this.handle_stats_update, this),
956
                error: _.bind(this.handle_stats_error, this),
957
                complete: _.bind(function(){this.updating_stats = false;}, this),
958
                critical: false,
959
                log_error: false,
960
                skips_timeouts: true
961
            });
962
        },
963

    
964
        get_stats_image: function(stat, type) {
965
        },
966
        
967
        _set_stats: function(stats) {
968
            var silent = silent === undefined ? false : silent;
969
            // unavailable stats while building
970
            if (this.get("status") == "BUILD") { 
971
                this.stats_available = false;
972
            } else { this.stats_available = true; }
973

    
974
            if (this.get("status") == "DESTROY") { this.stats_available = false; }
975
            
976
            this.set({stats: stats}, {silent:true});
977
            this.trigger("stats:update", stats);
978
        },
979

    
980
        unbind: function() {
981
            models.VM.__super__.unbind.apply(this, arguments);
982
        },
983

    
984
        handle_stats_error: function() {
985
            stats = {};
986
            _.each(['cpuBar', 'cpuTimeSeries', 'netBar', 'netTimeSeries'], function(k) {
987
                stats[k] = false;
988
            });
989

    
990
            this.set({'stats': stats});
991
        },
992

    
993
        // this method gets executed after a successful vm stats api call
994
        handle_stats_update: function(data) {
995
            var self = this;
996
            // avoid browser caching
997
            
998
            if (data.stats && _.size(data.stats) > 0) {
999
                var ts = $.now();
1000
                var stats = data.stats;
1001
                var images_loaded = 0;
1002
                var images = {};
1003

    
1004
                function check_images_loaded() {
1005
                    images_loaded++;
1006

    
1007
                    if (images_loaded == 4) {
1008
                        self._set_stats(images);
1009
                    }
1010
                }
1011
                _.each(['cpuBar', 'cpuTimeSeries', 'netBar', 'netTimeSeries'], function(k) {
1012
                    
1013
                    stats[k] = stats[k] + "?_=" + ts;
1014
                    
1015
                    var stat = k.slice(0,3);
1016
                    var type = k.slice(3,6) == "Bar" ? "bar" : "time";
1017
                    var img = $("<img />");
1018
                    var val = stats[k];
1019
                    
1020
                    // load stat image to a temporary dom element
1021
                    // update model stats on image load/error events
1022
                    img.load(function() {
1023
                        images[k] = val;
1024
                        check_images_loaded();
1025
                    });
1026

    
1027
                    img.error(function() {
1028
                        images[stat + type] = false;
1029
                        check_images_loaded();
1030
                    });
1031

    
1032
                    img.attr({'src': stats[k]});
1033
                })
1034
                data.stats = stats;
1035
            }
1036

    
1037
            // do we need to change the interval ??
1038
            if (data.stats.refresh * 1000 != this.stats_update_interval) {
1039
                this.stats_update_interval = data.stats.refresh * 1000;
1040
                this.stats_fetcher.interval = this.stats_update_interval;
1041
                this.stats_fetcher.maximum_interval = this.stats_update_interval;
1042
                this.stats_fetcher.stop();
1043
                this.stats_fetcher.start(false);
1044
            }
1045
        },
1046

    
1047
        // helper method that sets the do_update_stats
1048
        // in the future this method could also make an api call
1049
        // immediaetly if needed
1050
        enable_stats_update: function() {
1051
            this.do_update_stats = true;
1052
        },
1053
        
1054
        handle_destroy: function() {
1055
            this.stats_fetcher.stop();
1056
        },
1057

    
1058
        require_reboot: function() {
1059
            if (this.is_active()) {
1060
                this.set({'reboot_required': true});
1061
            }
1062
        },
1063
        
1064
        set_pending_action: function(data) {
1065
            this.pending_action = data;
1066
            return data;
1067
        },
1068

    
1069
        // machine has pending action
1070
        update_pending_action: function(action, force) {
1071
            this.set({pending_action: action});
1072
        },
1073

    
1074
        clear_pending_action: function() {
1075
            this.set({pending_action: undefined});
1076
        },
1077

    
1078
        has_pending_action: function() {
1079
            return this.get("pending_action") ? this.get("pending_action") : false;
1080
        },
1081
        
1082
        // machine is active
1083
        is_active: function() {
1084
            return models.VM.ACTIVE_STATES.indexOf(this.state()) > -1;
1085
        },
1086
        
1087
        // machine is building 
1088
        is_building: function() {
1089
            return models.VM.BUILDING_STATES.indexOf(this.state()) > -1;
1090
        },
1091
        
1092
        in_error_state: function() {
1093
            return this.state() === "ERROR"
1094
        },
1095

    
1096
        // user can connect to machine
1097
        is_connectable: function() {
1098
            // check if ips exist
1099
            if (!this.get_addresses().ip4 && !this.get_addresses().ip6) {
1100
                return false;
1101
            }
1102
            return models.VM.CONNECT_STATES.indexOf(this.state()) > -1;
1103
        },
1104
        
1105
        remove_meta: function(key, complete, error) {
1106
            var url = this.api_path() + "/meta/" + key;
1107
            this.api_call(url, "delete", undefined, complete, error);
1108
        },
1109

    
1110
        save_meta: function(meta, complete, error) {
1111
            var url = this.api_path() + "/meta/" + meta.key;
1112
            var payload = {meta:{}};
1113
            payload.meta[meta.key] = meta.value;
1114
            payload._options = {
1115
                critical:false, 
1116
                error_params: {
1117
                    title: "Machine metadata error",
1118
                    extra_details: {"Machine id": this.id}
1119
            }};
1120

    
1121
            this.api_call(url, "update", payload, complete, error);
1122
        },
1123

    
1124

    
1125
        // update/get the state of the machine
1126
        state: function() {
1127
            var args = slice.call(arguments);
1128
                
1129
            // TODO: it might not be a good idea to set the state in set_state method
1130
            if (args.length > 0 && models.VM.STATES.indexOf(args[0]) > -1) {
1131
                this.set({'state': args[0]});
1132
            }
1133

    
1134
            return this.get('state');
1135
        },
1136
        
1137
        // get the state that the api status corresponds to
1138
        state_for_api_status: function(status) {
1139
            return this.state_transition(this.state(), status);
1140
        },
1141
        
1142
        // vm state equals vm api status
1143
        state_is_status: function(state) {
1144
            return models.VM.STATUSES.indexOf(state) != -1;
1145
        },
1146
        
1147
        // get transition state for the corresponging api status
1148
        state_transition: function(state, new_status) {
1149
            var statuses = models.VM.STATES_TRANSITIONS[state];
1150
            if (statuses) {
1151
                if (statuses.indexOf(new_status) > -1) {
1152
                    return new_status;
1153
                } else {
1154
                    return state;
1155
                }
1156
            } else {
1157
                return new_status;
1158
            }
1159
        },
1160
        
1161
        // the current vm state is a transition state
1162
        in_transition: function() {
1163
            return models.VM.TRANSITION_STATES.indexOf(this.state()) > -1 || 
1164
                models.VM.TRANSITION_STATES.indexOf(this.get('status')) > -1;
1165
        },
1166
        
1167
        // get image object
1168
        get_image: function(callback) {
1169
            var image = storage.images.get(this.get('imageRef'));
1170
            if (!image) {
1171
                storage.images.update_unknown_id(this.get('imageRef'), callback);
1172
                return;
1173
            }
1174
            callback(image);
1175
            return image;
1176
        },
1177
        
1178
        // get flavor object
1179
        get_flavor: function() {
1180
            var flv = storage.flavors.get(this.get('flavorRef'));
1181
            if (!flv) {
1182
                storage.flavors.update_unknown_id(this.get('flavorRef'));
1183
                flv = storage.flavors.get(this.get('flavorRef'));
1184
            }
1185
            return flv;
1186
        },
1187

    
1188
        get_meta: function(key) {
1189
            if (this.get('metadata') && this.get('metadata').values) {
1190
                if (!this.get('metadata').values[key]) { return null }
1191
                return _.escape(this.get('metadata').values[key]);
1192
            } else {
1193
                return null;
1194
            }
1195
        },
1196

    
1197
        get_meta_keys: function() {
1198
            if (this.get('metadata') && this.get('metadata').values) {
1199
                return _.keys(this.get('metadata').values);
1200
            } else {
1201
                return [];
1202
            }
1203
        },
1204
        
1205
        // get metadata OS value
1206
        get_os: function() {
1207
            return this.get_meta('OS') || (this.get_image(function(){}) ? 
1208
                                          this.get_image(function(){}).get_os() || "okeanos" : "okeanos");
1209
        },
1210

    
1211
        get_gui: function() {
1212
            return this.get_meta('GUI');
1213
        },
1214
        
1215
        connected_to: function(net) {
1216
            return this.get('linked_to').indexOf(net.id) > -1;
1217
        },
1218

    
1219
        connected_with_nic_id: function(nic_id) {
1220
            return _.keys(this.get('nics')).indexOf(nic_id) > -1;
1221
        },
1222

    
1223
        get_nics: function(filter) {
1224
            ret = synnefo.storage.nics.filter(function(nic) {
1225
                return parseInt(nic.get('vm_id')) == this.id;
1226
            }, this);
1227

    
1228
            if (filter) {
1229
                return _.filter(ret, filter);
1230
            }
1231

    
1232
            return ret;
1233
        },
1234

    
1235
        get_net_nics: function(net_id) {
1236
            return this.get_nics(function(n){return n.get('network_id') == net_id});
1237
        },
1238

    
1239
        get_public_nic: function() {
1240
            return this.get_nics(function(n){ return n.get_network().is_public() === true })[0];
1241
        },
1242

    
1243
        get_nic: function(net_id) {
1244
        },
1245

    
1246
        has_firewall: function() {
1247
            var nic = this.get_public_nic();
1248
            if (nic) {
1249
                var profile = nic.get('firewallProfile'); 
1250
                return ['ENABLED', 'PROTECTED'].indexOf(profile) > -1;
1251
            }
1252
            return false;
1253
        },
1254

    
1255
        get_firewall_profile: function() {
1256
            var nic = this.get_public_nic();
1257
            if (nic) {
1258
                return nic.get('firewallProfile');
1259
            }
1260
            return null;
1261
        },
1262

    
1263
        get_addresses: function() {
1264
            var pnic = this.get_public_nic();
1265
            if (!pnic) { return {'ip4': undefined, 'ip6': undefined }};
1266
            return {'ip4': pnic.get('ipv4'), 'ip6': pnic.get('ipv6')};
1267
        },
1268
    
1269
        // get actions that the user can execute
1270
        // depending on the vm state/status
1271
        get_available_actions: function() {
1272
            return models.VM.AVAILABLE_ACTIONS[this.state()];
1273
        },
1274

    
1275
        set_profile: function(profile, net_id) {
1276
        },
1277
        
1278
        // call rename api
1279
        rename: function(new_name) {
1280
            //this.set({'name': new_name});
1281
            this.sync("update", this, {
1282
                critical: true,
1283
                data: {
1284
                    'server': {
1285
                        'name': new_name
1286
                    }
1287
                }, 
1288
                // do the rename after the method succeeds
1289
                success: _.bind(function(){
1290
                    //this.set({name: new_name});
1291
                    snf.api.trigger("call");
1292
                }, this)
1293
            });
1294
        },
1295
        
1296
        get_console_url: function(data) {
1297
            var url_params = {
1298
                machine: this.get("name"),
1299
                host_ip: this.get_addresses().ip4,
1300
                host_ip_v6: this.get_addresses().ip6,
1301
                host: data.host,
1302
                port: data.port,
1303
                password: data.password
1304
            }
1305
            return '/machines/console?' + $.param(url_params);
1306
        },
1307

    
1308
        // action helper
1309
        call: function(action_name, success, error, params) {
1310
            var id_param = [this.id];
1311
            
1312
            params = params || {};
1313
            success = success || function() {};
1314
            error = error || function() {};
1315

    
1316
            var self = this;
1317

    
1318
            switch(action_name) {
1319
                case 'start':
1320
                    this.__make_api_call(this.get_action_url(), // vm actions url
1321
                                         "create", // create so that sync later uses POST to make the call
1322
                                         {start:{}}, // payload
1323
                                         function() {
1324
                                             // set state after successful call
1325
                                             self.state("START"); 
1326
                                             success.apply(this, arguments);
1327
                                             snf.api.trigger("call");
1328
                                         },  
1329
                                         error, 'start', params);
1330
                    break;
1331
                case 'reboot':
1332
                    this.__make_api_call(this.get_action_url(), // vm actions url
1333
                                         "create", // create so that sync later uses POST to make the call
1334
                                         {reboot:{type:"HARD"}}, // payload
1335
                                         function() {
1336
                                             // set state after successful call
1337
                                             self.state("REBOOT"); 
1338
                                             success.apply(this, arguments)
1339
                                             snf.api.trigger("call");
1340
                                             self.set({'reboot_required': false});
1341
                                         },
1342
                                         error, 'reboot', params);
1343
                    break;
1344
                case 'shutdown':
1345
                    this.__make_api_call(this.get_action_url(), // vm actions url
1346
                                         "create", // create so that sync later uses POST to make the call
1347
                                         {shutdown:{}}, // payload
1348
                                         function() {
1349
                                             // set state after successful call
1350
                                             self.state("SHUTDOWN"); 
1351
                                             success.apply(this, arguments)
1352
                                             snf.api.trigger("call");
1353
                                         },  
1354
                                         error, 'shutdown', params);
1355
                    break;
1356
                case 'console':
1357
                    this.__make_api_call(this.url() + "/action", "create", {'console': {'type':'vnc'}}, function(data) {
1358
                        var cons_data = data.console;
1359
                        success.apply(this, [cons_data]);
1360
                    }, undefined, 'console', params)
1361
                    break;
1362
                case 'destroy':
1363
                    this.__make_api_call(this.url(), // vm actions url
1364
                                         "delete", // create so that sync later uses POST to make the call
1365
                                         undefined, // payload
1366
                                         function() {
1367
                                             // set state after successful call
1368
                                             self.state('DESTROY');
1369
                                             success.apply(this, arguments)
1370
                                         },  
1371
                                         error, 'destroy', params);
1372
                    break;
1373
                default:
1374
                    throw "Invalid VM action ("+action_name+")";
1375
            }
1376
        },
1377
        
1378
        __make_api_call: function(url, method, data, success, error, action, extra_params) {
1379
            var self = this;
1380
            error = error || function(){};
1381
            success = success || function(){};
1382

    
1383
            var params = {
1384
                url: url,
1385
                data: data,
1386
                success: function(){ self.handle_action_succeed.apply(self, arguments); success.apply(this, arguments)},
1387
                error: function(){ self.handle_action_fail.apply(self, arguments); error.apply(this, arguments)},
1388
                error_params: { ns: "Machines actions", 
1389
                                title: "'" + this.get("name") + "'" + " " + action + " failed", 
1390
                                extra_details: { 'Machine ID': this.id, 'URL': url, 'Action': action || "undefined" },
1391
                                allow_reload: false
1392
                              },
1393
                display: false,
1394
                critical: false
1395
            }
1396
            _.extend(params, extra_params)
1397
            this.sync(method, this, params);
1398
        },
1399

    
1400
        handle_action_succeed: function() {
1401
            this.trigger("action:success", arguments);
1402
        },
1403
        
1404
        reset_action_error: function() {
1405
            this.action_error = false;
1406
            this.trigger("action:fail:reset", this.action_error);
1407
        },
1408

    
1409
        handle_action_fail: function() {
1410
            this.action_error = arguments;
1411
            this.trigger("action:fail", arguments);
1412
        },
1413

    
1414
        get_action_url: function(name) {
1415
            return this.url() + "/action";
1416
        },
1417

    
1418
        get_diagnostics_url: function() {
1419
            return this.url() + "/diagnostics";
1420
        },
1421

    
1422
        get_connection_info: function(host_os, success, error) {
1423
            var url = "/machines/connect";
1424
            params = {
1425
                ip_address: this.get_addresses().ip4,
1426
                os: this.get_os(),
1427
                host_os: host_os,
1428
                srv: this.id
1429
            }
1430

    
1431
            url = url + "?" + $.param(params);
1432

    
1433
            var ajax = snf.api.sync("read", undefined, { url: url, 
1434
                                                         error:error, 
1435
                                                         success:success, 
1436
                                                         handles_error:1});
1437
        }
1438
    })
1439
    
1440
    models.VM.ACTIONS = [
1441
        'start',
1442
        'shutdown',
1443
        'reboot',
1444
        'console',
1445
        'destroy'
1446
    ]
1447

    
1448
    models.VM.AVAILABLE_ACTIONS = {
1449
        'UNKNWON'       : ['destroy'],
1450
        'BUILD'         : ['destroy'],
1451
        'REBOOT'        : ['shutdown', 'destroy', 'console'],
1452
        'STOPPED'       : ['start', 'destroy'],
1453
        'ACTIVE'        : ['shutdown', 'destroy', 'reboot', 'console'],
1454
        'ERROR'         : ['destroy'],
1455
        'DELETED'        : [],
1456
        'DESTROY'       : [],
1457
        'BUILD_INIT'    : ['destroy'],
1458
        'BUILD_COPY'    : ['destroy'],
1459
        'BUILD_FINAL'   : ['destroy'],
1460
        'SHUTDOWN'      : ['destroy'],
1461
        'START'         : [],
1462
        'CONNECT'       : [],
1463
        'DISCONNECT'    : []
1464
    }
1465

    
1466
    // api status values
1467
    models.VM.STATUSES = [
1468
        'UNKNWON',
1469
        'BUILD',
1470
        'REBOOT',
1471
        'STOPPED',
1472
        'ACTIVE',
1473
        'ERROR',
1474
        'DELETED'
1475
    ]
1476

    
1477
    // api status values
1478
    models.VM.CONNECT_STATES = [
1479
        'ACTIVE',
1480
        'REBOOT',
1481
        'SHUTDOWN'
1482
    ]
1483

    
1484
    // vm states
1485
    models.VM.STATES = models.VM.STATUSES.concat([
1486
        'DESTROY',
1487
        'BUILD_INIT',
1488
        'BUILD_COPY',
1489
        'BUILD_FINAL',
1490
        'SHUTDOWN',
1491
        'START',
1492
        'CONNECT',
1493
        'DISCONNECT',
1494
        'FIREWALL'
1495
    ]);
1496
    
1497
    models.VM.STATES_TRANSITIONS = {
1498
        'DESTROY' : ['DELETED'],
1499
        'SHUTDOWN': ['ERROR', 'STOPPED', 'DESTROY'],
1500
        'STOPPED': ['ERROR', 'ACTIVE', 'DESTROY'],
1501
        'ACTIVE': ['ERROR', 'STOPPED', 'REBOOT', 'SHUTDOWN', 'DESTROY'],
1502
        'START': ['ERROR', 'ACTIVE', 'DESTROY'],
1503
        'REBOOT': ['ERROR', 'ACTIVE', 'STOPPED', 'DESTROY'],
1504
        'BUILD': ['ERROR', 'ACTIVE', 'DESTROY'],
1505
        'BUILD_COPY': ['ERROR', 'ACTIVE', 'BUILD_FINAL', 'DESTROY'],
1506
        'BUILD_FINAL': ['ERROR', 'ACTIVE', 'DESTROY'],
1507
        'BUILD_INIT': ['ERROR', 'ACTIVE', 'BUILD_COPY', 'BUILD_FINAL', 'DESTROY']
1508
    }
1509

    
1510
    models.VM.TRANSITION_STATES = [
1511
        'DESTROY',
1512
        'SHUTDOWN',
1513
        'START',
1514
        'REBOOT',
1515
        'BUILD'
1516
    ]
1517

    
1518
    models.VM.ACTIVE_STATES = [
1519
        'BUILD', 'REBOOT', 'ACTIVE',
1520
        'BUILD_INIT', 'BUILD_COPY', 'BUILD_FINAL',
1521
        'SHUTDOWN', 'CONNECT', 'DISCONNECT'
1522
    ]
1523

    
1524
    models.VM.BUILDING_STATES = [
1525
        'BUILD', 'BUILD_INIT', 'BUILD_COPY', 'BUILD_FINAL'
1526
    ]
1527

    
1528
    models.Networks = models.Collection.extend({
1529
        model: models.Network,
1530
        path: 'networks',
1531
        details: true,
1532
        //noUpdate: true,
1533
        defaults: {'nics':[],'linked_to':[]},
1534
        
1535
        parse: function (resp, xhr) {
1536
            // FIXME: depricated global var
1537
            if (!resp) { return []};
1538
            var data = _.map(resp.networks.values, _.bind(this.parse_net_api_data, this));
1539
            return data;
1540
        },
1541

    
1542
        add: function() {
1543
            ret = models.Networks.__super__.add.apply(this, arguments);
1544
            // update nics after each network addition
1545
            ret.each(function(r){
1546
                synnefo.storage.nics.update_net_nics(r);
1547
            });
1548
        },
1549

    
1550
        reset_pending_actions: function() {
1551
            this.each(function(net) {
1552
                net.get("actions").reset();
1553
            });
1554
        },
1555

    
1556
        do_all_pending_actions: function() {
1557
            this.each(function(net) {
1558
                net.do_all_pending_actions();
1559
            })
1560
        },
1561

    
1562
        parse_net_api_data: function(data) {
1563
            // append nic metadata
1564
            // net.get('nics') contains a list of vm/index objects 
1565
            // e.g. {'vm_id':12231, 'index':1}
1566
            // net.get('linked_to') contains a list of vms the network is 
1567
            // connected to e.g. [1001, 1002]
1568
            if (data.attachments && data.attachments.values) {
1569
                data['nics'] = {};
1570
                data['linked_to'] = [];
1571
                _.each(data.attachments.values, function(nic_id){
1572
                  
1573
                  var vm_id = NIC_REGEX.exec(nic_id)[1];
1574
                  var nic_index = parseInt(NIC_REGEX.exec(nic_id)[2]);
1575

    
1576
                  if (vm_id !== undefined && nic_index !== undefined) {
1577
                      data['nics'][nic_id] = {
1578
                          'vm_id': vm_id, 
1579
                          'index': nic_index, 
1580
                          'id': nic_id
1581
                      };
1582
                      if (data['linked_to'].indexOf(vm_id) == -1) {
1583
                        data['linked_to'].push(vm_id);
1584
                      }
1585
                  }
1586
                });
1587
            }
1588
            return data;
1589
        },
1590

    
1591
        create: function (name, type, cidr, dhcp, callback) {
1592
            var params = {
1593
                network:{
1594
                    name:name
1595
                }
1596
            };
1597

    
1598
            if (type) {
1599
                params.network.type = type;
1600
            }
1601
            if (cidr) {
1602
                params.network.cidr = cidr;
1603
            }
1604
            if (dhcp) {
1605
                params.network.dhcp = dhcp;
1606
            }
1607

    
1608
            if (dhcp === false) {
1609
                params.network.dhcp = false;
1610
            }
1611
            
1612
            return this.api_call(this.path, "create", params, callback);
1613
        },
1614

    
1615
        get_public: function(){
1616
          return this.filter(function(n){return n.get('public')});
1617
        }
1618
    })
1619

    
1620
    models.Images = models.Collection.extend({
1621
        model: models.Image,
1622
        path: 'images',
1623
        details: true,
1624
        noUpdate: true,
1625
        supportIncUpdates: false,
1626
        meta_keys_as_attrs: ["OS", "description", "kernel", "size", "GUI"],
1627
        meta_labels: {},
1628
        read_method: 'read',
1629

    
1630
        // update collection model with id passed
1631
        // making a direct call to the image
1632
        // api url
1633
        update_unknown_id: function(id, callback) {
1634
            var url = getUrl.call(this) + "/" + id;
1635
            this.api_call(this.path + "/" + id, this.read_method, {
1636
              _options:{
1637
                async:true, 
1638
                skip_api_error:true}
1639
              }, undefined, 
1640
            _.bind(function() {
1641
                if (!this.get(id)) {
1642
                            if (this.fallback_service) {
1643
                        // if current service has fallback_service attribute set
1644
                        // use this service to retrieve the missing image model
1645
                        var tmpservice = new this.fallback_service();
1646
                        tmpservice.update_unknown_id(id, _.bind(function(img){
1647
                            img.attributes.status = "DELETED";
1648
                            this.add(img.attributes);
1649
                            callback(this.get(id));
1650
                        }, this));
1651
                    } else {
1652
                        var title = synnefo.config.image_deleted_title || 'Deleted';
1653
                        // else add a dummy DELETED state image entry
1654
                        this.add({id:id, name:title, size:-1, 
1655
                                  progress:100, status:"DELETED"});
1656
                        callback(this.get(id));
1657
                    }   
1658
                } else {
1659
                    callback(this.get(id));
1660
                }
1661
            }, this), _.bind(function(image, msg, xhr) {
1662
                if (!image) {
1663
                    var title = synnefo.config.image_deleted_title || 'Deleted';
1664
                    this.add({id:id, name:title, size:-1, 
1665
                              progress:100, status:"DELETED"});
1666
                    callback(this.get(id));
1667
                    return;
1668
                }
1669
                var img_data = this._read_image_from_request(image, msg, xhr);
1670
                this.add(img_data);
1671
                callback(this.get(id));
1672
            }, this));
1673
        },
1674

    
1675
        _read_image_from_request: function(image, msg, xhr) {
1676
            return image.image;
1677
        },
1678

    
1679
        parse: function (resp, xhr) {
1680
            var data = _.map(resp.images.values, _.bind(this.parse_meta, this));
1681
            return resp.images.values;
1682
        },
1683

    
1684
        get_meta_key: function(img, key) {
1685
            if (img.metadata && img.metadata.values && img.metadata.values[key]) {
1686
                return _.escape(img.metadata.values[key]);
1687
            }
1688
            return undefined;
1689
        },
1690

    
1691
        comparator: function(img) {
1692
            return -img.get_sort_order("sortorder") || 1000 * img.id;
1693
        },
1694

    
1695
        parse_meta: function(img) {
1696
            _.each(this.meta_keys_as_attrs, _.bind(function(key){
1697
                if (img[key]) { return };
1698
                img[key] = this.get_meta_key(img, key) || "";
1699
            }, this));
1700
            return img;
1701
        },
1702

    
1703
        active: function() {
1704
            return this.filter(function(img){return img.get('status') != "DELETED"});
1705
        },
1706

    
1707
        predefined: function() {
1708
            return _.filter(this.active(), function(i) { return !i.get("serverRef")});
1709
        },
1710
        
1711
        fetch_for_type: function(type, complete, error) {
1712
            this.fetch({update:true, 
1713
                        success: complete, 
1714
                        error: error, 
1715
                        skip_api_error: true });
1716
        },
1717
        
1718
        get_images_for_type: function(type) {
1719
            if (this['get_{0}_images'.format(type)]) {
1720
                return this['get_{0}_images'.format(type)]();
1721
            }
1722

    
1723
            return this.active();
1724
        },
1725

    
1726
        update_images_for_type: function(type, onStart, onComplete, onError, force_load) {
1727
            var load = false;
1728
            error = onError || function() {};
1729
            function complete(collection) { 
1730
                onComplete(collection.get_images_for_type(type)); 
1731
            }
1732
            
1733
            // do we need to fetch/update current collection entries
1734
            if (load) {
1735
                onStart();
1736
                this.fetch_for_type(type, complete, error);
1737
            } else {
1738
                // fallback to complete
1739
                complete(this);
1740
            }
1741
        }
1742
    })
1743

    
1744
    models.Flavors = models.Collection.extend({
1745
        model: models.Flavor,
1746
        path: 'flavors',
1747
        details: true,
1748
        noUpdate: true,
1749
        supportIncUpdates: false,
1750
        // update collection model with id passed
1751
        // making a direct call to the flavor
1752
        // api url
1753
        update_unknown_id: function(id, callback) {
1754
            var url = getUrl.call(this) + "/" + id;
1755
            this.api_call(this.path + "/" + id, "read", {_options:{async:false, skip_api_error:true}}, undefined, 
1756
            _.bind(function() {
1757
                this.add({id:id, cpu:"", ram:"", disk:"", name: "", status:"DELETED"})
1758
            }, this), _.bind(function(flv) {
1759
                if (!flv.flavor.status) { flv.flavor.status = "DELETED" };
1760
                this.add(flv.flavor);
1761
            }, this));
1762
        },
1763

    
1764
        parse: function (resp, xhr) {
1765
            return _.map(resp.flavors.values, function(o) { o.disk_template = o['SNF:disk_template']; return o});
1766
        },
1767

    
1768
        comparator: function(flv) {
1769
            return flv.get("disk") * flv.get("cpu") * flv.get("ram");
1770
        },
1771

    
1772
        unavailable_values_for_image: function(img, flavors) {
1773
            var flavors = flavors || this.active();
1774
            var size = img.get_size();
1775
            
1776
            var index = {cpu:[], disk:[], ram:[]};
1777

    
1778
            _.each(this.active(), function(el) {
1779
                var img_size = size;
1780
                var flv_size = el.get_disk_size();
1781
                if (flv_size < img_size) {
1782
                    if (index.disk.indexOf(flv_size) == -1) {
1783
                        index.disk.push(flv_size);
1784
                    }
1785
                };
1786
            });
1787
            
1788
            return index;
1789
        },
1790

    
1791
        get_flavor: function(cpu, mem, disk, disk_template, filter_list) {
1792
            if (!filter_list) { filter_list = this.models };
1793
            
1794
            return this.select(function(flv){
1795
                if (flv.get("cpu") == cpu + "" &&
1796
                   flv.get("ram") == mem + "" &&
1797
                   flv.get("disk") == disk + "" &&
1798
                   flv.get("disk_template") == disk_template &&
1799
                   filter_list.indexOf(flv) > -1) { return true; }
1800
            })[0];
1801
        },
1802
        
1803
        get_data: function(lst) {
1804
            var data = {'cpu': [], 'mem':[], 'disk':[]};
1805

    
1806
            _.each(lst, function(flv) {
1807
                if (data.cpu.indexOf(flv.get("cpu")) == -1) {
1808
                    data.cpu.push(flv.get("cpu"));
1809
                }
1810
                if (data.mem.indexOf(flv.get("ram")) == -1) {
1811
                    data.mem.push(flv.get("ram"));
1812
                }
1813
                if (data.disk.indexOf(flv.get("disk")) == -1) {
1814
                    data.disk.push(flv.get("disk"));
1815
                }
1816
            })
1817
            
1818
            return data;
1819
        },
1820

    
1821
        active: function() {
1822
            return this.filter(function(flv){return flv.get('status') != "DELETED"});
1823
        }
1824
            
1825
    })
1826

    
1827
    models.VMS = models.Collection.extend({
1828
        model: models.VM,
1829
        path: 'servers',
1830
        details: true,
1831
        copy_image_meta: true,
1832

    
1833
        parse: function (resp, xhr) {
1834
            var data = resp;
1835
            if (!resp) { return [] };
1836
            data = _.filter(_.map(resp.servers.values, _.bind(this.parse_vm_api_data, this)), function(v){return v});
1837
            return data;
1838
        },
1839

    
1840
        parse_vm_api_data: function(data) {
1841
            // do not add non existing DELETED entries
1842
            if (data.status && data.status == "DELETED") {
1843
                if (!this.get(data.id)) {
1844
                    return false;
1845
                }
1846
            }
1847

    
1848
            // OS attribute
1849
            if (this.has_meta(data)) {
1850
                data['OS'] = data.metadata.values.OS || "okeanos";
1851
            }
1852
            
1853
            if (!data.diagnostics) {
1854
                data.diagnostics = [];
1855
            }
1856

    
1857
            // network metadata
1858
            data['firewalls'] = {};
1859
            data['nics'] = {};
1860
            data['linked_to'] = [];
1861

    
1862
            if (data['attachments'] && data['attachments'].values) {
1863
                var nics = data['attachments'].values;
1864
                _.each(nics, function(nic) {
1865
                    var net_id = nic.network_id;
1866
                    var index = parseInt(NIC_REGEX.exec(nic.id)[2]);
1867
                    if (data['linked_to'].indexOf(net_id) == -1) {
1868
                        data['linked_to'].push(net_id);
1869
                    }
1870

    
1871
                    data['nics'][nic.id] = nic;
1872
                })
1873
            }
1874
            
1875
            // if vm has no metadata, no metadata object
1876
            // is in json response, reset it to force
1877
            // value update
1878
            if (!data['metadata']) {
1879
                data['metadata'] = {values:{}};
1880
            }
1881

    
1882
            return data;
1883
        },
1884

    
1885
        add: function() {
1886
            ret = models.VMS.__super__.add.apply(this, arguments);
1887
            ret.each(function(r){
1888
                synnefo.storage.nics.update_vm_nics(r);
1889
            });
1890
        },
1891
        
1892
        get_reboot_required: function() {
1893
            return this.filter(function(vm){return vm.get("reboot_required") == true})
1894
        },
1895

    
1896
        has_pending_actions: function() {
1897
            return this.filter(function(vm){return vm.pending_action}).length > 0;
1898
        },
1899

    
1900
        reset_pending_actions: function() {
1901
            this.each(function(vm) {
1902
                vm.clear_pending_action();
1903
            })
1904
        },
1905

    
1906
        do_all_pending_actions: function(success, error) {
1907
            this.each(function(vm) {
1908
                if (vm.has_pending_action()) {
1909
                    vm.call(vm.pending_action, success, error);
1910
                    vm.clear_pending_action();
1911
                }
1912
            })
1913
        },
1914
        
1915
        do_all_reboots: function(success, error) {
1916
            this.each(function(vm) {
1917
                if (vm.get("reboot_required")) {
1918
                    vm.call("reboot", success, error);
1919
                }
1920
            });
1921
        },
1922

    
1923
        reset_reboot_required: function() {
1924
            this.each(function(vm) {
1925
                vm.set({'reboot_required': undefined});
1926
            })
1927
        },
1928
        
1929
        stop_stats_update: function(exclude) {
1930
            var exclude = exclude || [];
1931
            this.each(function(vm) {
1932
                if (exclude.indexOf(vm) > -1) {
1933
                    return;
1934
                }
1935
                vm.stop_stats_update();
1936
            })
1937
        },
1938
        
1939
        has_meta: function(vm_data) {
1940
            return vm_data.metadata && vm_data.metadata.values
1941
        },
1942

    
1943
        has_addresses: function(vm_data) {
1944
            return vm_data.metadata && vm_data.metadata.values
1945
        },
1946

    
1947
        create: function (name, image, flavor, meta, extra, callback) {
1948

    
1949
            if (this.copy_image_meta) {
1950
                if (synnefo.config.vm_image_common_metadata) {
1951
                    _.each(synnefo.config.vm_image_common_metadata, 
1952
                        function(key){
1953
                            if (image.get_meta(key)) {
1954
                                meta[key] = image.get_meta(key);
1955
                            }
1956
                    });
1957
                }
1958

    
1959
                if (image.get("OS")) {
1960
                    meta['OS'] = image.get("OS");
1961
                }
1962
            }
1963
            
1964
            opts = {name: name, imageRef: image.id, flavorRef: flavor.id, metadata:meta}
1965
            opts = _.extend(opts, extra);
1966

    
1967
            this.api_call(this.path, "create", {'server': opts}, undefined, undefined, callback, {critical: true});
1968
        }
1969

    
1970
    })
1971
    
1972
    models.NIC = models.Model.extend({
1973
        
1974
        initialize: function() {
1975
            models.NIC.__super__.initialize.apply(this, arguments);
1976
            this.pending_for_firewall = false;
1977
            this.bind("change:firewallProfile", _.bind(this.check_firewall, this));
1978
            this.bind("change:pending_firewall", function(nic) {
1979
                nic.get_network().update_state();
1980
            });
1981
            this.get_vm().bind("remove", function(){
1982
                try {
1983
                    this.collection.remove(this);
1984
                } catch (err) {};
1985
            }, this);
1986
            this.get_network().bind("remove", function(){
1987
                try {
1988
                    this.collection.remove(this);
1989
                } catch (err) {};
1990
            }, this);
1991

    
1992
        },
1993

    
1994
        get_vm: function() {
1995
            return synnefo.storage.vms.get(parseInt(this.get('vm_id')));
1996
        },
1997

    
1998
        get_network: function() {
1999
            return synnefo.storage.networks.get(this.get('network_id'));
2000
        },
2001

    
2002
        get_v6_address: function() {
2003
            return this.get("ipv6");
2004
        },
2005

    
2006
        get_v4_address: function() {
2007
            return this.get("ipv4");
2008
        },
2009

    
2010
        set_firewall: function(value, callback, error, options) {
2011
            var net_id = this.get('network_id');
2012
            var self = this;
2013

    
2014
            // api call data
2015
            var payload = {"firewallProfile":{"profile":value}};
2016
            payload._options = _.extend({critical: false}, options);
2017
            
2018
            this.set({'pending_firewall': value});
2019
            this.set({'pending_firewall_sending': true});
2020
            this.set({'pending_firewall_from': this.get('firewallProfile')});
2021

    
2022
            var success_cb = function() {
2023
                if (callback) {
2024
                    callback();
2025
                }
2026
                self.set({'pending_firewall_sending': false});
2027
            };
2028

    
2029
            var error_cb = function() {
2030
                self.reset_pending_firewall();
2031
            }
2032
            
2033
            this.get_vm().api_call(this.get_vm().api_path() + "/action", "create", payload, success_cb, error_cb);
2034
        },
2035

    
2036
        reset_pending_firewall: function() {
2037
            this.set({'pending_firewall': false});
2038
            this.set({'pending_firewall': false});
2039
        },
2040

    
2041
        check_firewall: function() {
2042
            var firewall = this.get('firewallProfile');
2043
            var pending = this.get('pending_firewall');
2044
            var previous = this.get('pending_firewall_from');
2045
            if (previous != firewall) { this.get_vm().require_reboot() };
2046
            this.reset_pending_firewall();
2047
        }
2048
        
2049
    });
2050

    
2051
    models.NICs = models.Collection.extend({
2052
        model: models.NIC,
2053
        
2054
        add_or_update: function(nic_id, data, vm) {
2055
            var params = _.clone(data);
2056
            var vm;
2057
            params.attachment_id = params.id;
2058
            params.id = params.id + '-' + params.network_id;
2059
            params.vm_id = parseInt(NIC_REGEX.exec(nic_id)[1]);
2060

    
2061
            if (!this.get(params.id)) {
2062
                this.add(params);
2063
                var nic = this.get(params.id);
2064
                vm = nic.get_vm();
2065
                nic.get_network().decrease_connecting();
2066
                nic.bind("remove", function() {
2067
                    nic.set({"removing": 0});
2068
                    if (this.get_network()) {
2069
                        // network might got removed before nic
2070
                        nic.get_network().update_state();
2071
                    }
2072
                });
2073

    
2074
            } else {
2075
                this.get(params.id).set(params);
2076
                vm = this.get(params.id).get_vm();
2077
            }
2078
            
2079
            // vm nics changed, trigger vm update
2080
            if (vm) { vm.trigger("change", vm)};
2081
        },
2082
        
2083
        reset_nics: function(nics, filter_attr, filter_val) {
2084
            var nics_to_check = this.filter(function(nic) {
2085
                return nic.get(filter_attr) == filter_val;
2086
            });
2087
            
2088
            _.each(nics_to_check, function(nic) {
2089
                if (nics.indexOf(nic.get('id')) == -1) {
2090
                    this.remove(nic);
2091
                } else {
2092
                }
2093
            }, this);
2094
        },
2095

    
2096
        update_vm_nics: function(vm) {
2097
            var nics = vm.get('nics');
2098
            this.reset_nics(_.map(nics, function(nic, key){
2099
                return key + "-" + nic.network_id;
2100
            }), 'vm_id', vm.id);
2101

    
2102
            _.each(nics, function(val, key) {
2103
                var net = synnefo.storage.networks.get(val.network_id);
2104
                if (net && net.connected_with_nic_id(key) && vm.connected_with_nic_id(key)) {
2105
                    this.add_or_update(key, vm.get('nics')[key], vm);
2106
                }
2107
            }, this);
2108
        },
2109

    
2110
        update_net_nics: function(net) {
2111
            var nics = net.get('nics');
2112
            this.reset_nics(_.map(nics, function(nic, key){
2113
                return key + "-" + net.get('id');
2114
            }), 'network_id', net.id);
2115

    
2116
            _.each(nics, function(val, key) {
2117
                var vm = synnefo.storage.vms.get(val.vm_id);
2118
                if (vm && net.connected_with_nic_id(key) && vm.connected_with_nic_id(key)) {
2119
                    this.add_or_update(key, vm.get('nics')[key], vm);
2120
                }
2121
            }, this);
2122
        }
2123
    });
2124

    
2125
    models.PublicKey = models.Model.extend({
2126
        path: 'keys',
2127
        base_url: '/ui/userdata',
2128
        details: false,
2129
        noUpdate: true,
2130

    
2131

    
2132
        get_public_key: function() {
2133
            return cryptico.publicKeyFromString(this.get("content"));
2134
        },
2135

    
2136
        get_filename: function() {
2137
            return "{0}.pub".format(this.get("name"));
2138
        },
2139

    
2140
        identify_type: function() {
2141
            try {
2142
                var cont = snf.util.validatePublicKey(this.get("content"));
2143
                var type = cont.split(" ")[0];
2144
                return synnefo.util.publicKeyTypesMap[type];
2145
            } catch (err) { return false };
2146
        }
2147

    
2148
    })
2149
    
2150
    models.PublicKeys = models.Collection.extend({
2151
        model: models.PublicKey,
2152
        details: false,
2153
        path: 'keys',
2154
        base_url: '/ui/userdata',
2155
        noUpdate: true,
2156

    
2157
        generate_new: function(success, error) {
2158
            snf.api.sync('create', undefined, {
2159
                url: getUrl.call(this, this.base_url) + "/generate", 
2160
                success: success, 
2161
                error: error,
2162
                skip_api_error: true
2163
            });
2164
        },
2165

    
2166
        add_crypto_key: function(key, success, error, options) {
2167
            var options = options || {};
2168
            var m = new models.PublicKey();
2169

    
2170
            // guess a name
2171
            var name_tpl = "my generated public key";
2172
            var name = name_tpl;
2173
            var name_count = 1;
2174
            
2175
            while(this.filter(function(m){ return m.get("name") == name }).length > 0) {
2176
                name = name_tpl + " " + name_count;
2177
                name_count++;
2178
            }
2179
            
2180
            m.set({name: name});
2181
            m.set({content: key});
2182
            
2183
            options.success = function () { return success(m) };
2184
            options.errror = error;
2185
            options.skip_api_error = true;
2186
            
2187
            this.create(m.attributes, options);
2188
        }
2189
    })
2190
    
2191
    // storage initialization
2192
    snf.storage.images = new models.Images();
2193
    snf.storage.flavors = new models.Flavors();
2194
    snf.storage.networks = new models.Networks();
2195
    snf.storage.vms = new models.VMS();
2196
    snf.storage.keys = new models.PublicKeys();
2197
    snf.storage.nics = new models.NICs();
2198

    
2199
    //snf.storage.vms.fetch({update:true});
2200
    //snf.storage.images.fetch({update:true});
2201
    //snf.storage.flavors.fetch({update:true});
2202

    
2203
})(this);