fix for prototype-1.7, leases were broken
[plewww.git] / planetlab / slices / leases.js
1 /*  Thierry Parmentelat -- INRIA */
2
3 /* need to put some place else in CSS ? */
4
5 // space for the nodenames
6 var x_nodelabel = 200;
7 // right space after the nodename - removed from the above
8 var x_sep=20;
9 // height for the (two) rows of timelabels
10 var y_header = 12;
11 // space between nodes
12 var y_sep = 10;
13
14 // 1-grain leases attributes
15 // leases_w is configurable from html
16 //var leases_w = 20;
17 var y_node = 15;
18 var radius= 6;
19
20 var anim_delay=350;
21
22 /* decorations / headers */
23 /* note: looks like the 'font' attr is not effective... */
24
25 // vertical rules
26 var attr_rules={'fill':"#888", 'stroke-dasharray':'- ', 'stroke-width':0.5};
27 // set font-size separately in here rather than depend on the height
28 var txt_timelabel = {"font": 'Times, "Trebuchet MS", Verdana, Arial, Helvetica, sans-serif', 
29                      stroke: "none", fill: "#008", 'font-size': 9};
30 var txt_allnodes = {"font": '"Trebuchet MS", Verdana, Arial, Helvetica, sans-serif', stroke: "none", fill: "#404"};
31 var txt_nodelabel = {"font": '"Trebuchet MS", Verdana, Arial, Helvetica, sans-serif', stroke: "none", fill: "#008"};
32
33 var attr_timebutton = {'fill':'#bbf', 'stroke': '#338','stroke-width':1, 
34                        'stroke-linecap':'round', 'stroke-linejoin':'miter', 'stroke-miterlimit':3};
35 var attr_daymarker = {'stroke':'#000','stroke-width':2};
36 var attr_half_daymarker = {'stroke':'#444','stroke-width':2};
37
38 /* lease dimensions and colors */
39 /* refrain from using gradient color, seems to not be animated properly */
40 /* lease was originally free and is still free */
41 var attr_lease_free_free={'fill':"#def", 'stroke-width':0.5, 'stroke-dasharray':''};
42 /* lease was originally free and is now set for our usage */
43 var attr_lease_free_mine={'fill':"green", 'stroke-width':1, 'stroke-dasharray':'-..'};
44 /* was mine and is still mine */
45 var attr_lease_mine_mine={'fill':"#beb", 'stroke-width':0.5, 'stroke-dasharray':''};
46 /* was mine and is about to be released */
47 var attr_lease_mine_free={'fill':"white", 'stroke-width':1, 'stroke-dasharray':'-..'};
48 var attr_lease_other={'fill':"#f88"};
49
50 /* other slices name */
51 var txt_otherslice = {"font": '"Trebuchet MS", Verdana, Arial, Helvetica, sans-serif', stroke: "none", fill: "#444",
52                       "font-size": 12 };
53
54 ////////////////////////////////////////////////////////////
55 // the scheduler object
56 function Scheduler () {
57
58     // xxx-hacky dunno how to retrieve this object from an ajax callback
59     Scheduler.scheduler=this;
60
61     // the data contains slice names, and lease_id, we need this to find our own leases (mine)
62     this.paper=null;
63
64     ////////////////////
65     // store the result of an ajax request in the leases_data table 
66     this.set_html = function (html_data) {
67         var table_text = $$("table#leases_data")[0].innerHTML;
68         $$("table#leases_data")[0].innerHTML=html_data;
69         table_text = $$("table#leases_data")[0].innerHTML;
70         return true;
71     }
72
73     ////////////////////
74     // the names of the hidden fields that hold the input to this class
75     // are hard-wired for now
76     this.parse_html = function () {
77         
78         var table = $$("table#leases_data")[0];
79         // no reservable nodes - no data
80         if ( ! table) return false;
81
82         // the nodelabels
83         var data = [], axisx = [], axisy = [];
84         table.getElementsBySelector("tbody>tr>th").each(function (cell) {
85             axisy.push(getInnerText(cell));
86         });
87         // test for at least one entry; other wise this means we haven't retrieved
88         // the html dta yet
89         if (axisy.length <1) return false;
90
91         // the timeslot labels
92         table.getElementsBySelector("thead>tr>th").each(function (cell) {
93             /* [0]: timestamp -- [1]: displayable*/
94             axisx.push(getInnerText(cell).split("&"));
95         });
96
97         // leases - expect colspan to describe length in grains
98         // the text contents is expected to be lease_id & slicename
99         table.getElementsBySelector("tbody>tr>td").each(function (cell) {
100             var cell_data;
101             var slice_attributes=getInnerText(cell).split('&');
102             // booked leases come with lease id and slice name
103             if (slice_attributes.length == 2) {
104                 // leases is booked : slice_id, slice_name, duration in grains
105                 cell_data=new Array (slice_attributes[0], slice_attributes[1], cell.colSpan);
106             } else {
107                 cell_data = new Array ('','',cell.colSpan);
108             }
109             data.push(cell_data);
110         });
111
112         this.axisx=axisx;
113         this.axisy=axisy;
114         this.data=data;
115         return true;
116     }
117
118     // how many time slots 
119     this.nb_grains = function () { return this.axisx.length;}
120
121     ////////////////////
122     // draw 
123     this.draw_area = function (canvas_id) {
124         this.total_width = x_nodelabel + this.nb_grains()*this.leases_w; 
125         this.total_height =   2*y_header /* the timelabels */
126                             + 2*y_sep    /* extra space */
127                             + y_node     /* all-nodes & timebuttons row */ 
128                             + (this.axisy.length)*(y_node+y_sep);  /* the regular nodes and preceding space */
129         // reuse for paper if exists with same size, or (re-)create otherwise
130         var paper;
131         if (this.paper == null) {
132             paper = Raphael (canvas_id, this.total_width+x_sep, this.total_height);
133         } else if (this.paper.width==this.total_width && this.paper.height==this.total_height) {
134             paper=this.paper;
135             paper.clear();
136         } else {
137             $$("#"+canvas_id)[0].innerHTML="";
138             paper = Raphael (canvas_id, this.total_width+x_sep, this.total_height);
139         }
140         this.paper=paper;
141
142         // the path for the triangle-shaped buttons
143         this.timebutton_path="M1,0L"+(this.leases_w-1)+",0L"+(this.leases_w/2)+","+y_header+"L1,0";
144
145         var axisx=this.axisx;
146         
147         var axisy=this.axisy;
148         // maintain the list of nodelabels for the 'all nodes' button
149         this.nodelabels=[];
150
151         ////////// create the time slots legend
152         var top=0;
153         var left=x_nodelabel;
154
155         var daymarker_height= 2*y_header+2*y_sep + (axisy.length+1)*(y_node+y_sep);
156         var daymarker_path="M0,0L0," + daymarker_height;
157
158         var half_daymarker_off= 2*y_header+y_sep;
159         var half_daymarker_path="M0," + half_daymarker_off + "L0," + daymarker_height;
160
161         var col=0;
162         for (var i=0, len=axisx.length; i < len; ++i) {
163             // pick the printable part
164             var timelabel=axisx[i][1];
165             var y = top+y_header;
166             if (col%2 == 0) y += y_header;
167             col +=1;
168             // display time label
169             var timelabel=paper.text(left,y,timelabel).attr(txt_timelabel)
170                 .attr({"text-anchor":"middle"});
171             // draw vertical line
172             var path_spec="M"+left+" "+(y+y_header/2)+"L"+left+" "+this.total_height;
173             var rule=paper.path(path_spec).attr(attr_rules);
174             // show a day marker when relevant
175             var timestamp=parseInt(axisx[i][0]);
176             if ( (timestamp%(24*3600))==0) {
177                 paper.path(daymarker_path).attr({'translation':left+','+top}).attr(attr_daymarker);
178             } else if ( (timestamp%(12*3600))==0) {
179                 paper.path(half_daymarker_path).attr({'translation':left+','+top}).attr(attr_daymarker);
180             }
181             left+=(this.leases_w);
182         }
183
184         ////////// the row with the timeslot buttons (the one labeled 'All nodes')
185         this.granularity=axisx[1][0]-axisx[0][0];
186
187         // move two lines down
188         top += 2*y_header+2*y_sep;
189         left=x_nodelabel;
190         // all nodes buttons
191         var allnodes = paper.text (x_nodelabel-x_sep,top+y_node/2,"All nodes").attr(txt_allnodes)
192                 .attr ({"font-size":y_node, "text-anchor":"end","baseline":"bottom"});
193         allnodes.scheduler=this;
194         allnodes.click(allnodes_methods.click);
195         // timeslot buttons
196         for (var i=0, len=axisx.length; i < len; ++i) {
197             var timebutton=paper.path(this.timebutton_path).attr({'translation':left+','+top}).attr(attr_timebutton);
198             timebutton.from_time=axisx[i][0];
199             timebutton.scheduler=this;
200             timebutton.click(timebutton_methods.click);
201             left+=(this.leases_w);
202         }
203         
204         //////// the body of the scheduler : loop on nodes
205         top += y_node+y_sep;
206         var data_index=0;
207         this.leases=[];
208         for (var i=0, len=axisy.length; i<len; ++i) {
209             var nodename=axisy[i];
210             left=0;
211             var nodelabel = paper.text(x_nodelabel-x_sep,top+y_node/2,nodename).attr(txt_nodelabel)
212                 .attr ({"font-size":y_node, "text-anchor":"end","baseline":"bottom"});
213             nodelabel_methods.selected(nodelabel,1);
214             nodelabel.click(nodelabel_methods.click);
215             this.nodelabels.push(nodelabel);
216             
217             left += x_nodelabel;
218             var grain=0;
219             while (grain < this.nb_grains()) {
220                 lease_id=this.data[data_index][0];
221                 slicename=this.data[data_index][1];
222                 duration=this.data[data_index][2];
223                 var lease=paper.rect (left,top,this.leases_w*duration,y_node,radius);
224                 // record scheduler in lease - early as we need this in init_other
225                 lease.scheduler=this;
226                 lease.lease_id=lease_id;
227                 lease.nodename=nodename;
228                 lease.nodelabel=nodelabel;
229                 if (slicename == "") {
230                     lease.initial="free";
231                     lease_methods.init_free(lease);
232                 } else if (slicename == this.slicename) {
233                     lease.initial="mine";
234                     lease_methods.init_mine(lease);
235                 } else {
236                     lease.initial="other";
237                     lease_methods.init_other(lease,slicename);
238                 }
239                 lease.from_time = axisx[grain%this.nb_grains()][0];
240                 grain += duration;
241                 lease.until_time = axisx[grain%this.nb_grains()][0];
242                 // and vice versa
243                 this.leases.push(lease);
244                 // move on with the loop
245                 left += this.leases_w*duration;
246                 data_index +=1;
247             }
248             top += y_node + y_sep;
249         };
250     }
251
252     this.submit = function () {
253         document.body.style.cursor = "wait";
254         var actions=new Array();
255         for (var i=0, len=this.leases.length; i<len; ++i) {
256             var lease=this.leases[i];
257             if (lease.current != lease.initial) {
258                 var from_time=lease.from_time;
259                 var until_time=lease.until_time;
260                 /* scan the leases just after this one and merge if appropriate */
261                 /* this makes sense when adding leases only though */
262                 if (lease.current=='mine') {
263                     var j=i+1;
264                     while (j<len && lease_methods.compare (lease, until_time, this.leases[j])) {
265 //                      window.console.log('merging index='+i+' initial='+lease.initial+' current='+lease.current);
266 //                      window.console.log('merged index='+j+' initial='+this.leases[j].initial+' current='+this.leases[j].current);
267                         until_time=this.leases[j].until_time;
268                         ++j; ++i;
269                     }
270                 }
271                 if (lease.current!='free') { // lease to add
272                     actions.push(new Array('add-leases',
273                                            new Array(lease.nodename),
274                                            this.slicename,
275                                            from_time,
276                                            until_time));
277                 } else { // lease to delete
278                     actions.push(new Array ('delete-leases',
279                                             lease.lease_id));
280                 }
281             }
282         }
283         slice_id=this.slice_id;
284         // Ajax.Request comes with prototype
285         var ajax=new Ajax.Request('/planetlab/common/actions.php', 
286                                   {method:'post',
287                                    parameters:{'action':'manage-leases',
288                                                'actions':Object.toJSON(actions)},
289                                    onSuccess: function(transport) {
290                                        var response = transport.responseText || "no response text";
291                                        document.body.style.cursor = "default";
292 //                                     alert("Server answered:\n\n" + response + "\n\nPress OK to refresh page");
293                                        Scheduler.scheduler.refresh();
294                                    },
295                                    onFailure: function(){ 
296                                        document.body.style.cursor = "default";
297                                        alert("Could not reach server, sorry...\n\nPress OK to refresh page");
298                                        // not too sure what to do here ...
299                                        Scheduler.scheduler.refresh();
300                                    },
301                                   });
302     }
303
304     this.clear = function () {
305         for (var i=0, len=this.leases.length; i<len; ++i) {
306             var lease=this.leases[i];
307             if (lease.current != lease.initial) {
308                 if (lease.initial == 'free') lease_methods.init_free(lease,lease_methods.click_mine);
309                 else                         lease_methods.init_mine(lease,lease_methods.click_free);
310             }
311         }
312     }
313
314     // re-read settings from the html, ajax-aquire the html text for the leases_data table
315     // store it in the html tree, parse it, and refresh graphic
316     this.refresh = function () {
317         this.slice_id=getInnerText($$("span#leases_slice_id")[0]).strip();
318         this.slicename=getInnerText($$("span#leases_slicename")[0]).strip();
319         this.leases_granularity=getInnerText($$("span#leases_granularity")[0]).strip();
320         this.leases_offset=$("leases_offset_input").value.strip();
321         this.leases_slots=$("leases_slots_input").value.strip();
322         this.leases_w=parseInt($("leases_w_input").value.strip());
323
324         document.body.style.cursor = "wait";
325         var ajax=new Ajax.Request('/planetlab/slices/leases-data.php',
326                                   {method:'post',
327                                    parameters:{'slice_id':this.slice_id,
328                                                'slicename':this.slicename,
329                                                'leases_granularity':this.leases_granularity,
330                                                'leases_offset':this.leases_offset,
331                                                'leases_slots':this.leases_slots,
332                                                'leases_w':this.leases_w},
333                                    onSuccess: function (transport) {
334                                        var response = transport.responseText || "no response text";
335 //                                     window.console.log("received from ajax=[["+response+"]]");
336                                        var scheduler=Scheduler.scheduler;
337                                        if ( ! scheduler.set_html (response)) 
338                                            alert ("Something wrong .. Could not store ajax result..");
339                                        else if ( ! scheduler.parse_html()) 
340                                            alert ("Error: could not parse ajax result..\nIf your session has expired, you need to log back in");
341                                        else
342                                            scheduler.draw_area("leases_area");
343                                        document.body.style.cursor = "default";
344                                    },
345                                    onFailure: function(){ 
346                                        document.body.style.cursor = "default";
347                                        alert("Could not reach server, sorry...\n\n");
348                                    },
349                                   });
350                                        
351     }
352
353 } // end Scheduler
354
355 //////////////////////////////////////// couldn't find how to inhererit from the raphael objects...
356
357 //////////////////// the 'all nodes' button
358 var allnodes_methods = {
359     click: function (event) {
360         var scheduler=this.scheduler;
361         /* decide what to do */
362         var unselected=0;
363         for (var i=0, len=scheduler.nodelabels.length; i<len; ++i) 
364             if (! scheduler.nodelabels[i].selected) unselected++;
365         /* if at least one is not selected : select all */
366         var new_state = (unselected >0) ? 1 : 0;
367         for (var i=0, len=scheduler.nodelabels.length; i<len; ++i) 
368             nodelabel_methods.selected(scheduler.nodelabels[i],new_state);
369     }
370 }
371
372 //////////////////// the buttons for managing the whole timeslot
373 var timebutton_methods = {
374
375     /* clicking */
376     click: function (event) {
377         var scheduler = this.scheduler;
378         var from_time = this.from_time;
379         var until_time = from_time + scheduler.granularity;
380         /* scan leases on selected nodes, store in two arrays */
381         var relevant_free=[], relevant_mine=[];
382         for (var i=0,len=scheduler.leases.length; i<len; ++i) {
383             var scan=scheduler.leases[i];
384             if ( ! scan.nodelabel.selected) continue;
385             // overlap ?
386             if (scan.from_time<=from_time && scan.until_time>=until_time) {
387                 if (scan.current == "free")       relevant_free.push(scan);
388                 else if (scan.current == "mine")  relevant_mine.push(scan);
389             }
390         }
391 //      window.console.log("Found " + relevant_free.length + " free and " + relevant_mine.length + " mine");
392         /* decide what to do, whether book or release */
393         if (relevant_mine.length==0 && relevant_free.length==0) {
394             alert ("Nothing to do in this timeslot on the selected nodes");
395             return;
396         }
397         // if at least one is free, let's book
398         if (relevant_free.length > 0) {
399             for (var i=0, len=relevant_free.length; i<len; ++i) {
400                 var lease=relevant_free[i];
401                 lease_methods.init_mine(lease,lease_methods.click_free);
402             }
403         // otherwise we unselect
404         } else {
405             for (var i=0, len=relevant_mine.length; i<len; ++i) {
406                 var lease=relevant_mine[i];
407                 lease_methods.init_free(lease,lease_methods.click_mine);
408             }
409         }
410     }
411 }
412
413 //////////////////// the nodelabel buttons
414 var nodelabel_methods = {
415     
416     // set selected mode and render visually
417     selected: function (nodelabel, flag) {
418         nodelabel.selected=flag;
419         nodelabel.attr({'font-weight': (flag ? 'bold' : 'normal')});
420     },
421
422     // toggle selected
423     click: function (event) {
424         nodelabel_methods.selected( this, ! this.selected );
425     }
426 }
427
428
429 //////////////////// the lease buttons
430 var lease_methods = {
431     
432     /* in the process of merging leases before posting to the API */
433     compare: function (lease, until_time, next_lease) {
434         return (next_lease['nodename'] == lease['nodename'] &&
435                 next_lease['from_time'] == until_time &&
436                 next_lease['initial'] == lease['initial'] &&
437                 next_lease['current'] == lease['current']);
438     },
439
440     init_free: function (lease, unclick) {
441         lease.current="free";
442         // set color
443         lease.animate((lease.initial=="free") ? attr_lease_free_free : attr_lease_mine_free,anim_delay);
444         // keep track of the current status
445         // record action
446         lease.click (lease_methods.click_free);
447         if (unclick) lease.unclick(unclick);
448     },
449                      
450     // find out all the currently free leases that overlap this one
451     click_free: function (event) {
452         var scheduler = this.scheduler;
453         lease_methods.init_mine(this,lease_methods.click_free);
454     },
455
456     init_mine: function (lease, unclick) {
457         lease.current="mine";
458         lease.animate((lease.initial=="mine") ? attr_lease_mine_mine : attr_lease_free_mine,anim_delay);
459         lease.click (lease_methods.click_mine);
460         if (unclick) lease.unclick(unclick);
461     },
462
463     click_mine: function (event) {
464         var scheduler = this.scheduler;
465         // this lease was originally free but is now marked for booking
466         // we free just this lease
467         lease_methods.init_free(this, lease_methods.click_mine);
468     },
469
470
471     init_other: function (lease, slicename) {
472         lease.animate (attr_lease_other,anim_delay);
473         /* a text obj to display the name of the slice that owns that lease */
474         var otherslicelabel = lease.scheduler.paper.text (lease.attr("x")+lease.attr("width")/2,
475                                                           // xxx
476                                                           lease.attr("y")+lease.attr("height")/2,slicename).attr(txt_otherslice);
477         /* hide it right away */
478         otherslicelabel.hide();
479         /* record it */
480         lease.label=otherslicelabel;
481         lease.hover ( function (e) { this.label.toFront(); this.label.show(); },
482                       function (e) { this.label.hide(); } ); 
483     },
484 }
485
486 function init_scheduler () {
487     // Grab the data
488     var scheduler = new Scheduler ();
489     // parse the table with data, and if not empty, draw the scheduler
490     scheduler.refresh();
491     
492     // attach behaviour to buttons
493     $("leases_submit").onclick = function () { scheduler.submit(); }
494     $("leases_refresh").onclick = function () { scheduler.refresh();}
495
496 }
497
498 Event.observe(window, 'load', init_scheduler);