Cleaned code and improved communication with SLA Collector
[unfold.git] / plugins / queryupdater / static / js / queryupdater.js
1 /**
2  * MySlice QueryUpdater plugin
3  * Version: 0.1.0
4  * URL: http://www.myslice.info
5  * Description: display of selected resources
6  * Requires: 
7  * Author: The MySlice Team
8  * Copyright: Copyright 2012 UPMC Sorbonne Universités
9  * License: GPLv3
10  */
11
12 (function( $ ){
13
14     var debug=false;
15     debug=true;
16
17     // XXX record selected (multiple selection ?)
18     // XXX record disabled ?
19     // XXX out of sync plugin ?
20     // XXX out of date record ?
21     // record tags ???
22     //
23     // criticality of the absence of a handler in a plugin
24     // non-critical only can have switch case
25     // 
26     // Record state through the query cycle
27
28
29     var QueryUpdater = Plugin.extend({
30
31         init: function(options, element) {
32                 this.classname="queryupdater";
33             this._super(options, element);
34
35             var self = this;
36
37             this.initial = Array();
38             this.selected_resources = Array();
39
40             this.table = this.elmt('table').dataTable({
41 // the original querytable layout was
42 //                sDom: "<'row'<'col-xs-5'l><'col-xs-1'r><'col-xs-6'f>>t<'row'<'col-xs-5'i><'col-xs-7'p>>",
43 // however the bottom line with 'showing blabla...' and the navigation widget are not really helpful
44                 sDom: "<'row'<'col-xs-5'l><'col-xs-1'r><'col-xs-6'f>>t>",
45 // so this does not matter anymore now that the pagination area is turned off
46 //                sPaginationType: 'bootstrap',
47                       bAutoWidth: true,
48 //                bJQueryUI      : true,
49 //                bRetrieve      : true,
50 //                sScrollX       : '100%',                 // Horizontal scrolling 
51 //                bSortClasses   : false,              // Disable style for the sorted column
52 //                aaSorting      : [[ 0, 'asc' ]],        // Default sorting on URN
53 //                fnDrawCallback: function() {      // Reassociate close click every time the table is redrawn
54 //                    /* Prevent to loop on click while redrawing table  */
55 //                    $('.ResourceSelectedClose').unbind('click');
56 //                    /* Handle clicks on close span */
57 //                    /* Reassociate close click every time the table is redrawn */
58 //                    $('.ResourceSelectedClose').bind('click', self, self._close_click);
59 //                }
60              });
61             
62             // XXX This should not be done at init...
63             this.elmt('update').click(this, this.do_checksla);
64             this.elmt('refresh').click(this, this.do_refresh);
65             this.elmt('reset').click(this, this.do_reset);
66             this.elmt('clear_annotations').click(this, this.do_clear_annotations);
67
68             this.listen_query(options.query_uuid);
69         },
70
71         /*************************** PLUGIN EVENTS ****************************/
72
73         /***************************** GUI EVENTS *****************************/
74
75         do_checksla: function(e) {
76             var username = e.data.options.username;
77             var urn = data.value;
78             var arraySelectedResources = data.selected_resources;
79
80             var accepted_sla = [];
81             var count = 0;
82             var self = e.data;
83             // var testbedsWithSLA = ["iminds", "fuseco", "netmode"];
84             var testbedsWithSLA;
85             
86             var sliverPattern = /IDN\+(.+)\+(node|channel)\+/;
87             var list = [];
88
89             var promt = $('#sla-table-body');
90             
91             $.get("/sla/testbeds/", function(data) {
92                 testbedsWithSLA = data;
93
94                 console.log("Testbeds with SLA: " + testbedsWithSLA);
95
96                 $(arraySelectedResources).each(function () {
97                     var sliverMatch = sliverPattern.exec(this);
98                     var sliverId = sliverMatch[1];
99                     for (var i = 0; i < testbedsWithSLA.length; i++) {
100                         if(this.indexOf(testbedsWithSLA[i].toLowerCase()) >= 0){ // If it has SLA
101                             if (list.indexOf(sliverId) == -1) { // If it is not in the list
102                                 list.push(sliverId);
103                             }
104                         }
105                     }
106                 });
107
108                 if (list.length > 0) {
109                     for (var i = 0; i < list.length; i++) {
110                         var element = $('<tr>');
111                         element.append(
112                             $('<td>').append(list[i]),
113                             $('<td>').append('99% of Uptime for 99% of resources'),
114                             $('<td align="center">').append('<input type="checkbox" name="slaaccept" value="' + list[i] + '"/> <br />')
115                         );
116                         promt.append(element);
117                     }
118
119                     $('#sla_dialog').show();
120                     $('#slamodal').modal('show');
121                 } else {
122                     //manifold.raise_event(self.options.query_uuid, RUN_UPDATE);
123                 }
124             
125             });
126                     
127             $("#submit_sla").unbind().click(function(){
128                 console.log("With username: " + username);
129
130                 var notChecked = $("input[name='slaaccept']:not(:checked)");
131                 
132                 if (notChecked.length > 0) {
133                     for (var i = 0; i < notChecked.length; i++) {
134                          console.log("SLA not accepted: " + notChecked[i].value);
135                     }    
136
137                     alert("All SLAs have to be accepted to continue with the reservation");
138
139                 } else {
140                     // $(list).each(function () {
141                     //     var date = new Date();
142                     //     date.setYear(date.getFullYear() + 1);
143
144                     //     $.post("/sla/agreements/simplecreate", 
145                     //         { "template_id": this.toString(),
146                     //           "user": username,
147                     //           "expiration_time": date.toISOString()
148                     //         });
149
150                         
151                     // });
152
153                     $.ajax({
154                         url: "/sla/agreements/simplecreate", 
155                         data: { testbeds: list,
156                           user: username,
157                           resources: arraySelectedResources,
158                           slice: main_query.filters.slice()[0][2]
159                         },
160                         type: "post",
161                         traditional: true
162                     });
163
164                     console.log(main_query.filters.slice()[0][2]);
165                       
166                     $('#slamodal').modal('hide');
167                     $('#sla-table-body').empty();
168                     //manifold.raise_event(self.options.query_uuid, RUN_UPDATE);
169                 }
170             }); 
171         
172             $("#cancel_sla").unbind().click(function(){
173                 $('#slamodal').modal('hide');
174                 $('#sla-table-body').empty();
175             }); 
176         },
177
178      
179         do_update: function(e) {
180             var self = e.data;
181
182             var username = e.data.options.username;
183             var urn = data.value;
184             // XXX check that the query is not disabled
185
186             self.spin();
187             console.log("do_update");
188             // XXX check that the query is not disabled
189             //manifold.raise_event(self.options.query_uuid, RUN_UPDATE);
190
191             // how to stop the spinning after the event? 
192             // this should be triggered by some on_updatequery_done ?
193
194         },
195
196         // related buttons are also disabled in the html template
197         do_refresh: function(e)
198         {
199             throw 'resource_selected.do_refresh Not implemented';
200         },
201
202         do_reset: function(e)
203         {
204             throw 'queryupdater.do_reset Not implemented';
205         },
206
207         do_clear_annotations: function(e)
208         {
209             throw 'queryupdater.do_clear_annotations Not implemented';
210         },
211         
212         /************************** GUI MANIPULATION **************************/
213
214         
215         set_button_state: function(name, state)
216         {
217             this.elmt(name).attr('disabled', state ? false : 'disabled');
218         },
219
220         clear: function()
221         {
222
223         },
224
225         find_row: function(key)
226         {
227             // key in third position, column id = 2
228             var KEY_POS = 2;
229
230             var cols = $.grep(this.table.fnSettings().aoData, function(col) {
231                 return (col._aData[KEY_POS] == key);
232             } );
233
234             if (cols.length == 0)
235                 return null;
236             if (cols.length > 1)
237                 throw "Too many same-key rows in ResourceSelected plugin";
238
239             return cols[0];
240         },
241
242         set_state: function(data)
243         {
244             console.log("function set_state");
245             var action;
246             var msg;
247             var button = '';
248
249             var row;
250             
251             // make sure the change is visible : toggle on the whole plugin
252             // this might have to be made an 'auto-toggle' option of this plugin..
253             // also it might be needed to be a little finer-grained here
254
255         // XXX we don't want to show automaticaly the pending when a checkbox is checked
256             //this.toggle_on();
257             
258             switch(data.request) {
259                 case FIELD_REQUEST_ADD_RESET:
260                 case FIELD_REQUEST_REMOVE_RESET:
261                     // find line and delete it
262                     row = this.find_row(data.value);
263                     if (row)
264                         this.table.fnDeleteRow(row.nTr);
265                         $("#badge-pending").data('number', $("#badge-pending").data('number') - 1 );
266                         $("#badge-pending").text($("#badge-pending").data('number'));
267                     return;
268                 case FIELD_REQUEST_CHANGE:
269                     action = 'UPDATE';
270                     break;
271                 case FIELD_REQUEST_ADD:
272                     action = 'ADD';
273                     break;
274                 case FIELD_REQUEST_REMOVE:
275                     action = 'REMOVE';
276                     break;
277             }
278
279             switch(data.status) {
280                 case FIELD_REQUEST_PENDING:
281                     msg   = 'PENDING';
282                     button = "<span class='glyphicon glyphicon-remove ResourceSelectedClose' id='" + data.key + "'/>";
283                     break;
284                 case FIELD_REQUEST_SUCCESS:
285                     msg   = 'SUCCESS';
286                     break;
287                 case FIELD_REQUEST_FAILURE:
288                     msg   = 'FAILURE';
289                     break;
290             }
291
292             var status = msg + status;
293
294             
295
296             // find line
297             // if no, create it, else replace it
298             // XXX it's not just about adding lines, but sometimes removing some
299             // XXX how do we handle status reset ?
300             data.value = JSON.stringify(data.value);
301             data.selected_resources = this.selected_resources;
302             row = this.find_row(data.value);
303             newline = [
304                 action,
305                 data.key,
306                 data.value,
307                 msg,
308                 button
309             ];
310             if (!row) {
311                 // XXX second parameter refresh = false can improve performance. todo in querytable also
312                 this.table.fnAddData(newline);
313                 row = this.find_row(data.value);
314                 $("#badge-pending").data('number', $("#badge-pending").data('number') + 1 );
315                 $("#badge-pending").text($("#badge-pending").data('number'));
316             } else {
317                 // Update row text...
318                 this.table.fnUpdate(newline, row.nTr);
319             }
320
321             // Change cell color according to status
322             if (row) {
323                 $(row.nTr).removeClass('add remove')
324                 var cls = action.toLowerCase();
325                 if (cls)
326                     $(row.nTr).addClass(cls);
327             }
328         },
329
330         /*************************** QUERY HANDLER ****************************/
331
332         // NONE
333
334         /*************************** RECORD HANDLER ***************************/
335
336         on_new_record: function(record)
337         {
338             console.log("query_updater on_new_record");
339             console.log(record);
340
341             // if (not and update) {
342
343                 // initial['resource'], initial['lease'] ?
344                 this.initial.push(record);
345
346             //this.set_record_state(record, RECORD_STATE_ATTACHED);
347                 // We simply add to the table
348             // } else {
349                 //                 \ this.initial_resources
350                 //                  \
351                 // this.             \
352                 // current_resources  \    YES    |   NO
353                 // --------------------+----------+---------
354                 //       YES           | attached | added
355                 //       NO            | removed  |   /
356                 // 
357
358             // }
359         },
360
361         // QUERY STATUS
362         //                                      +-----------------+--------------+
363         //                                      v        R        |              |
364         // +-------+  ?G    +-------+        +-------+        +---+---+          |
365         // |       | -----> |       |  !G    |       |        |       |    DA    |
366         // |  ND   |        |  PG   | -----> |   D   | -----> |  PC   | <------+ |
367         // |       | <----- |       |  ~G    |       |   C    |       |        | | 
368         // +-------+   GE   +-------+        +-------+        +-------+      +------+
369         //                                       ^              ^  |         |      |
370         //                                       | DA        UE |  | ?U      | PCA  |
371         //                                       |              |  v         |      |
372         //                                   +-------+        +-------+      +------+
373         //                                   |       |   !U   |       |         ^
374         //                                   |  AD   | <----- |  PU   | --------+
375         //                                   |       |        |       |   ~U     
376         //                                   +-------+        +-------+          
377         //                                                                       
378         //
379         // LEGEND:
380         // 
381         // Plugins (i) receive state information, (ii) perform actions
382         //
383         // States:                                  Actions:
384         // ND : No data                             ?G : Get query
385         // PG : Pending Get                         !G : Get reply  
386         //  D : Data present                        ~G : Get partial reply
387         // PC : Pending changes                     GE : Get error                            
388         // PU : Pending update                       C : Change request
389         // PCA: Pending change with annotation       R : Reset request
390         // AD : Annotated data                      ?U : Update query
391         //                                          !U : Update reply
392         //                                          ~U : Update partial reply
393         //                                          UE : Update error            
394         //                                          DA : Delete annotation request
395         // NOTE:
396         // - D -> PU directly if the user chooses 'dynamic update'
397         // - Be careful for updates if partial Get success
398
399         // ND: No data == initialization state
400         
401         // PG : Pending get
402         // - on_query_in_progress
403         // NOTE: cannot distinguish get and update here. Is it important ?
404
405         on_query_in_progress: function()
406         {
407                 messages.debug("queryupdater.on_query_in_progress");
408             this.spin();
409         },
410
411         // D : Data present
412         // - on_clear_records (Get)
413         // - on_new_record (shared with AD) XXX
414         // - on_query_done
415         // NOTE: cannot distinguish get and update here. Is it important ?
416         // NOTE: Would record key be sufficient for update ?
417
418         on_clear_records: function()
419         {
420             this.clear();
421         },
422
423         on_query_done: function()
424         {
425             console.log("on_query_done");
426             this.unspin();
427         },
428
429         // PC : Pending changes
430         // NOTE: record_key could be sufficient 
431         on_added_record: function(record)
432         {
433             console.log("on_added_record = ",record);
434             this.set_record_state(record, RECORD_STATE_ADDED);
435             // update pending number
436         },
437
438         on_removed_record: function(record_key)
439         {
440             console.log("on_removed_record = ",record_key);
441             this.set_record_state(RECORD_STATE_REMOVED);
442         },
443
444         // PU : Pending update
445         // - on_query_in_progress (already done)
446         
447         // PCA : Pending change with annotation
448         // NOTE: Manifold will inform the plugin about updates, and thus won't
449         // call new record, even if the same channel UUID is used...
450         // - TODO on_updated_record
451         // - Key and confirmation could be sufficient, or key and record state
452         // XXX move record state to the manifold plugin API
453
454         on_field_state_changed: function(result)
455         {
456             console.log("on_field_state_changed");
457             console.log(result);
458             if(result.request == FIELD_REQUEST_ADD){
459                 this.selected_resources.push(result.value);
460             } else if(result.request == FIELD_REQUEST_REMOVE_RESET){
461                 var i = this.selected_resources.indexOf(result.value);
462                 if(i != -1){
463                     this.selected_resources.splice(i,1);
464                 }
465             }
466             console.log("Resources: " + self.selected_resources);
467             messages.debug(result)
468             /* this.set_state(result.request, result.key, result.value, result.status); */
469             this.set_state(result);
470         },
471
472         // XXX we will have the requests for change
473         // XXX + the requests to move into the query cycle = the buttons aforementioned
474
475         // XXX what happens in case of updates ? not implemented yet
476         // XXX we want resources and leases
477         // listen for SET_ADD and SET_REMOVE for slice query
478
479         /************************** PRIVATE METHODS ***************************/
480
481         _close_click: function(e)
482         {
483             var self = e.data;
484
485             //jQuery.publish('selected', 'add/'+key_value);
486             // this.parentNode is <td> this.parentNode.parentNode is <tr> 
487             // this.parentNode.parentNode.firstChild is the first cell <td> of this line <tr>
488             // this.parentNode.parentNode.firstChild.firstChild is the text in that cell
489             //var firstCellVal=this.parentNode.parentNode.firstChild.firstChild.data;
490             var remove_urn = this.id; 
491             var current_resources = event.data.instance.current_resources;
492             var list_resources = $.grep(current_resources, function(x) {return x.urn != remove_urn});
493             //jQuery.publish('selected', 'cancel/'+this.id+'/'+unfold.get_value(firstCellVal));
494             $.publish('/update-set/' + event.data.instance.options.resource_query_uuid, [list_resources, true]);
495         },
496
497         /******************************** TODO ********************************/
498
499         update_resources: function(resources, change)
500         {
501             messages.debug("update_resources");
502             var my_oTable = this.table.dataTable();
503             var prev_resources = this.current_resources; 
504
505             /*
506              * The first time the query is advertised, don't do anything.  The
507              * component will learn nodes in the slice through the manifest
508              * received through the other subscription 
509              */
510              if (!change)
511                 return;
512              // ioi: Refubrished
513              var initial = this.initial;
514              //var r_removed  = []; //
515              /*-----------------------------------------------------------------------
516                 TODO: remove this dirty hack !!!
517              */
518              resources = jQuery.map(resources, function(x){
519                 if(!('timeslot' in x)){x.timeslot=0;}
520                 return x;
521              });
522              /*
523                 TODO: handle generic keys instead of specific stuff
524                       ex: urn
525                           urn-lease
526              */
527              var initial_urn = $.map(initial, function(x){return x.urn;});
528              var resources_urn = $.map(resources, function(x){return x.urn;});
529              var r_removed = $.grep(initial, function (x) { return $.inArray(x.urn, resources_urn) == -1 });
530              var r_attached = $.grep(initial, function (x) { return $.inArray(x.urn, resources_urn) > -1 });
531              var r_added = $.grep(resources, function (x) { return $.inArray(x.urn, initial_urn) == -1 });
532              exists = false; // ioi
533              /*-----------------------------------------------------------------------*/
534
535              my_oTable.fnClearTable();
536              /*
537                 TODO: factorization of this code !!!
538              */
539              $.each(r_added, function(i, r) { 
540                 //var type = (typeof initial == 'undefined' || r.node != initial.node) ? 'add' : 'attached';
541                 var type = 'add';  
542                 // Create the resource objects
543                 // ioi: refubrished
544                 var urn = r.urn;
545                 time = r.timeslot;
546                               
547                 var SPAN = "<span class='glyphicon glyphicon-remove ResourceSelectedClose' id='"+urn+"'/>";
548                 var slot = "<span id='resource_"+urn+"'>" + time + "</span>"; //ioi
549                 // ioi
550                 var newline=Array();
551                 newline.push(type, urn, slot, SPAN); // ioi
552                 var line = my_oTable.fnAddData(newline);
553                 var nTr = my_oTable.fnSettings().aoData[ line[0] ].nTr;
554                 nTr.className = type;
555              });
556              $.each(r_attached, function(i, r) {  
557                 //var type = (typeof initial == 'undefined' || r.node != initial.node) ? 'add' : 'attached';
558                 var type = 'attached';
559                 // Create the resource objects
560                 // ioi: refubrished
561                 var node = r.urn;
562                 time = r.timeslot;
563
564                 var SPAN = "<span class='glyphicon glyphicon-renomve ResourceSelectedClose' id='"+node+"'/>";
565                 var slot = "<span id='resource_"+node+"'>" + time + "</span>"; //ioi
566                 // ioi
567                 var newline=Array();
568                 newline.push(type, node, slot, SPAN); // ioi
569                 var line = my_oTable.fnAddData(newline);
570                 var nTr = my_oTable.fnSettings().aoData[ line[0] ].nTr;
571                 nTr.className = type;
572              });
573              $.each(r_removed, function(i, r) { 
574                 // The list contains objects
575                 // ioi: refubrished
576                 var node = r.urn;
577                 var time = r.timeslot;
578                     
579                 var SPAN = "<span class='glyphicon glyphicon-remove ResourceSelectedClose' id='"+node+"'/>";
580                 var slot = "<span id='resource_"+node+"'>" + time + "</span>";
581                 // ioi
582                 var newline=Array();
583                 newline.push('remove', node, slot, SPAN); // ioi
584                 var line = my_oTable.fnAddData(newline);
585                 var nTr = my_oTable.fnSettings().aoData[ line[0] ].nTr;
586                 nTr.className = 'remove';
587              });
588
589              this.current_resources = $.merge(r_attached,r_added);
590
591              /* Allow the user to update the slice */
592              //jQuery('#updateslice-' + data.ResourceSelected.plugin_uuid).prop('disabled', false);
593
594         }, // update_resources
595
596     });
597
598     $.plugin('QueryUpdater', QueryUpdater);
599
600 })(jQuery);