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