added scheduler to slice view
[myslice.git] / plugins / scheduler / static / js / scheduler.js
1 /**
2  * Description: display a query result in a Google map
3  * Copyright (c) 2012-2013 UPMC Sorbonne Universite - INRIA
4  * License: GPLv3
5  */
6
7 /* based on the leases.js code in PLE WWW interface for MyPLC by Thierry Parmentelat -- INRIA */
8
9 /* XXX Those declarations should not be part of the js file... */
10
11 /* decorations / headers */
12 /* note: looks like the 'font' attr is not effective... */
13
14 // vertical rules
15 var attr_rules={'fill':"#888", 'stroke-dasharray':'- ', 'stroke-width':0.5};
16 // set font-size separately in here rather than depend on the height
17 var txt_timelabel = {"font": 'Times, "Trebuchet MS", Verdana, Arial, Helvetica, sans-serif', 
18              stroke: "none", fill: "#008", 'font-size': 9};
19 var txt_allnodes = {"font": '"Trebuchet MS", Verdana, Arial, Helvetica, sans-serif', stroke: "none", fill: "#404"};
20 var txt_nodelabel = {"font": '"Trebuchet MS", Verdana, Arial, Helvetica, sans-serif', stroke: "none", fill: "#008"};
21
22 var attr_timebutton = {'fill':'#bbf', 'stroke': '#338','stroke-width':1, 
23                'stroke-linecap':'round', 'stroke-linejoin':'miter', 'stroke-miterlimit':3};
24 var attr_daymarker = {'stroke':'#000','stroke-width':2};
25 var attr_half_daymarker = {'stroke':'#444','stroke-width':2};
26
27 /* lease dimensions and colors */
28 /* refrain from using gradient color, seems to not be animated properly */
29 /* lease was originally free and is still free */
30 var attr_lease_free_free={'fill':"#def", 'stroke-width':0.5, 'stroke-dasharray':''};
31 /* lease was originally free and is now set for our usage */
32 var attr_lease_free_mine={'fill':"green", 'stroke-width':1, 'stroke-dasharray':'-..'};
33 /* was mine and is still mine */
34 var attr_lease_mine_mine={'fill':"#beb", 'stroke-width':0.5, 'stroke-dasharray':''};
35 /* was mine and is about to be released */
36 var attr_lease_mine_free={'fill':"white", 'stroke-width':1, 'stroke-dasharray':'-..'};
37 var attr_lease_other={'fill':"#f88"};
38
39 /* other slices name */
40 var txt_otherslice = {"font": '"Trebuchet MS", Verdana, Arial, Helvetica, sans-serif', stroke: "none", fill: "#444", "font-size": "12px"};
41
42 (function($){
43
44     var Scheduler = Plugin.extend({
45
46         init: function(options, element) 
47         {
48             this._super(options, element);
49
50             /* Member variables */
51             this.canvas_id = this.id('leases_area');
52
53             this.query_uuid = options.query_uuid;
54             this.rows = null;
55             // XXX TODEL
56             //this.current_resources = Array();
57             //this.current_leases = Array();
58
59             this.myLeases = Array();
60             this.allLeases = Array();
61
62             this.listLeases = Array();
63
64             this.axisx = Array();
65             this.axisy = Array();
66             this.data = Array();
67             this.default_granularity = 1800; /* 30 min */
68             this.initial_timestamp = null;
69
70             /* This should be updated to be the ppcm of all granularities */
71             this.min_granularity = this.default_granularity;
72
73             // the data contains slice names, and lease_id, we need this to find our own leases (mine)
74             this.paper=null;
75
76             /* XXX Events */
77
78             /* XXX Keys */
79
80             /* Listening to queries */
81             this.listen_query(options.query_uuid);
82             this.listen_query(options.query_lease_uuid);
83
84             /* XXX GUI setup and event binding */
85             jQuery("#datepicker").datetimepicker({
86                 //Timezone wise selection option
87                 //timeFormat: 'hh:mm tt z',
88                 //showTimezone: true,
89                 
90                 onSelect: function(value) { 
91                     //console.log(value);
92                     //converting time to timestamp
93                     currentDate= Math.round(Date.parse(value)/ 1000);
94                     // TODO -- DONE
95                     // convert value to timestamp --done
96                     // Get jQuery("#timepicker").val(); - no need anymore
97                     // convert timepicker into seconds - no need
98                     // Add time to date - done
99                     // pass the result to init_axisx - done
100                     //console.log(currentDate);
101                     s.clear();
102                     s.init_axisx(currentDate);
103                     s.draw();
104                     // Do we need to populate the timeslots with existing leases? 
105                     // Look how to populate with initial_leases [we have to show the leases]
106                     
107                 } 
108             });
109             //console.log(s.nodelabels[1]);
110             // Do we need to populate the timeslots with existing leases? 
111             // Look how to populate with initial_leases
112             
113             // TODO -- DONE  Note: autocomplete is not search box
114             // Implement a filtering functionality, on the name of the node
115             // http://jqueryui.com/autocomplete/
116             // pass s.nodelabels to autocomplete function
117             //jQuery("#search").autocomplete('s.nodelabel');
118             //console.log(s.nodelabel);
119             
120             /*
121              * TODO
122              * During init, there are no resources
123              * So the list of nodes is empty
124              * The function triggered by the subscription to the resources query
125              * var RESULTS_RESOURCES = '/results/' + options.resource_query_uuid + '/changed';
126              * $.subscribe(RESULTS_RESOURCES, function(e, resources) { s.set_resources(resources);   });
127              * Will have to update the list of nodes available through autocomplete (availableTags)
128              * 
129              * Be inspired by QueryEditor plugin
130              * 
131              * Resources informations in s.axisy ???
132              * 
133              * Filter what has been selected in other plugins:
134              * QueryEditor
135              * QuickFilter
136              * AdvancedFilter
137              * 
138              * Implement an action of filtering while typing
139              * filter what correspond to the user choice
140              * 
141             $(function() {
142                 var availableTags = ['omf','nitos','ple', s.nodelabel];
143             $( "#search" ).autocomplete({
144               source: availableTags
145                 });
146             });
147              */
148
149             this.init_axisx('');
150             this.draw();
151
152         }, /* init */
153
154         /* Default settings */
155         default_options: {
156             leases_offset:       0,
157             leases_slots:        36,
158             leases_w:            180,
159             leases_granularity:  3600,
160
161             x_nodelabel:         200,   /* space for the nodenames */
162             x_sep:               20,    /* right space after the nodename - removed from the above */
163             y_header:            12,    /* height for the (two) rows of timelabels */
164             y_sep:               10,    /* space between nodes */
165             leases_w:            20,    /* 1-grain leases attributes */
166             y_node:              15,
167             radius:              6,
168             anim_delay:          350,
169             checkboxes:          false,
170             resource_query_uuid: null,  /* resources */
171             lease_query_uuid:    null,  /* leases */
172         },
173
174         /* PLUGIN EVENTS */
175
176         /* GUI EVENTS */
177
178         /* GUI MANIPULATION */
179
180         /* TEMPLATES */
181
182         /* QUERY HANDLERS */
183
184         set_resources: function(resources) 
185         {
186             //console.log(resources);
187             var scheduler = this;
188             jQuery.each(resources, function(i, resource) {
189                 // ... add reservable ones to the x axis
190                 if ((typeof resource.exclusive != 'undefined') && (resource.exclusive)) {
191                     scheduler.axisy.push(Array(resource.urn, resource.resource_hrn, resource.type));
192                 }
193                 // ... if we do not have information about slivers (first update), update it
194                 if (typeof resource.sliver != 'undefined') {
195                     // XXX
196                 }
197             });
198
199             this.draw(this.canvas_id);
200         },
201
202         set_leases: function(leases) 
203         {
204             this.initial_leases=leases;
205             this.draw(this.canvas_id);
206         },
207
208         update_resources: function(resources) 
209         {
210             //
211         },
212
213         update_leases: function(leases)
214         {
215             //
216         },
217
218         /* RECORD HANDLERS */
219
220         /* INTERNAL FUNCTIONS */
221
222         /**
223          * @brief Return the number of time slots
224          */
225         nb_grains: function () 
226         {
227             return this.axisx.length; 
228         },
229
230         /**
231          * @brief Returns whether there is a pending lease at this timestamp
232          */
233         find_lease: function(urn, timestamp)
234         {
235             var scheduler = this;
236             var result = null;
237
238             $.each(Array(scheduler.myLeases, scheduler.allLeases), function(i, array) {
239                 $.each(array, function(i, lease) {
240                     if (lease[0] == urn) {
241                         if ((timestamp >= lease[1]) && (timestamp < (lease[1] + lease[2] * 1800))) {
242                             result = lease;
243                             
244                             return false;
245                         }
246                     }
247                 });
248                 if (result)
249                     return false;
250             });
251             return result;
252         },
253
254         /**
255          * @brief Draw
256          */
257         draw: function() 
258         { 
259             var canvas_id = this.canvas_id;
260             var o = this.options;
261             var total_width = o.x_nodelabel + this.nb_grains() * this.options.leases_w;
262             var total_height = 2 * o.y_header /* the timelabels */
263                              + 2 * o.y_sep    /* extra space */
264                              + o.y_node   /* all-nodes & timebuttons row */ 
265                              + (this.axisy.length)*(o.y_node+o.y_sep);  /* the regular nodes and preceding space */
266
267             /* reuse for paper if exists with same size, or (re-)create otherwise */
268             var paper;
269             if (this.paper == null) {
270                 paper = Raphael (canvas_id, total_width+o.x_sep, total_height);
271             } else if (this.paper.width==total_width && this.paper.height==total_height) {
272                 paper=this.paper;
273                 paper.clear();
274             } else {
275                 $$("#"+canvas_id)[0].innerHTML="";
276                 paper = Raphael (canvas_id, total_width+o.x_sep, total_height);
277             }
278             this.paper=paper;
279
280             /* the path for the triangle-shaped buttons */
281             this.timebutton_path = "M1,0L"+(this.options.leases_w-1)+",0L"+(this.options.leases_w/2)+","+o.y_header+"L1,0";
282
283             var axisx = this.axisx;
284             var axisy = this.axisy;
285
286             /* maintain the list of nodelabels for the 'all nodes' button */
287             this.nodelabels=[];
288             
289
290             /* create the time slots legend */
291             var top = 0;
292             var left = o.x_nodelabel;
293
294             var daymarker_height= 2*o.y_header + 2*o.y_sep + (axisy.length+1)*(o.y_node+o.y_sep);
295             var daymarker_path="M0,0L0," + daymarker_height;
296
297             var half_daymarker_off= 2*o.y_header + o.y_sep;
298             var half_daymarker_path="M0," + half_daymarker_off + "L0," + daymarker_height;
299
300             var col=0;
301             for (var i=0, len=axisx.length; i < len; ++i) {
302                 /* pick the printable part */
303                 var timelabel=axisx[i][1];
304                 var y = top + o.y_header;
305                 if (col%2 == 0) y += o.y_header;
306                 col +=1;
307                 /* display time label */
308                 var timelabel=paper.text(left,y,timelabel).attr(txt_timelabel).attr({"text-anchor":"middle"});
309                 /* draw vertical line */
310                 var path_spec="M"+left+" "+(y+o.y_header/2)+"L"+left+" "+this.total_height;
311                 var rule=paper.path(path_spec).attr(attr_rules);
312                 /* show a day marker when relevant */
313                 var timestamp=parseInt(axisx[i][0]);
314                 if ( (timestamp%(24*3600))==0) {
315                     paper.path(daymarker_path).attr({'translation':left+','+top}).attr(attr_daymarker);
316                 } else if ( (timestamp%(12*3600))==0) {
317                     paper.path(half_daymarker_path).attr({'translation':left+','+top}).attr(attr_daymarker);
318                 }
319                 left += this.options.leases_w;
320             }
321
322             ////////// the row with the timeslot buttons (the one labeled 'All nodes')
323             this.granularity= this.min_granularity; // XXX axisx[1][0]-axisx[0][0];
324
325             // move two lines down
326             top += 2*o.y_header + 2*o.y_sep;
327             left=o.x_nodelabel;
328             // all nodes buttons
329             var allnodes = paper.text (o.x_nodelabel-o.x_sep,top+o.y_node/2,"All nodes").attr(txt_allnodes)
330                 .attr ({"font-size":o.y_node, "text-anchor":"end","baseline":"bottom"});
331             allnodes.scheduler=this;
332             allnodes.click(this.allnodes_methods.click);
333             
334             // timeslot buttons [it's the triangles above the slots]
335             for (var i=0, len=axisx.length; i < len; ++i) {
336                 var timebutton=paper.path(this.timebutton_path).attr({'translation':left+','+top}).attr(attr_timebutton);
337                 timebutton.from_time=axisx[i][0];
338                 timebutton.scheduler=this;
339                 timebutton.click(this.timebutton_methods.click);
340                 left+=(this.options.leases_w);
341             }
342             
343             //////// the body of the scheduler : loop on nodes
344             top += o.y_node + o.y_sep;
345             var data_index=0;
346             this.leases=[];
347             for (var i=0, len=axisy.length; i<len; ++i) {
348                 var urn=axisy[i][0];
349                 var nodename=axisy[i][1];
350                 var type=axisy[i][2];
351                 left=0;            
352                 /*
353                  *  MODIFIED font-size
354                 var nodelabel = paper.text(o.x_nodelabel-x_sep,top+y_node/2,nodename).attr(txt_nodelabel)
355                 .attr ({"font-size":y_node, "text-anchor":"end","baseline":"bottom"});
356                 */
357                 var nodelabel = paper.text(o.x_nodelabel-o.x_sep,top+o.y_node/3,nodename).attr(txt_nodelabel)
358                 .attr ({"font-size":"12px", "text-anchor":"end","baseline":"bottom"});    
359                 //console.log(nodelabel);
360                 this.nodelabel_methods.selected(nodelabel,1);
361                 //nodelabel_methods.selected( this, ! this.selected );
362                 nodelabel.click(this.nodelabel_methods.click); //click action works here
363                 //timebutton.click(timebutton_methods.click);
364                 
365                // lease_methods.init_free(nodelabel.click, lease_methods.click_mine);
366                //lease_methods.init_free(nodelabel.lease);
367                 this.nodelabels.push(nodelabel);
368                 
369                 left += o.x_nodelabel;
370                 var grain=0;
371                 // data index contains the full array of leases
372                 // not the same amount of grains per node
373
374                 // NOTE: remembering the previous lease might help for long leases.
375                 while (grain < this.nb_grains()) {
376
377                     if (l = this.find_lease(urn, this.initial_timestamp + grain * 1800)) {
378                         slicename = l.slice_id;
379                     } else {
380                         slicename = "";
381                     }
382
383                     //lease_id  = this.data[data_index][0];
384                     //slicename = this.data[data_index][1];
385                     /* Duration should not be the lease duration, but the grain */
386                     var duration = 1; // this.data[data_index][2];
387
388                     var lease=paper.rect (left,top,this.options.leases_w*duration,o.y_node,o.radius);
389                     // record scheduler in lease - early as we need this in init_other
390                     lease.scheduler=this;
391                     //lease.lease_id=lease_id;
392                     lease.nodename=nodename;
393                     lease.urn=urn;
394                     lease.nodelabel=nodelabel;
395                     if (slicename == "") {
396                         lease.initial="free";
397                         lease_methods.init_free(lease);
398                     } else if (slicename == this.options.slicename) {
399                         lease.initial="mine";
400                         lease_methods.init_mine(lease);
401                     } else {
402                         lease.initial="other";
403                         lease_methods.init_other(lease,slicename);
404                     }
405                     lease.from_time = axisx[grain%this.nb_grains()][0];
406                     grain += duration;
407                     lease.until_time = axisx[grain%this.nb_grains()][0];
408                     // and vice versa
409                     this.leases.push(lease);
410                     // move on with the loop
411                     left += this.options.leases_w*duration;
412                     data_index +=1;
413                 }
414                 top += o.y_node + o.y_sep;
415             };
416         }, /* draw */
417
418         init_axisx: function(currentDate) 
419         {
420             this.axisx = Array();
421     
422             if(currentDate=="") {
423                 // creating timestamp of the current time
424                 currentDate = new Date().getTime() / 1000;
425             }
426             this.initial_timestamp = currentDate;
427             //console.log(currentDate);
428     
429             // round it by granularity (becomes an Int)
430             var rounded = Math.round(currentDate/this.min_granularity)*this.min_granularity;
431             // Convert Int to Date
432             rounded = new Date(rounded*1000);
433             // get hours and minutes in a 24h format 00:00
434             var roundedHours=(rounded.getHours()<10?'0':'') + rounded.getHours();
435             var roundedMinutes=(rounded.getMinutes()<10?'0':'') + rounded.getMinutes();
436     
437             //timeFrame.push(rounded);
438             this.axisx.push(Array(rounded, roundedHours+":"+roundedMinutes));
439     
440             // Generate as man slots as we need
441             for(i=0; i<this.options.leases_slots;i++) {
442                 rounded = this.min_granularity+(rounded.getTime()/1000);
443                 rounded = new Date(rounded*1000);
444                 roundedHours=(rounded.getHours()<10?'0':'') + rounded.getHours();
445                 roundedMinutes=(rounded.getMinutes()<10?'0':'') + rounded.getMinutes();
446     
447                 //timeFrame.push(rounded);
448                 this.axisx.push(Array(rounded, roundedHours+":"+roundedMinutes));
449             }
450         },
451
452         clear: function ()
453         {
454             for (var i=0, len=this.leases.length; i<len; ++i) {
455                 var lease=this.leases[i];
456                 if (lease.current != lease.initial) {
457                 if (lease.initial == 'free') lease_methods.init_free(lease,lease_methods.click_mine);
458                 else                         lease_methods.init_mine(lease,lease_methods.click_free);
459                 }
460             }
461         },
462
463         // XXX Couldn't find how to inhererit from the raphael objects...
464
465         /* ---------------------------------------------------------------------
466          * The 'all nodes' button
467          */
468         allnodes_methods: {
469             click: function (event) {
470                 var scheduler=this.scheduler;
471                 /* decide what to do */
472                 var unselected=0;
473                 for (var i=0, len=scheduler.nodelabels.length; i<len; ++i) 
474                     if (! scheduler.nodelabels[i].selected) unselected++;
475                 /* if at least one is not selected : select all */
476                 var new_state = (unselected >0) ? 1 : 0;
477                 for (var i=0, len=scheduler.nodelabels.length; i<len; ++i) 
478                     this.nodelabel_methods.selected(scheduler.nodelabels[i],new_state);
479             }
480         },
481
482         /* ---------------------------------------------------------------------
483          * The buttons for managing the whole timeslot
484          */
485         timebutton_methods: {
486
487             /* clicking */
488             click: function (event) {
489                 var scheduler = this.scheduler;
490                 var from_time = this.from_time;
491                 var until_time = from_time + scheduler.granularity;
492                 /* scan leases on selected nodes, store in two arrays */
493                 var relevant_free=[], relevant_mine=[];
494                 for (var i=0,len=scheduler.leases.length; i<len; ++i) {
495                     var scan=scheduler.leases[i];
496                     if ( ! scan.nodelabel.selected) continue;
497                     // overlap ?
498                     if (scan.from_time<=from_time && scan.until_time>=until_time) {
499                     if (scan.current == "free")       relevant_free.push(scan);
500                     else if (scan.current == "mine")  relevant_mine.push(scan);
501                     }
502                 }
503                 // window.console.log("Found " + relevant_free.length + " free and " + relevant_mine.length + " mine");
504                 /* decide what to do, whether book or release */
505                 if (relevant_mine.length==0 && relevant_free.length==0) {
506                     alert ("Nothing to do in this timeslot on the selected nodes");
507                     return;
508                 }
509                 // if at least one is free, let's book
510                 if (relevant_free.length > 0) {
511                     for (var i=0, len=relevant_free.length; i<len; ++i) {
512                         var lease=relevant_free[i];
513                         lease_methods.init_mine(lease,lease_methods.click_free);
514                     }
515                 // otherwise we unselect
516                 } else {
517                     for (var i=0, len=relevant_mine.length; i<len; ++i) {
518                         var lease=relevant_mine[i];
519                         lease_methods.init_free(lease,lease_methods.click_mine);
520                     }
521                 }
522             } /* click */
523         }, 
524
525         /* ---------------------------------------------------------------------
526          * The nodelabel buttons
527          */
528         nodelabel_methods: {
529             
530             // set selected mode and render visually
531             selected: function (nodelabel, flag) {
532                 nodelabel.selected=flag;
533                 nodelabel.attr({'font-weight': (flag ? 'bold' : 'normal')});
534                 // TODO
535                 // 
536                 // loop on axis x and select each timebutton
537                 // for (var i=0, len=axisx.length; i < len; ++i)
538                 // figure out how to use timebutton_methods.click();
539                     
540             },
541
542             // toggle selected
543             click: function (event) {
544                 nodelabel_methods.selected( this, ! this.selected );
545             }
546         },
547
548
549         /* ---------------------------------------------------------------------
550          * The lease buttons
551          */
552         lease_methods: {
553         
554             init_free: function (lease, unclick) {
555                 var o = lease.scheduler.options;
556                 lease.current="free";
557                 // set color
558                 lease.animate((lease.initial=="free") ? attr_lease_free_free : attr_lease_mine_free, o.anim_delay);
559                 // keep track of the current status
560                 // record action
561                 lease.click (lease_methods.click_free);
562                 if (unclick) lease.unclick(unclick);
563             },
564                      
565             // find out all the currently free leases that overlap this one
566             click_free: function (event) {
567                 var scheduler = this.scheduler;
568                 lease_methods.init_mine(this,lease_methods.click_free);        
569                 //publish
570                 //this.from_time
571                 //this.urn
572                 //this.until_time
573                 var urn = this.urn
574                 var start_time=new Date(this.from_time).getTime() / 1000;        
575                 var end_time=new Date(this.until_time).getTime() / 1000;
576                 var duration=(end_time-start_time)/1800; // XXX HARDCODED LEASE GRAIN
577
578                 /* Add a new lease : XXX should be replaced by a dictionary */
579                 // Do we have a lease with the same urn  just before or just after ?
580                 var removeIdBefore = null;
581                 var removeIdAfter = null;
582                 jQuery.each(scheduler.listLeases, function(i, lease) {
583                     if (lease[0] == urn) {
584                         if (lease[1] + lease[2] * 1800 == start_time) { // XXX HARDCODED LEASE GRAIN
585                             // Merge with previous lease
586                             removeIdBefore = i;
587                             start_time = lease[1];
588                             duration += lease[2];
589                         }
590                         if (lease[1] == end_time) {
591                             // Merge with following lease
592                             removeIdAfter = i;
593                             duration += lease[2];
594                         }
595                     }
596                 });
597                 if (removeIdBefore != null) {
598                     scheduler.listLeases.splice(removeIdBefore , 1);
599                     if (removeIdAfter != null)
600                         removeIdAfter -= 1;
601                 }
602                 if (removeIdAfter != null) {
603                     scheduler.listLeases.splice(removeIdAfter , 1);
604                 }
605
606                 scheduler.listLeases.push([this.urn, start_time, duration]);
607
608                 console.log(scheduler.listLeases);
609                 //jQuery.publish('/update-set/' + scheduler.options.query_uuid, [scheduler.listLeases]);
610                 jQuery.publish('/update-set/' + scheduler.options.lease_query_uuid, [scheduler.listLeases]);
611             },
612
613             init_mine: function (lease, unclick) {
614                 var o = lease.scheduler.options;
615                 lease.current="mine";
616                 lease.animate((lease.initial=="mine") ? attr_lease_mine_mine : attr_lease_free_mine,o.anim_delay);
617                 lease.click (lease_methods.click_mine);
618                 if (unclick) lease.unclick(unclick);
619             },
620             
621             /* TODO: remove selected lease from array listLeases and publish change */
622             click_mine: function (event) {
623                 var scheduler = this.scheduler;
624                 // this lease was originally free but is now marked for booking
625                 // we free just this lease
626                 //console.log('this is mine');
627                 lease_methods.init_free(this, lease_methods.click_mine);
628             },
629
630
631             init_other: function (lease, slicename) {
632                 lease.animate (attr_lease_other,anim_delay);
633                 /* a text obj to display the name of the slice that owns that lease */
634                 var otherslicelabel = lease.scheduler.paper.text (lease.attr("x")+lease.attr("width")/2,
635                                           // xxx
636                                           lease.attr("y")+lease.attr("height")/2,slicename).attr(txt_otherslice);
637                 /* hide it right away */
638                 otherslicelabel.hide();
639                 /* record it */
640                 lease.label=otherslicelabel;
641                 lease.hover ( function (e) {this.label.toFront();this.label.show();},
642                           function (e) {this.label.hide();} ); 
643             }
644         }
645
646     });
647
648     $.plugin('Scheduler', Scheduler);
649
650 })(jQuery);