SLA update to see if it fixes something
[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 = Array();
81             var count = 0;
82             // XXX check that the query is not disabled
83
84             console.log("DATA VALUE: " + data.value);
85             
86             //<p>SLA description</p>
87             //<p>Testbed guarantees 0.99 Uptime rate for 0.99 rate of the VirtualWall resources during the sliver lifetime</p>
88             //<p>SLA description</p>
89             //<p>Testbed guarantees 0.99 Uptime rate for 0.99 rate of the WiLab2 resources during the sliver lifetime</p>
90             var promt = $('#modal-body');
91             
92             // id="myModalLabel"
93             var flagVW = false;
94             var  flagWi = false;
95
96             var wilabForm = "";
97             var wimessage = '<p>SLA description</p><p>to be deployed</p>';
98             for(var iter = 0; iter < arrayselectedresources.length; iter++){
99                 var list = '<p class="wi'+iter+'" name=wi"'+iter+'">'+arrayselectedresources[iter].toLowerCase()+'</p><br>';
100                 
101
102                 if (arrayselectedresources[iter].toLowerCase().indexOf("wilab2") >= 0){
103
104                     accepted_sla.push({"wilab2":false}); 
105                     wilabForm += list;   
106                     flagWi = true;             
107
108                 }
109
110             }
111
112             //var wallmessage = '<p>SLA description</p><p>Testbed guarantees 0.99 Uptime rate for 0.99 rate of the VirtualWall resources during the sliver lifetime</p>';
113
114             var wallForm = "";
115             for(var iter = 0; iter < arrayselectedresources.length; iter++){
116                 var list = '<class="wall'+iter+'" name=wall"'+iter+'" >'+arrayselectedresources[iter].toLowerCase()+'</p><br>';
117                 
118                 if (arrayselectedresources[iter].toLowerCase().indexOf("wall2") >= 0){
119
120                     accepted_sla.push({"wall2":false});
121                     wallForm += list;
122                     flagVW = true;
123                     
124                 }
125
126             }
127             promt.append(wimessage);
128             var flagDouble = false;
129             if(flagWi)
130             {
131                 flagDouble = true;
132                 promt.append(wilabForm);
133             }
134             if(flagVW)
135             {
136                 //promt.append(wallmessage);
137                 flagDouble = true;
138                 promt.append(wallForm);
139             }
140
141                         
142             // var wimessage = '<p>SLA description</p><p>Testbed guarantees 0.99 Uptime rate for 0.99 rate of the VirtualWall resources during the sliver lifetime</p>'
143
144                 $('#sla_dialog').show();
145                     $('#slamodal-wilab2').modal('show');
146                     
147                     
148                         $("#accept_sla_wilab2").click(function(){
149                             console.log("SLA ACCEPTED");
150                             console.log("With username: " + username);
151
152                             // var promt = $('#modal-body');
153                             // var notchecked = true;
154                             // for (var i=0;i<50;i++)
155                             // {
156                             //     var wielement = $('#wi'+i);
157                             //     var wallElement = $('#wall'+i);
158                             //     if(wielement != null && !wielement.checked)
159                             //     {
160                             //         notchecked = false;
161                             //     }
162                             //     if(wallElement!= null && !wallElement.checked)
163                             //     {
164                             //         notchecked = false;
165                             //     }
166                             // }
167             
168                                                        
169                                 if(flagDouble)
170                                 {
171                                     $.post("/sla/agreements/simplecreate", 
172                                         { "template_id": "iMindsServiceWiLab2",
173                                           "user": username,
174                                           "expiration_time": new Date().toISOString()
175                                        });
176                                      $.post("/sla/agreements/simplecreate", 
177                                         { "template_id": "iMindsServiceVirtualwall",
178                                           "user": username,
179                                           "expiration_time": new Date().toISOString()
180                                        });
181                             
182                                     $('#slamodal-wilab2').modal('hide');
183                                 accepted_sla["wilab2"] = true;
184                             
185                                 this.do_update(e);
186                             }
187                         }); 
188                     
189                         $("#dismiss_sla_wilab2").click(function(){
190                             console.log("SLA NOT ACCEPTED");
191                             $('#slamodal-wilab2').modal('hide');
192                         }); 
193
194             // for(var iter = 0; iter < arrayselectedresources.length; iter++){
195             //     var list = '<input type="checkbox" name="'+iter+'" >'+arrayselectedresources[iter].toLowerCase()+'<br>';
196             //     promt.append(list);
197             //     if (arrayselectedresources[iter].toLowerCase().indexOf("wall2") >= 0){
198
199
200                     
201             //         accepted_sla.push({"wall2":false});
202
203             //         $('#sla_dialog').show();
204             //         $('#slamodal-virtualwall').modal('show');
205                     
206                     
207             //             $("#accept_sla_vwall").click(function(){
208             //                 console.log("SLA ACCEPTED");
209             //                 console.log("With username: " + username);
210                         
211             //                 $.post("/sla/agreements/simplecreate", 
212             //                     { "template_id": "iMindsServiceVirtualwall",
213             //                       "user": username,
214             //                       "expiration_time": new Date()
215             //                     });
216                         
217             //                 $('#slamodal-virtualwall').modal('hide');
218             //                 accepted_sla["wall2"] = true;
219             //             }); 
220
221             //             $("#dismiss_sla_vwall").click(function(){
222             //                 console.log("SLA NOT ACCEPTED");
223             //                 $('#slamodal-vir').modal('hide');
224             //             }); 
225                     
226             //     }
227
228             //     if (arrayselectedresources[iter].toLowerCase().indexOf("wilab2") >= 0){
229
230             //         accepted_sla.push({"wilab2":false});
231
232             //         $('#sla_dialog').show();
233             //         $('#slamodal-wilab2').modal('show');
234                     
235                     
236             //             $("#accept_sla_wilab2").click(function(){
237             //                 console.log("SLA ACCEPTED");
238             //                 console.log("With username: " + username);
239                         
240             //                 $.post("/sla/agreements/simplecreate", 
241             //                     { "template_id": "iMindsServiceWiLab2",
242             //                       "user": username,
243             //                       "expiration_time": new Date()
244             //                     });
245                         
246             //                 $('#slamodal-wilab2').modal('hide');
247             //                 accepted_sla["wilab2"] = true;
248             //             }); 
249                     
250             //             $("#dismiss_sla_wilab2").click(function(){
251             //                 console.log("SLA NOT ACCEPTED");
252             //                 $('#slamodal-wilab2').modal('hide');
253             //             }); 
254                     
255
256             //     }
257
258             // }
259
260             // for(var sla in accepted_sla){
261             //     if(accepted_sla[sla] == true){
262             //         count += 1;
263             //     }
264             // }
265
266             // if(count == accepted_sla.length){
267             //     this.do_update(e);
268             // }
269         },
270
271      
272         do_update: function(e) {
273             var self = e.data;
274
275             var username = e.data.options.username;
276             var urn = data.value;
277             // XXX check that the query is not disabled
278
279             self.spin();
280             console.log("do_update");
281             // XXX check that the query is not disabled
282             //manifold.raise_event(self.options.query_uuid, RUN_UPDATE);
283
284             // how to stop the spinning after the event? 
285             // this should be triggered by some on_updatequery_done ?
286
287         },
288
289         // related buttons are also disabled in the html template
290         do_refresh: function(e)
291         {
292             throw 'resource_selected.do_refresh Not implemented';
293         },
294
295         do_reset: function(e)
296         {
297             throw 'queryupdater.do_reset Not implemented';
298         },
299
300         do_clear_annotations: function(e)
301         {
302             throw 'queryupdater.do_clear_annotations Not implemented';
303         },
304         
305         /************************** GUI MANIPULATION **************************/
306
307         
308         set_button_state: function(name, state)
309         {
310             this.elmt(name).attr('disabled', state ? false : 'disabled');
311         },
312
313         clear: function()
314         {
315
316         },
317
318         find_row: function(key)
319         {
320             // key in third position, column id = 2
321             var KEY_POS = 2;
322
323             var cols = $.grep(this.table.fnSettings().aoData, function(col) {
324                 return (col._aData[KEY_POS] == key);
325             } );
326
327             if (cols.length == 0)
328                 return null;
329             if (cols.length > 1)
330                 throw "Too many same-key rows in ResourceSelected plugin";
331
332             return cols[0];
333         },
334
335         set_state: function(data)
336         {
337             console.log("function set_state");
338             var action;
339             var msg;
340             var button = '';
341
342             var row;
343             
344             // make sure the change is visible : toggle on the whole plugin
345             // this might have to be made an 'auto-toggle' option of this plugin..
346             // also it might be needed to be a little finer-grained here
347
348         // XXX we don't want to show automaticaly the pending when a checkbox is checked
349             //this.toggle_on();
350             
351             switch(data.request) {
352                 case FIELD_REQUEST_ADD_RESET:
353                 case FIELD_REQUEST_REMOVE_RESET:
354                     // find line and delete it
355                     row = this.find_row(data.value);
356                     if (row)
357                         this.table.fnDeleteRow(row.nTr);
358                         $("#badge-pending").data('number', $("#badge-pending").data('number') - 1 );
359                         $("#badge-pending").text($("#badge-pending").data('number'));
360                     return;
361                 case FIELD_REQUEST_CHANGE:
362                     action = 'UPDATE';
363                     break;
364                 case FIELD_REQUEST_ADD:
365                     action = 'ADD';
366                     break;
367                 case FIELD_REQUEST_REMOVE:
368                     action = 'REMOVE';
369                     break;
370             }
371
372             switch(data.status) {
373                 case FIELD_REQUEST_PENDING:
374                     msg   = 'PENDING';
375                     button = "<span class='glyphicon glyphicon-remove ResourceSelectedClose' id='" + data.key + "'/>";
376                     break;
377                 case FIELD_REQUEST_SUCCESS:
378                     msg   = 'SUCCESS';
379                     break;
380                 case FIELD_REQUEST_FAILURE:
381                     msg   = 'FAILURE';
382                     break;
383             }
384
385             var status = msg + status;
386
387             
388
389             // find line
390             // if no, create it, else replace it
391             // XXX it's not just about adding lines, but sometimes removing some
392             // XXX how do we handle status reset ?
393             data.value = JSON.stringify(data.value);
394             data.selected_resources = this.selected_resources;
395             row = this.find_row(data.value);
396             newline = [
397                 action,
398                 data.key,
399                 data.value,
400                 msg,
401                 button
402             ];
403             if (!row) {
404                 // XXX second parameter refresh = false can improve performance. todo in querytable also
405                 this.table.fnAddData(newline);
406                 row = this.find_row(data.value);
407                 $("#badge-pending").data('number', $("#badge-pending").data('number') + 1 );
408                 $("#badge-pending").text($("#badge-pending").data('number'));
409             } else {
410                 // Update row text...
411                 this.table.fnUpdate(newline, row.nTr);
412             }
413
414             // Change cell color according to status
415             if (row) {
416                 $(row.nTr).removeClass('add remove')
417                 var cls = action.toLowerCase();
418                 if (cls)
419                     $(row.nTr).addClass(cls);
420             }
421         },
422
423         /*************************** QUERY HANDLER ****************************/
424
425         // NONE
426
427         /*************************** RECORD HANDLER ***************************/
428
429         on_new_record: function(record)
430         {
431             console.log("query_updater on_new_record");
432             console.log(record);
433
434             // if (not and update) {
435
436                 // initial['resource'], initial['lease'] ?
437                 this.initial.push(record);
438
439             //this.set_record_state(record, RECORD_STATE_ATTACHED);
440                 // We simply add to the table
441             // } else {
442                 //                 \ this.initial_resources
443                 //                  \
444                 // this.             \
445                 // current_resources  \    YES    |   NO
446                 // --------------------+----------+---------
447                 //       YES           | attached | added
448                 //       NO            | removed  |   /
449                 // 
450
451             // }
452         },
453
454         // QUERY STATUS
455         //                                      +-----------------+--------------+
456         //                                      v        R        |              |
457         // +-------+  ?G    +-------+        +-------+        +---+---+          |
458         // |       | -----> |       |  !G    |       |        |       |    DA    |
459         // |  ND   |        |  PG   | -----> |   D   | -----> |  PC   | <------+ |
460         // |       | <----- |       |  ~G    |       |   C    |       |        | | 
461         // +-------+   GE   +-------+        +-------+        +-------+      +------+
462         //                                       ^              ^  |         |      |
463         //                                       | DA        UE |  | ?U      | PCA  |
464         //                                       |              |  v         |      |
465         //                                   +-------+        +-------+      +------+
466         //                                   |       |   !U   |       |         ^
467         //                                   |  AD   | <----- |  PU   | --------+
468         //                                   |       |        |       |   ~U     
469         //                                   +-------+        +-------+          
470         //                                                                       
471         //
472         // LEGEND:
473         // 
474         // Plugins (i) receive state information, (ii) perform actions
475         //
476         // States:                                  Actions:
477         // ND : No data                             ?G : Get query
478         // PG : Pending Get                         !G : Get reply  
479         //  D : Data present                        ~G : Get partial reply
480         // PC : Pending changes                     GE : Get error                            
481         // PU : Pending update                       C : Change request
482         // PCA: Pending change with annotation       R : Reset request
483         // AD : Annotated data                      ?U : Update query
484         //                                          !U : Update reply
485         //                                          ~U : Update partial reply
486         //                                          UE : Update error            
487         //                                          DA : Delete annotation request
488         // NOTE:
489         // - D -> PU directly if the user chooses 'dynamic update'
490         // - Be careful for updates if partial Get success
491
492         // ND: No data == initialization state
493         
494         // PG : Pending get
495         // - on_query_in_progress
496         // NOTE: cannot distinguish get and update here. Is it important ?
497
498         on_query_in_progress: function()
499         {
500                 messages.debug("queryupdater.on_query_in_progress");
501             this.spin();
502         },
503
504         // D : Data present
505         // - on_clear_records (Get)
506         // - on_new_record (shared with AD) XXX
507         // - on_query_done
508         // NOTE: cannot distinguish get and update here. Is it important ?
509         // NOTE: Would record key be sufficient for update ?
510
511         on_clear_records: function()
512         {
513             this.clear();
514         },
515
516         on_query_done: function()
517         {
518             console.log("on_query_done");
519             this.unspin();
520         },
521
522         // PC : Pending changes
523         // NOTE: record_key could be sufficient 
524         on_added_record: function(record)
525         {
526             console.log("on_added_record = ",record);
527             this.set_record_state(record, RECORD_STATE_ADDED);
528             // update pending number
529         },
530
531         on_removed_record: function(record_key)
532         {
533             console.log("on_removed_record = ",record_key);
534             this.set_record_state(RECORD_STATE_REMOVED);
535         },
536
537         // PU : Pending update
538         // - on_query_in_progress (already done)
539         
540         // PCA : Pending change with annotation
541         // NOTE: Manifold will inform the plugin about updates, and thus won't
542         // call new record, even if the same channel UUID is used...
543         // - TODO on_updated_record
544         // - Key and confirmation could be sufficient, or key and record state
545         // XXX move record state to the manifold plugin API
546
547         on_field_state_changed: function(result)
548         {
549             console.log("on_field_state_changed");
550             console.log(result);
551             if(result.request == FIELD_REQUEST_ADD){
552                 this.selected_resources.push(result.value);
553             } else if(result.request == FIELD_REQUEST_REMOVE_RESET){
554                 var i = this.selected_resources.indexOf(result.value);
555                 if(i != -1){
556                     this.selected_resources.splice(i,1);
557                 }
558             }
559             console.log("Resources: " + self.selected_resources);
560             messages.debug(result)
561             /* this.set_state(result.request, result.key, result.value, result.status); */
562             this.set_state(result);
563         },
564
565         // XXX we will have the requests for change
566         // XXX + the requests to move into the query cycle = the buttons aforementioned
567
568         // XXX what happens in case of updates ? not implemented yet
569         // XXX we want resources and leases
570         // listen for SET_ADD and SET_REMOVE for slice query
571
572         /************************** PRIVATE METHODS ***************************/
573
574         _close_click: function(e)
575         {
576             var self = e.data;
577
578             //jQuery.publish('selected', 'add/'+key_value);
579             // this.parentNode is <td> this.parentNode.parentNode is <tr> 
580             // this.parentNode.parentNode.firstChild is the first cell <td> of this line <tr>
581             // this.parentNode.parentNode.firstChild.firstChild is the text in that cell
582             //var firstCellVal=this.parentNode.parentNode.firstChild.firstChild.data;
583             var remove_urn = this.id; 
584             var current_resources = event.data.instance.current_resources;
585             var list_resources = $.grep(current_resources, function(x) {return x.urn != remove_urn});
586             //jQuery.publish('selected', 'cancel/'+this.id+'/'+unfold.get_value(firstCellVal));
587             $.publish('/update-set/' + event.data.instance.options.resource_query_uuid, [list_resources, true]);
588         },
589
590         /******************************** TODO ********************************/
591
592         update_resources: function(resources, change)
593         {
594             messages.debug("update_resources");
595             var my_oTable = this.table.dataTable();
596             var prev_resources = this.current_resources; 
597
598             /*
599              * The first time the query is advertised, don't do anything.  The
600              * component will learn nodes in the slice through the manifest
601              * received through the other subscription 
602              */
603              if (!change)
604                 return;
605              // ioi: Refubrished
606              var initial = this.initial;
607              //var r_removed  = []; //
608              /*-----------------------------------------------------------------------
609                 TODO: remove this dirty hack !!!
610              */
611              resources = jQuery.map(resources, function(x){
612                 if(!('timeslot' in x)){x.timeslot=0;}
613                 return x;
614              });
615              /*
616                 TODO: handle generic keys instead of specific stuff
617                       ex: urn
618                           urn-lease
619              */
620              var initial_urn = $.map(initial, function(x){return x.urn;});
621              var resources_urn = $.map(resources, function(x){return x.urn;});
622              var r_removed = $.grep(initial, function (x) { return $.inArray(x.urn, resources_urn) == -1 });
623              var r_attached = $.grep(initial, function (x) { return $.inArray(x.urn, resources_urn) > -1 });
624              var r_added = $.grep(resources, function (x) { return $.inArray(x.urn, initial_urn) == -1 });
625              exists = false; // ioi
626              /*-----------------------------------------------------------------------*/
627
628              my_oTable.fnClearTable();
629              /*
630                 TODO: factorization of this code !!!
631              */
632              $.each(r_added, function(i, r) { 
633                 //var type = (typeof initial == 'undefined' || r.node != initial.node) ? 'add' : 'attached';
634                 var type = 'add';  
635                 // Create the resource objects
636                 // ioi: refubrished
637                 var urn = r.urn;
638                 time = r.timeslot;
639                               
640                 var SPAN = "<span class='glyphicon glyphicon-remove ResourceSelectedClose' id='"+urn+"'/>";
641                 var slot = "<span id='resource_"+urn+"'>" + time + "</span>"; //ioi
642                 // ioi
643                 var newline=Array();
644                 newline.push(type, urn, slot, SPAN); // ioi
645                 var line = my_oTable.fnAddData(newline);
646                 var nTr = my_oTable.fnSettings().aoData[ line[0] ].nTr;
647                 nTr.className = type;
648              });
649              $.each(r_attached, function(i, r) {  
650                 //var type = (typeof initial == 'undefined' || r.node != initial.node) ? 'add' : 'attached';
651                 var type = 'attached';
652                 // Create the resource objects
653                 // ioi: refubrished
654                 var node = r.urn;
655                 time = r.timeslot;
656
657                 var SPAN = "<span class='glyphicon glyphicon-renomve ResourceSelectedClose' id='"+node+"'/>";
658                 var slot = "<span id='resource_"+node+"'>" + time + "</span>"; //ioi
659                 // ioi
660                 var newline=Array();
661                 newline.push(type, node, slot, SPAN); // ioi
662                 var line = my_oTable.fnAddData(newline);
663                 var nTr = my_oTable.fnSettings().aoData[ line[0] ].nTr;
664                 nTr.className = type;
665              });
666              $.each(r_removed, function(i, r) { 
667                 // The list contains objects
668                 // ioi: refubrished
669                 var node = r.urn;
670                 var time = r.timeslot;
671                     
672                 var SPAN = "<span class='glyphicon glyphicon-remove ResourceSelectedClose' id='"+node+"'/>";
673                 var slot = "<span id='resource_"+node+"'>" + time + "</span>";
674                 // ioi
675                 var newline=Array();
676                 newline.push('remove', node, slot, SPAN); // ioi
677                 var line = my_oTable.fnAddData(newline);
678                 var nTr = my_oTable.fnSettings().aoData[ line[0] ].nTr;
679                 nTr.className = 'remove';
680              });
681
682              this.current_resources = $.merge(r_attached,r_added);
683
684              /* Allow the user to update the slice */
685              //jQuery('#updateslice-' + data.ResourceSelected.plugin_uuid).prop('disabled', false);
686
687         }, // update_resources
688
689     });
690
691     $.plugin('QueryUpdater', QueryUpdater);
692
693 })(jQuery);