2 * Description: display a query result in a Google map
3 * Copyright (c) 2012-2013 UPMC Sorbonne Universite - INRIA
7 /* based on the leases.js code in PLE WWW interface for MyPLC by Thierry Parmentelat -- INRIA */
9 /* XXX Those declarations should not be part of the js file... */
11 /* decorations / headers */
12 /* note: looks like the 'font' attr is not effective... */
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"};
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};
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"};
39 /* other slices name */
40 var txt_otherslice = {"font": '"Trebuchet MS", Verdana, Arial, Helvetica, sans-serif', stroke: "none", fill: "#444", "font-size": "12px"};
44 var Scheduler = Plugin.extend({
46 init: function(options, element)
48 this._super(options, element);
50 /* Member variables */
51 this._canvas_id = this.id('leases_area');
53 this.query_uuid = options.query_uuid;
56 //this.current_resources = Array();
57 //this.current_leases = Array();
59 /* Managing asynchronous reception of resources and leases */
60 this._resources = Array();
61 this._leases = Array();
62 this._received_resources = false;
63 this._received_leases = false;
65 this._axisx = Array();
66 this._nodelabels = Array();
67 this._lease_elements = Array();
68 //this.myLeases = Array();
69 //this.allLeases = Array();
71 /* The time axis is an array of tuple (time, printable time) representing timeslots */
74 this.default_granularity = 1800; /* 30 min */
75 this._initial_timestamp = null;
77 /* This should be updated to be the ppcm of all granularities */
78 this.min_granularity = this.default_granularity;
80 // the data contains slice names, and lease_id, we need this to find our own leases (mine)
88 /* Listening to queries */
89 this.listen_query(options.query_uuid);
90 this.listen_query(options.query_all_resources_uuid, 'all_resources');
91 this.listen_query(options.query_lease_uuid, 'lease');
93 /* XXX GUI setup and event binding */
94 jQuery("#datepicker").datetimepicker({
95 //Timezone wise selection option
96 //timeFormat: 'hh:mm tt z',
99 onSelect: function(value) {
100 //console.log(value);
101 //converting time to timestamp
102 currentDate= Math.round(Date.parse(value)/ 1000);
104 // convert value to timestamp --done
105 // Get jQuery("#timepicker").val(); - no need anymore
106 // convert timepicker into seconds - no need
107 // Add time to date - done
108 // pass the result to init_axisx - done
109 //console.log(currentDate);
111 s._init_axisx(currentDate);
113 // Do we need to populate the timeslots with existing leases?
114 // Look how to populate with initial_leases [we have to show the leases]
119 this._init_axisx('');
124 /* Default settings */
129 leases_granularity: 3600,
131 x_nodelabel: 200, /* space for the nodenames */
132 x_sep: 20, /* right space after the nodename - removed from the above */
133 y_header: 12, /* height for the (two) rows of timelabels */
134 y_sep: 10, /* space between nodes */
135 leases_w: 20, /* 1-grain leases attributes */
146 /************************** GUI MANIPULATION **************************/
148 /* NOTE: All Raphael-dependent code should go here. Performance issues
149 * are suspected, it might be improved by a move to d3.js. The more
150 * general problem to solve is how to manipulate lots of svg objects.
153 /*************************** RECORD HANDLER ***************************/
155 /* ------------------------------------------------------------------
157 * ------------------------------------------------------------------ */
159 on_query_in_progress: function() {
163 on_query_done: function() {
164 /* We have received all leases */
165 if (this._received_resources) {
166 this._draw(this._canvas_id);
169 this._received_leases = true;
172 /* ------------------------------------------------------------------
174 * ------------------------------------------------------------------ */
176 on_all_resources_query_in_progress: function() {
177 console.log("all resources query in progress");
180 on_all_resources_new_record: function(record)
182 if ((typeof record.exclusive != 'undefined') && (record.exclusive)) {
183 this._resources.push(Array(record.urn, record.hrn, record.type));
185 // ... if we do not have information about slivers (first update), update it
186 if (typeof record.sliver != 'undefined') {
191 /* ------------------------------------------------------------------
193 * ------------------------------------------------------------------ */
195 on_lease_new_record: function(record)
197 this._leases.push(record);
198 // this.initial_leases=leases;
201 on_lease_field_state_changed: function(data)
203 var lease = data.value;
205 var start_time = lease[1];
207 var lease_element = this._lease_element_find(urn, start_time);
208 if (!lease_element) {
209 console.log("Alert: lease element not found");
213 switch(data.request) {
214 case FIELD_REQUEST_ADD:
215 case FIELD_REQUEST_ADD_RESET:
216 this._leases.push(data.value);
217 this._lease_init_mine(lease_element);
219 case FIELD_REQUEST_REMOVE:
220 case FIELD_REQUEST_REMOVE_RESET:
221 // We remove data.value (aka keep those leases different from data.value
222 this._leases = $.grep(this._leases, function(x) { return x != data.value; });
223 this._lease_init_free(lease_element);
231 on_lease_query_done: function(record)
233 /* We have received all resources */
234 if (this._received_leases) {
235 this._draw(this._canvas_id);
238 this._received_resources = true;
241 /************************** PRIVATE METHODS ***************************/
244 * @brief Return the number of time slots
246 nb_grains: function ()
248 return this._axisx.length;
252 * @brief Returns whether there is a pending lease at this timestamp
254 _lease_find: function(urn, timestamp)
256 var scheduler = this;
259 $.each(scheduler._leases, function(i, lease) {
260 if ((lease[0] == urn) &&
261 ((timestamp >= lease[1]) && (timestamp < (lease[1] + lease[2] * 1800)))) {
263 return false; // stop each
268 $.each(Array(scheduler.myLeases, scheduler.allLeases), function(i, array) {
269 $.each(array, function(i, lease) {
270 if (lease[0] == urn) {
271 if ((timestamp >= lease[1]) && (timestamp < (lease[1] + lease[2] * 1800))) {
285 /* Iterative search through raphael.js objects, no forEach, no getById in the current version */
286 _lease_element_find: function(urn, start_time)
288 var date = new Date(start_time*1000);
289 var pos = this._paper.top;
291 if (pos.key == urn + "-" + date)
303 var canvas_id = this._canvas_id;
304 var o = this.options;
306 var total_width = o.x_nodelabel + this.nb_grains() * this.options.leases_w;
307 var total_height = 2 * o.y_header /* the timelabels */
308 + 2 * o.y_sep /* extra space */
309 + o.y_node /* all-nodes & timebuttons row */
310 + (this._resources.length) * (o.y_node + o.y_sep); /* the regular nodes and preceding space */
312 /* reuse for paper if exists with same size, or (re-)create otherwise */
314 if (this._paper == null) {
315 paper = Raphael (canvas_id, total_width + o.x_sep, total_height);
316 } else if (this._paper.width==total_width && this._paper.height==total_height) {
320 $("#"+canvas_id)[0].innerHTML="";
321 //this.elmt().html();
322 paper = Raphael (canvas_id, total_width + o.x_sep, total_height);
326 /* the path for the triangle-shaped buttons */
327 var timebutton_path = "M1,0L"+(this.options.leases_w-1)+",0L"+(this.options.leases_w/2)+","+o.y_header+"L1,0";
329 var axisx = this._axisx;
330 var axisy = this._resources;
332 /* maintain the list of nodelabels for the 'all nodes' button */
333 this._nodelabels = [];
336 /* create the time slots legend */
338 var left = o.x_nodelabel;
340 var daymarker_height = 2*o.y_header + 2*o.y_sep + (axisy.length + 1) * (o.y_node + o.y_sep);
341 var daymarker_path = "M0,0L0," + daymarker_height;
343 var half_daymarker_off= 2*o.y_header + o.y_sep;
344 var half_daymarker_path="M0," + half_daymarker_off + "L0," + daymarker_height;
347 for (var i=0, len = axisx.length; i < len; ++i) {
348 /* pick the printable part */
349 var timelabel = axisx[i][1];
350 var y = top + o.y_header;
354 /* display time label */
355 var timelabel = paper.text(left, y, timelabel).attr(txt_timelabel).attr({"text-anchor": "middle"});
356 /* draw vertical line */
357 var path_spec = "M" + left + " " + (y+o.y_header / 2) + "L" + left + " " + this.total_height;
358 var rule = paper.path(path_spec).attr(attr_rules);
359 /* show a day marker when relevant */
360 var timestamp = parseInt(axisx[i][0]);
361 if ((timestamp % (24 * 3600)) == 0) {
362 paper.path(daymarker_path).attr({'translation': left + ',' + top}).attr(attr_daymarker);
363 } else if ( (timestamp%(12*3600))==0) {
364 paper.path(half_daymarker_path).attr({'translation': left + ',' + top}).attr(attr_daymarker);
369 ////////// the row with the timeslot buttons (the one labeled 'All nodes')
370 this.granularity = this.min_granularity; // XXX axisx[1][0]-axisx[0][0];
372 // move two lines down
373 top += 2 * o.y_header + 2 * o.y_sep;
374 left = o.x_nodelabel;
376 var allnodes = paper.text(o.x_nodelabel - o.x_sep, top + o.y_node / 2, "All nodes").attr(txt_allnodes)
377 .attr({"font-size": o.y_node, "text-anchor": "end", "baseline": "bottom"});
378 //allnodes.scheduler = this;
379 allnodes.click(this._allnodes_click); // XXX click
381 // timeslot buttons [it's the triangles above the slots]
382 for (var i = 0, len = axisx.length; i < len; ++i) {
383 var timebutton = paper.path(timebutton_path).attr({'translation':left + ',' + top}).attr(attr_timebutton);
384 timebutton.from_time = axisx[i][0];
385 timebutton.scheduler = this;
386 timebutton.click(this._timebutton_click);
387 left += (o.leases_w);
390 //////// the body of the scheduler : loop on nodes
391 top += o.y_node + o.y_sep;
394 this.leases = []; /* XXX ??? XXX */
396 for (var i = 0, len = axisy.length; i < len; ++i) {
397 var urn = axisy[i][0];
398 var nodename = axisy[i][1];
399 var type = axisy[i][2];
403 var nodelabel = paper.text(o.x_nodelabel-x_sep,top+y_node/2,nodename).attr(txt_nodelabel)
404 .attr ({"font-size":y_node, "text-anchor":"end","baseline":"bottom"});
406 var nodelabel = paper.text(o.x_nodelabel - o.x_sep, top + o.y_node / 3, nodename).attr(txt_nodelabel)
407 .attr({"font-size": "12px", "text-anchor": "end","baseline": "bottom"});
409 this._nodelabel_select(nodelabel, 1); // By default we select all nodes
410 nodelabel.scheduler = this;
411 nodelabel.click(this._nodelabel_click); //click action works here
412 this._nodelabels.push(nodelabel);
414 // lease_methods.init_free(nodelabel.click, lease_methods.click_mine);
415 //lease_methods.init_free(nodelabel.lease);
417 left += o.x_nodelabel;
419 // data index contains the full array of leases
420 // not the same amount of grains per node
422 // NOTE: remembering the previous lease might help for long leases.
424 while (grain < this.nb_grains()) {
426 if (l = this._lease_find(urn, this._initial_timestamp + grain * 1800)) {
427 slicename = l.slice_id;
432 //lease_id = this.data[data_index][0];
433 //slicename = this.data[data_index][1];
434 /* Duration should not be the lease duration, but the grain */
435 var duration = 1; // this.data[data_index][2];
437 var lease = paper.rect(left, top, o.leases_w * duration, o.y_node, o.radius);
438 lease.scheduler = this; // we record a pointer to the scheduler in the lease element
439 //lease.lease_id=lease_id;
440 lease.nodename = nodename;
442 lease.nodelabel = nodelabel;
444 if (slicename == "") {
445 lease.initial = "free";
446 this._lease_init_free(lease);
447 } else if (slicename == o.slicename) {
448 lease.initial = "mine";
449 this._lease_init_mine(lease);
451 lease.initial = "other";
452 this._lease_init_other(lease, slicename);
455 lease.from_time = axisx[grain % this.nb_grains()][0];
457 lease.until_time = axisx[grain % this.nb_grains()][0];
459 /* We set a key to the lease element to find it later in the paper thanks to this._lease_element_find() */
460 lease.key = urn + '-' + lease.from_time;
463 this._lease_elements.push(lease);
464 // move on with the loop
465 left += o.leases_w * duration;
468 top += o.y_node + o.y_sep;
472 _init_axisx: function(currentDate)
474 this._axisx = Array();
476 if(currentDate == "") {
477 // creating timestamp of the current time
478 currentDate = new Date().getTime() / 1000;
480 this._initial_timestamp = currentDate;
481 //console.log(currentDate);
483 // round it by granularity (becomes an Int)
484 var rounded = Math.round(currentDate / this.min_granularity) * this.min_granularity;
485 // Convert Int to Date
486 rounded = new Date(rounded * 1000);
487 // get hours and minutes in a 24h format 00:00
488 var roundedHours = (rounded.getHours() < 10 ? '0' : '') + rounded.getHours();
489 var roundedMinutes = (rounded.getMinutes() < 10 ? '0' : '') + rounded.getMinutes();
491 this._axisx.push(Array(rounded, roundedHours + ":" + roundedMinutes));
493 // Generate as many slots as we need
494 for(i = 0; i < this.options.leases_slots; i++) {
495 rounded = this.min_granularity + (rounded.getTime() / 1000);
496 rounded = new Date(rounded * 1000);
497 roundedHours = (rounded.getHours() < 10 ? '0' : '') + rounded.getHours();
498 roundedMinutes = (rounded.getMinutes() < 10 ? '0' : '') + rounded.getMinutes();
500 this._axisx.push(Array(rounded, roundedHours + ":" + roundedMinutes));
506 for (var i=0, len = this.leases.length; i<len; ++i) {
507 var lease = this.leases[i];
508 if (lease.current != lease.initial) {
509 if (lease.initial == 'free')
510 this._lease_init_free(lease, this._lease_click_mine);
512 this._lease_init_mine(lease, this._lease_methods.click_free);
517 // XXX Couldn't find how to inhererit from the raphael objects...
519 /* ---------------------------------------------------------------------
520 * The 'all nodes' button
522 _allnodes_click: function (event) {
523 var scheduler=this.scheduler;
525 /* decide what to do */
527 for (var i = 0, len = this._nodelabels.length; i < len; ++i)
528 if (!this._nodelabels[i].selected)
531 /* if at least one is not selected : select all */
532 var new_state = (unselected >0) ? 1 : 0;
533 for (var i=0, len=this._nodelabels.length; i<len; ++i)
534 this._nodelabel_select(this._nodelabels[i], new_state);
537 /* ---------------------------------------------------------------------
538 * The buttons for managing the whole timeslot
542 _timebutton_click: function (event)
544 var scheduler = this.scheduler;
545 var from_time = this.from_time;
546 var until_time = new Date(from_time.getTime() + scheduler.granularity);
547 /* scan leases on selected nodes, store in two arrays */
548 var relevant_free = [], relevant_mine = [];
549 for (var i = 0, len = scheduler._lease_elements.length; i < len; ++i) {
550 var scan = scheduler._lease_elements[i];
551 if (!scan.nodelabel.selected)
554 if (scan.from_time <= from_time && scan.until_time >= until_time) {
555 if (scan.current == "free")
556 relevant_free.push(scan);
557 else if (scan.current == "mine")
558 relevant_mine.push(scan);
561 // window.console.log("Found " + relevant_free.length + " free and " + relevant_mine.length + " mine");
562 /* decide what to do, whether book or release */
563 if (relevant_mine.length == 0 && relevant_free.length == 0) {
564 alert ("Nothing to do in this timeslot on the selected nodes");
567 // if at least one is free, let's book
568 if (relevant_free.length > 0) {
569 for (var i = 0, len = relevant_free.length; i < len; ++i) {
570 var lease = relevant_free[i];
571 scheduler._lease_init_mine(lease, scheduler._lease_click_free);
573 // otherwise we unselect
575 for (var i = 0, len = relevant_mine.length; i < len; ++i) {
576 var lease = relevant_mine[i];
577 scheduler._lease_init_free(lease, scheduler._lease_click_mine);
580 }, /* _timebutton_click */
582 /* ---------------------------------------------------------------------
583 * The nodelabel buttons
586 // set selected mode and render visually
587 _nodelabel_select: function (nodelabel, flag)
589 nodelabel.selected = flag;
590 nodelabel.attr({'font-weight': (flag ? 'bold' : 'normal')});
593 // loop on axis x and select each timebutton
594 // for (var i=0, len=axisx.length; i < len; ++i)
595 // figure out how to use timebutton_methods.click();
600 _nodelabel_click: function (event)
602 this.scheduler._nodelabel_select( this, ! this.selected );
606 /* ---------------------------------------------------------------------
609 _lease_init_free: function (lease, unclick)
611 var o = lease.scheduler.options;
612 lease.current = "free";
614 lease.animate((lease.initial == "free") ? attr_lease_free_free : attr_lease_mine_free, o.anim_delay);
615 // keep track of the current status
617 lease.click(this._lease_click_free);
618 if (unclick) lease.unclick(unclick);
621 // find out all the currently free leases that overlap this one
622 _lease_click_free: function (event)
624 var scheduler = this.scheduler;
626 scheduler._lease_init_mine(this, scheduler._lease_click_free);
632 var start_time = this.from_time.getTime() / 1000;
633 var end_time = this.until_time.getTime() / 1000;
634 var duration = (end_time - start_time) / 1800; // XXX HARDCODED LEASE GRAIN
636 /* Add a new lease : XXX should be replaced by a dictionary */
638 // Do we have a lease with the same urn just before or just after ?
639 //var removeIdBefore = null;
640 //var removeIdAfter = null;
641 var remove_lease_before = null;
642 var remove_lease_after = null;
643 // It is important to group leases, while this is technically
644 // equivalent, some testbeds such as IotLab limit the number of
645 // leases a user can have.
646 // XXX we might have several leases before or after if they have
647 // XXX not been grouped like this tool does
648 $.each(scheduler._leases, function(i, lease) {
649 if (lease[0] == urn) {
650 if (lease[1] + lease[2] * 1800 == start_time) { // XXX HARDCODED LEASE GRAIN
651 // Merge with previous lease
652 // removeIdBefore = i;
653 remove_lease_before = lease;
654 start_time = lease[1];
655 duration += lease[2];
657 if (lease[1] == end_time) {
658 // Merge with following lease
659 // removeIdAfter = i;
660 remove_lease_after = lease;
661 duration += lease[2];
665 //if (removeIdBefore != null) {
666 // scheduler._leases.splice(removeIdBefore , 1);
667 // if (removeIdAfter != null)
668 // removeIdAfter -= 1;
670 //if (removeIdAfter != null) {
671 // scheduler._leases.splice(removeIdAfter , 1);
674 // We add the new lease, no need to push
675 var new_lease = [this.urn, start_time, duration];
677 // We send events, manifold will inform us about the change and we will react accordingly
679 if (remove_lease_before != null)
680 manifold.raise_event(scheduler.options.query_lease_uuid, SET_REMOVED, remove_lease_before);
681 if (remove_lease_after != null)
682 manifold.raise_event(scheduler.options.query_lease_uuid, SET_REMOVED, remove_lease_after);
684 manifold.raise_event(scheduler.options.query_lease_uuid, SET_ADD, new_lease);
685 //scheduler._leases.push([this.urn, start_time, duration]);
687 //console.log(scheduler._leases);
688 //jQuery.publish('/update-set/' + scheduler.options.query_uuid, [scheduler._leases]);
690 /* We need to inform manifold about the whole diff, in addition to maintaining our own structure */
691 event.preventDefault();
694 _lease_init_mine: function (lease, unclick)
696 var o = lease.scheduler.options;
697 lease.current = "mine";
698 lease.animate((lease.initial == "mine") ? attr_lease_mine_mine : attr_lease_free_mine, o.anim_delay);
699 lease.click(this._lease_click_mine);
701 lease.unclick(unclick);
704 /* TODO: remove selected lease from array _leases and publish change */
705 _lease_click_mine: function (event)
707 var scheduler = this.scheduler;
708 // this lease was originally free but is now marked for booking
709 // we free just this lease
710 //console.log('this is mine');
711 scheduler._lease_init_free(this, scheduler._lease_click_mine);
712 event.preventDefault();
716 lease_init_other: function (lease, slicename)
718 lease.animate (attr_lease_other,anim_delay);
719 /* a text obj to display the name of the slice that owns that lease */
720 var otherslicelabel = lease.scheduler.paper.text (lease.attr("x")+lease.attr("width")/2,
722 lease.attr("y")+lease.attr("height")/2,slicename).attr(txt_otherslice);
723 /* hide it right away */
724 otherslicelabel.hide();
726 lease.label=otherslicelabel;
727 lease.hover ( function (e) {this.label.toFront();this.label.show();},
728 function (e) {this.label.hide();} );
733 $.plugin('Scheduler', Scheduler);