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