reservation : timeslot width in pixels can be set with $_GET['resa_x_grain']
[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 // x_grain is configurable from $_GET
14 //var x_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, x_grain, axisx, axisy, data) {
55
56     // the data contains slice names, and lease_id, we need this to find our own leases (mine)
57     this.sliceid=sliceid;
58     this.slicename=slicename;
59     this.axisx=axisx;
60     this.axisy=axisy;
61     this.data=data;
62
63     this.x_grain = parseInt(x_grain);
64     // the path for the triangle-shaped buttons
65     this.timebutton_path="M1,0L"+(this.x_grain-1)+",0L"+(this.x_grain/2)+","+y_header+"L1,0";
66
67     // utilities to keep track of all the leases
68     this.leases=[];
69     this.append_lease = function (lease) { 
70         this.leases.push(lease);
71     }
72
73     // how many time slots 
74     this.nb_grains = function () { return axisx.length;}
75
76     this.init = function (canvas_id) {
77         this.total_width = x_nodelabel + this.nb_grains()*this.x_grain; 
78         this.total_height =   2*y_header /* the timelabels */
79                             + 2*y_sep    /* extra space */
80                             + y_node     /* all-nodes & timebuttons row */ 
81                             + (this.axisy.length)*(y_node+y_sep);  /* the regular nodes and preceding space */
82         paper = Raphael (canvas_id, this.total_width+x_sep, this.total_height);
83
84         // maintain the list of nodelabels for the 'all nodes' button
85         this.nodelabels=[];
86
87         ////////// create the time slots legend
88         var top=0;
89         var left=x_nodelabel;
90
91         var daymarker_height= 2*y_header+2*y_sep + (axisy.length+1)*(y_node+y_sep);
92         var daymarker_path="M0,0L0," + daymarker_height;
93
94         var half_daymarker_off= 2*y_header+y_sep;
95         var half_daymarker_path="M0," + half_daymarker_off + "L0," + daymarker_height;
96
97         var col=0;
98         for (var i=0, len=axisx.length; i < len; ++i) {
99             // pick the printable part
100             var timelabel=axisx[i][1];
101             var y = top+y_header;
102             if (col%2 == 0) y += y_header;
103             col +=1;
104             // display time label
105             var timelabel=paper.text(left,y,timelabel).attr(txt_timelabel)
106                 .attr({"text-anchor":"middle"});
107             // draw vertical line
108             var path_spec="M"+left+" "+(y+y_header/2)+"L"+left+" "+this.total_height;
109             var rule=paper.path(path_spec).attr(attr_rules);
110             // show a day marker when relevant
111             var timestamp=parseInt(axisx[i][0]);
112             if ( (timestamp%(24*3600))==0) {
113                 paper.path(daymarker_path).attr({'translation':left+','+top}).attr(attr_daymarker);
114             } else if ( (timestamp%(12*3600))==0) {
115                 paper.path(half_daymarker_path).attr({'translation':left+','+top}).attr(attr_daymarker);
116             }
117             left+=(this.x_grain);
118         }
119
120         ////////// the row with the timeslot buttons (the one labeled 'All nodes')
121         this.granularity=axisx[1][0]-axisx[0][0];
122
123         // move two lines down
124         top += 2*y_header+2*y_sep;
125         left=x_nodelabel;
126         // all nodes buttons
127         var allnodes = paper.text (x_nodelabel-x_sep,top+y_node/2,"All nodes").attr(txt_allnodes)
128                 .attr ({"font-size":y_node, "text-anchor":"end","baseline":"bottom"});
129         allnodes.scheduler=this;
130         allnodes.click(allnodes_methods.click);
131         // timeslot buttons
132         for (var i=0, len=axisx.length; i < len; ++i) {
133             var timebutton=paper.path(this.timebutton_path).attr({'translation':left+','+top}).attr(attr_timebutton);
134             timebutton.from_time=axisx[i][0];
135             timebutton.scheduler=this;
136             timebutton.click(timebutton_methods.click);
137             left+=(this.x_grain);
138         }
139         
140         //////// the body of the scheduler : loop on nodes
141         top += y_node+y_sep;
142         var data_index=0;
143         for (var i=0, len=axisy.length; i<len; ++i) {
144             nodename=axisy[i];
145             left=0;
146             var nodelabel = paper.text(x_nodelabel-x_sep,top+y_node/2,nodename).attr(txt_nodelabel)
147                 .attr ({"font-size":y_node, "text-anchor":"end","baseline":"bottom"});
148             nodelabel_methods.selected(nodelabel,1);
149             nodelabel.click(nodelabel_methods.click);
150             this.nodelabels.push(nodelabel);
151             
152             left += x_nodelabel;
153             var grain=0;
154             while (grain < this.nb_grains()) {
155                 lease_id=data[data_index][0];
156                 slicename=data[data_index][1];
157                 duration=data[data_index][2];
158                 var lease=paper.rect (left,top,this.x_grain*duration,y_node,radius);
159                 lease.lease_id=lease_id;
160                 lease.nodename=nodename;
161                 lease.nodelabel=nodelabel;
162                 if (slicename == "") {
163                     lease.initial="free";
164                     lease_methods.init_free(lease);
165                 } else if (slicename == this.slicename) {
166                     lease.initial="mine";
167                     lease_methods.init_mine(lease);
168                 } else {
169                     lease_initial="other";
170                     lease_methods.init_other(lease,slicename);
171                 }
172                 lease.from_time = axisx[grain%this.nb_grains()][0];
173                 grain += duration;
174                 lease.until_time = axisx[grain%this.nb_grains()][0];
175                 // record scheduler in lease
176                 lease.scheduler=this;
177                 // and vice versa
178                 this.append_lease(lease);
179                 // move on with the loop
180                 left += this.x_grain*duration;
181                 data_index +=1;
182             }
183             top += y_node + y_sep;
184         };
185     }
186
187     this.submit = function () {
188         document.body.style.cursor = "wait";
189         var actions=new Array();
190         for (var i=0, len=this.leases.length; i<len; ++i) {
191             var lease=this.leases[i];
192             if (lease.current != lease.initial) {
193                 var from_time=lease.from_time;
194                 var until_time=lease.until_time;
195                 /* scan the leases just after this one and merge if appropriate */
196                 var j=i+1;
197                 while (j<len && lease_methods.compare (lease, until_time, this.leases[j])) {
198 //                  window.console.log('merged index='+j);
199                     until_time=this.leases[j].until_time;
200                     ++j; ++i;
201                 }
202                 if (lease.current!='free') { // lease to add
203                     actions.push(new Array('add-leases',
204                                            new Array(lease.nodename),
205                                            this.slicename,
206                                            from_time,
207                                            until_time));
208                 } else { // lease to delete
209                     actions.push(new Array ('delete-leases',
210                                             lease.lease_id));
211                 }
212             }
213         }
214         sliceid=this.sliceid;
215         // once we're done with the side-effect performed in actions.php, we need to refresh this view
216         redirect = function (sliceid) {
217             window.location = '/db/slices/slice.php?id=' + sliceid + '&show_details=0&show_nodes=1&show_nodes_resa=1';
218         }
219         // Ajax.Request comes with prototype
220         var ajax=new Ajax.Request('/planetlab/common/actions.php', 
221                                   {method:'post',
222                                    parameters:{'action':'manage-leases',
223                                                'actions':actions.toJSON()},
224                                    onSuccess: function(transport) {
225                                        var response = transport.responseText || "no response text";
226                                        document.body.style.cursor = "default";
227                                        alert("Server answered:\n\n" + response + "\n\nPress OK to refresh page");
228                                        redirect(sliceid);
229                                    },
230                                    onFailure: function(){ 
231                                        document.body.style.cursor = "default";
232                                        alert("Could not reach server, sorry...\n\nPress OK to refresh page");
233                                        // not too sure what to do here ...
234                                        redirect(sliceid);
235                                    },
236                                   });
237     }
238
239     this.clear = function () {
240         for (var i=0, len=this.leases.length; i<len; ++i) {
241             var lease=this.leases[i];
242             if (lease.current != lease.initial) {
243                 if (lease.initial == 'free') lease_methods.init_free(lease,lease_methods.click_mine);
244                 else                         lease_methods.init_mine(lease,lease_methods.click_free);
245             }
246         }
247     }
248
249 } // end Scheduler
250
251 //////////////////////////////////////// couldn't find how to inhererit from the raphael objects...
252
253 //////////////////// the 'all nodes' button
254 var allnodes_methods = {
255     click: function (event) {
256         var scheduler=this.scheduler;
257         /* decide what to do */
258         var unselected=0;
259         for (var i=0, len=scheduler.nodelabels.length; i<len; ++i) 
260             if (! scheduler.nodelabels[i].selected) unselected++;
261         /* if at least one is not selected : select all */
262         var new_state = (unselected >0) ? 1 : 0;
263         for (var i=0, len=scheduler.nodelabels.length; i<len; ++i) 
264             nodelabel_methods.selected(scheduler.nodelabels[i],new_state);
265     }
266 }
267
268 //////////////////// the buttons for managing the whole timeslot
269 var timebutton_methods = {
270
271     /* clicking */
272     click: function (event) {
273         var scheduler = this.scheduler;
274         var from_time = this.from_time;
275         var until_time = from_time + scheduler.granularity;
276         /* scan leases on selected nodes, store in two arrays */
277         var relevant_free=[], relevant_mine=[];
278         for (var i=0,len=scheduler.leases.length; i<len; ++i) {
279             var scan=scheduler.leases[i];
280             if ( ! scan.nodelabel.selected) continue;
281             // overlap ?
282             if (scan.from_time<=from_time && scan.until_time>=until_time) {
283                 if (scan.current == "free")       relevant_free.push(scan);
284                 else if (scan.current == "mine")  relevant_mine.push(scan);
285             }
286         }
287 //      window.console.log("Found " + relevant_free.length + " free and " + relevant_mine.length + " mine");
288         /* decide what to do, whether book or release */
289         if (relevant_mine.length==0 && relevant_free.length==0) {
290             alert ("Nothing to do in this timeslot on the selected nodes");
291             return;
292         }
293         // if at least one is free, let's book
294         if (relevant_free.length > 0) {
295             for (var i=0, len=relevant_free.length; i<len; ++i) {
296                 var lease=relevant_free[i];
297                 lease_methods.init_mine(lease,lease_methods.click_free);
298             }
299         // otherwise we unselect
300         } else {
301             for (var i=0, len=relevant_mine.length; i<len; ++i) {
302                 var lease=relevant_mine[i];
303                 lease_methods.init_free(lease,lease_methods.click_mine);
304             }
305         }
306     }
307 }
308
309 //////////////////// the nodelabel buttons
310 var nodelabel_methods = {
311     
312     // set selected mode and render visually
313     selected: function (nodelabel, flag) {
314         nodelabel.selected=flag;
315         nodelabel.attr({'font-weight': (flag ? 'bold' : 'normal')});
316     },
317
318     // toggle selected
319     click: function (event) {
320         nodelabel_methods.selected( this, ! this.selected );
321     }
322 }
323
324
325 //////////////////// the lease buttons
326 var lease_methods = {
327     
328     /* in the process of merging leases before posting to the API */
329     compare: function (lease, until_time, next_lease) {
330         return (next_lease['nodename'] == lease['nodename'] &&
331                 next_lease['from_time'] == until_time &&
332                 next_lease['initial'] == lease['initial'] &&
333                 next_lease['current'] == lease['current']);
334     },
335
336     init_free: function (lease, unclick) {
337         lease.current="free";
338         // set color
339         lease.animate((lease.initial=="free") ? attr_lease_free_free : attr_lease_mine_free,anim_delay);
340         // keep track of the current status
341         // record action
342         lease.click (lease_methods.click_free);
343         if (unclick) lease.unclick(unclick);
344     },
345                      
346     // find out all the currently free leases that overlap this one
347     click_free: function (event) {
348         var scheduler = this.scheduler;
349         lease_methods.init_mine(this,lease_methods.click_free);
350     },
351
352     init_mine: function (lease, unclick) {
353         lease.current="mine";
354         lease.animate((lease.initial=="mine") ? attr_lease_mine_mine : attr_lease_free_mine,anim_delay);
355         lease.click (lease_methods.click_mine);
356         if (unclick) lease.unclick(unclick);
357     },
358
359     click_mine: function (event) {
360         var scheduler = this.scheduler;
361         // this lease was originally free but is now marked for booking
362         // we free just this lease
363         lease_methods.init_free(this, lease_methods.click_mine);
364     },
365
366
367     init_other: function (lease, slicename) {
368         lease.animate (attr_lease_other,anim_delay);
369         /* a text obj to display the name of the slice that owns that lease */
370         var otherslicelabel = paper.text (lease.attr("x")+lease.attr("width")/2,
371                                           // xxx
372                                           lease.attr("y")+lease.attr("height")/2,slicename).attr(txt_otherslice);
373         /* hide it right away */
374         otherslicelabel.hide();
375         /* record it */
376         lease.label=otherslicelabel;
377         lease.hover ( function (e) { this.label.toFront(); this.label.show(); },
378                       function (e) { this.label.hide(); } ); 
379     },
380 }
381
382 function init_scheduler () {
383     // Grab the data
384     var data = [], axisx = [], axisy = [];
385     var table = $$("table#leases_data")[0];
386     // no reservable nodes - no data
387     if ( ! table) return;
388     // upper-left cell : sliceid & slicename & x_grain
389     var slice_attributes = getInnerText(table.getElementsBySelector("thead>tr>td")[0]).split('&');
390     var sliceid=slice_attributes[0];
391     var slicename=slice_attributes[1];
392     var x_grain=slice_attributes[2];
393     // the nodelabels
394     table.getElementsBySelector("tbody>tr>th").each(function (cell) {
395         axisy.push(getInnerText(cell));
396     });
397     // the timeslot labels
398     table.getElementsBySelector("thead>tr>th").each(function (cell) {
399         /* [0]: timestamp -- [1]: displayable*/
400         axisx.push(getInnerText(cell).split("&"));
401     });
402     // leases - expect colspan to describe length in grains
403     // the text contents is expected to be lease_id & slicename
404     table.getElementsBySelector("tbody>tr>td").each(function (cell) {
405         var cell_data;
406         slice_attributes=getInnerText(cell).split('&');
407         // booked leases come with lease id and slice name
408         if (slice_attributes.length == 2) {
409             // leases is booked : slice_id, slice_name, duration in grains
410             cell_data=new Array (slice_attributes[0], slice_attributes[1], cell.colSpan);
411         } else {
412             cell_data = new Array ('','',cell.colSpan);
413         }
414         data.push(cell_data);
415     });
416     var scheduler = new Scheduler (sliceid,slicename, x_grain, axisx, axisy, data);
417     table.hide();
418     // leases_area is a <div> created by slice.php as a placeholder
419     scheduler.init ("leases_area");
420
421     var submit=$$("button#leases_submit")[0];
422     submit.onclick = function () { scheduler.submit(); }
423     var clear=$$("button#leases_clear")[0];
424     clear.onclick = function () { scheduler.clear(); }
425
426 }
427
428 Event.observe(window, 'load', init_scheduler);