2 function debug_dict_keys (msg, o) {
4 for (var k in o) keys.push(k);
5 messages.debug ("debug_dict_keys: " + msg + " keys= " + keys);
7 function debug_dict (msg, o) {
8 for (var k in o) messages.debug ("debug_dict: " + msg + " [" + k + "]=" + o[k]);
10 function debug_value (msg, value) {
11 messages.debug ("debug_value: " + msg + " " + value);
13 function debug_query (msg, query) {
14 if (query === undefined) messages.debug ("debug_query: " + msg + " -> undefined");
15 else if (query == null) messages.debug ("debug_query: " + msg + " -> null");
16 else if ('query_uuid' in query) messages.debug ("debug_query: " + msg + query.__repr());
17 else messages.debug ("debug_query: " + msg + " query= " + query);
20 // http://stackoverflow.com/questions/7837456/comparing-two-arrays-in-javascript
21 // attach the .equals method to Array's prototype to call it on any array
22 Array.prototype.equals = function (array) {
23 // if the other array is a falsy value, return
27 // compare lengths - can save a lot of time
28 if (this.length != array.length)
31 for (var i = 0, l=this.length; i < l; i++) {
32 // Check if we have nested arrays
33 if (this[i] instanceof Array && array[i] instanceof Array) {
34 // recurse into the nested arrays
35 if (!this[i].equals(array[i]))
38 else if (this[i] != array[i]) {
39 // Warning - two different object instances will never be equal: {x:20} != {x:20}
46 // http://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript-typeof-operator/
47 Object.toType = (function toType(global) {
48 return function(obj) {
52 return ({}).toString.call(obj).match(/\s([a-z|A-Z]+)/)[1].toLowerCase();
56 /* ------------------------------------------------------------ */
58 // Constants that should be somehow moved to a plugin.js file
60 var FILTER_REMOVED = 2;
61 var CLEAR_FILTERS = 3;
63 var FIELD_REMOVED = 5;
66 var CLEAR_RECORDS = 8;
69 * event: FIELD_STATE_CHANGED
73 * .state : ???? used to be FIELD_REQUEST_ADD / FIELD_REQUEST_REMOVE
74 * .key : ??? the key fields of the record
75 * .op : the key of the record who has received an update
76 * .value : the new state of the record
78 var FIELD_STATE_CHANGED = 9;
80 var IN_PROGRESS = 101;
81 var DONE = 102; //XXX Should be harmonized with query state
83 /* Update requests related to subqueries */
87 var SET_REMOVED = 202;
92 var FIELD_REQUEST_CHANGE = 301;
93 var FIELD_REQUEST_ADD = 302;
94 var FIELD_REQUEST_REMOVE = 303;
95 var FIELD_REQUEST_ADD_RESET = 304;
96 var FIELD_REQUEST_REMOVE_RESET = 305;
98 // status (XXX Should be deprecated)
99 var FIELD_REQUEST_PENDING = 401;
100 var FIELD_REQUEST_SUCCESS = 402;
101 var FIELD_REQUEST_FAILURE = 403;
102 var STATUS_OKAY = 404;
103 var STATUS_SET_WARNING = 405;
104 var STATUS_ADD_WARNING = 406;
105 var STATUS_REMOVE_WARNING = 407;
106 var STATUS_RESET = 408;
108 /* Requests for query cycle */
109 var RUN_UPDATE = 601;
114 var TYPE_LIST_OF_VALUES = 3;
115 var TYPE_LIST_OF_RECORDS = 4;
117 /******************************************************************************
118 * QUERY STATUS (for manifold events)
119 ******************************************************************************/
121 var STATUS_NONE = 500; // Query has not been started yet
122 var STATUS_GET_IN_PROGRESS = 501; // Query has been sent, no result has been received
123 var STATUS_GET_RECEIVED = 502; // Success
124 var STATUS_GET_ERROR = 503; // Error
125 var STATUS_UPDATE_PENDING = 504;
126 var STATUS_UPDATE_IN_PROGRESS = 505;
127 var STATUS_UPDATE_RECEIVED = 506;
128 var STATUS_UPDATE_ERROR = 507;
130 /******************************************************************************
131 * QUERY STATE (for query_store)
132 ******************************************************************************/
134 // XXX Rendundant with query status ?
136 var QUERY_STATE_INIT = 0;
137 var QUERY_STATE_INPROGRESS = 1;
138 var QUERY_STATE_DONE = 2;
140 /******************************************************************************
141 * RECORD STATES (for query_store)
142 ******************************************************************************/
145 var STATE_VALUE = 21;
146 var STATE_WARNINGS = 22;
147 var STATE_VISIBLE = 23;
150 var STATE_SET_CHANGE = 0;
151 var STATE_SET_ADD = 1;
152 var STATE_SET_REMOVE = 2;
153 var STATE_SET_CLEAR = 3;
156 var STATE_SET_IN = 0;
157 var STATE_SET_OUT = 1;
158 var STATE_SET_IN_PENDING = 2;
159 var STATE_SET_OUT_PENDING = 3;
160 var STATE_SET_IN_SUCCESS = 4;
161 var STATE_SET_OUT_SUCCESS = 5;
162 var STATE_SET_IN_FAILURE = 6;
163 var STATE_SET_OUT_FAILURE = 7;
164 var STATE_VALUE_CHANGE_PENDING = 8;
165 var STATE_VALUE_CHANGE_SUCCESS = 9;
166 var STATE_VALUE_CHANGE_FAILURE = 10;
168 // STATE_WARNINGS : dict
170 // STATE_VISIBLE : boolean
172 /******************************************************************************
174 ******************************************************************************/
176 var CONSTRAINT_RESERVABLE_LEASE = 0;
178 var CONSTRAINT_RESERVABLE_LEASE_MSG = "Configuration required: this resource needs to be scheduled";
180 var CONSTRAINT_SLA = 1;
182 var CONSTRAINT_SLA_MSG = "SLA acceptance required: testbed offers SLA for its resources"
184 // A structure for storing queries
186 function QueryExt(query, parent_query_ext, main_query_ext, update_query_ext, disabled, domain_query_ext) {
189 if (typeof query == "undefined")
190 throw "Must pass a query in QueryExt constructor";
192 this.parent_query_ext = (typeof parent_query_ext == "undefined") ? null : parent_query_ext;
193 this.main_query_ext = (typeof main_query_ext == "undefined") ? null : main_query_ext;
194 this.update_query_ext = (typeof update_query_ext == "undefined") ? null : update_query_ext;
195 this.update_query_orig_ext = (typeof update_query_orig_ext == "undefined") ? null : update_query_orig_ext;
196 this.disabled = (typeof disabled == "undefined") ? false : disabled;
198 // A domain query is a query that is issued to retrieve all possible values for a set
199 // eg. all resources that can be attached to a slice
200 // It is null unless we are a subquery for which a domain query has been issued
201 this.domain_query_ext = (typeof domain_query_ext == "undefined") ? null : domain_query_ext;
203 // Set members to buffer until the domain query is completed
205 this.set_members = [];
207 // The set query is the query for which the domain query has been issued.
208 // It is null unless the query is a domain query
209 this.set_query_ext = (typeof set_query_ext == "undefined") ? null : domain_query_ext;
211 this.query_state = QUERY_STATE_INIT;
213 // Results from a query consists in a dict that maps keys to records
214 this.records = new Hashtable();
216 // Status is a dict that maps keys to record status
217 this.state = new Hashtable();
219 // Filters that impact visibility in the local interface
222 // XXX Until we find a better solution
223 this.num_pending = 0;
224 this.num_unconfigured = 0;
226 // update_query null unless we are a main_query (aka parent_query == null); only main_query_fields can be updated...
229 function QueryStore() {
231 this.main_queries = {};
232 this.analyzed_queries = {};
236 this.insert = function(query) {
237 // We expect only main_queries are inserted
239 /* If the query has not been analyzed, then we analyze it */
240 if (query.analyzed_query == null) {
241 query.analyze_subqueries();
244 /* We prepare the update query corresponding to the main query and store both */
245 /* Note: they have the same UUID */
247 // XXX query.change_action() should become deprecated
248 update_query = query.clone();
249 update_query.action = 'update';
250 update_query.fields = [];
251 update_query.analyzed_query.action = 'update';
252 update_query.params = {};
253 update_query_ext = new QueryExt(update_query);
255 /* We remember the original query to be able to reset it */
256 update_query_orig_ext = new QueryExt(update_query.clone());
259 /* We store the main query */
260 query_ext = new QueryExt(query, null, null, update_query_ext, update_query_orig_ext, false);
261 manifold.query_store.main_queries[query.query_uuid] = query_ext;
262 /* Note: the update query does not have an entry! */
265 // The query is disabled; since it is incomplete until we know the content of the set of subqueries
266 // XXX unless we have no subqueries ???
267 // we will complete with params when records are received... this has to be done by the manager
268 // SET_ADD, SET_REMOVE will change the status of the elements of the set
269 // UPDATE will change also, etc.
270 // XXX We need a proper structure to store this information...
272 // We also need to insert all queries and subqueries from the analyzed_query
273 // XXX We need the root of all subqueries
274 query.iter_subqueries(function(sq, data, parent_query) {
275 var parent_query_ext;
277 parent_query_ext = manifold.query_store.find_analyzed_query_ext(parent_query.query_uuid);
279 parent_query_ext = null;
281 // XXX parent_query_ext == false
282 // XXX main.subqueries = {} # Normal, we need analyzed_query
283 sq_ext = new QueryExt(sq, parent_query_ext, query_ext)
286 /* Let's issue a query for the subquery domain. This query will not need any update etc.
287 eg. for resources in a slice, we also query all resources */
288 var all_fields = manifold.metadata.get_field_names(sq.object);
289 var domain_query = new ManifoldQuery('get', sq.object, 'now', [], {}, all_fields);
290 //var domain_query = new ManifoldQuery('get', sq.object);
292 console.log("Created domain query", domain_query);
293 var domain_query_ext = new QueryExt(domain_query);
295 domain_query_ext.set_query_ext = sq_ext;
296 sq_ext.domain_query_ext = domain_query_ext;
298 // One of these two is useless ?
299 manifold.query_store.main_queries[domain_query.query_uuid] = domain_query_ext;
300 manifold.query_store.analyzed_queries[domain_query.query_uuid] = domain_query_ext;
302 // XXX This query is run before the plugins are initialized and listening
303 manifold.run_query(domain_query);
306 manifold.query_store.analyzed_queries[sq.query_uuid] = sq_ext;
309 // XXX We have spurious update queries...
314 this.find_query_ext = function(query_uuid)
316 return this.main_queries[query_uuid];
319 this.find_query = function(query_uuid)
321 return this.find_query_ext(query_uuid).query;
324 this.find_analyzed_query_ext = function(query_uuid)
326 return this.analyzed_queries[query_uuid];
329 this.find_analyzed_query = function(query_uuid)
331 return this.find_analyzed_query_ext(query_uuid).query;
334 this.state_dict_create = function(default_set)
336 default_set = (default_set === undefined) ? STATE_SET_OUT : default_set;
338 // We cannot use constants in literal definition, so...
339 state_dict[STATE_WARNINGS] = {};
340 state_dict[STATE_SET] = default_set;
341 state_dict[STATE_VISIBLE] = true;
347 this.set_records = function(query_uuid, records, default_set)
349 default_set = (default_set === undefined) ? STATE_SET_OUT : default_set;
352 var key, object, query_ext, record_key;
354 query_ext = this.find_analyzed_query_ext(query_uuid);
355 object = query_ext.query.object;
356 if (object.indexOf(':') != -1) {
357 object = object.split(':')[1];
359 record_key = manifold.metadata.get_key(object);
361 // ["start_time", "resource", "end_time"]
364 $.each(records, function(i, record) {
365 //var key = manifold.metadata.get_key(query_ext.query.object);
367 var record_key_value = manifold.record_get_value(record, record_key);
368 query_ext.records.put(record_key_value, record);
370 if (!(query_ext.state.get(record_key_value)))
371 query_ext.state.put(record_key_value, self.state_dict_create(default_set));
375 this.get_records = function(query_uuid)
377 var query_ext = this.find_analyzed_query_ext(query_uuid);
378 return query_ext.records.values();
381 this.get_record = function(query_uuid, record_key)
383 var query_ext = this.find_analyzed_query_ext(query_uuid);
384 return query_ext.records.get(record_key);
387 this.del_record = function(query_uuid, record_key)
389 var query_ext = this.find_analyzed_query_ext(query_uuid);
390 return query_ext.records.remove(record_key);
393 this.del_state = function(query_uuid, record_key)
395 var query_ext = this.find_analyzed_query_ext(query_uuid);
396 return query_ext.state.remove(record_key);
399 this.add_record = function(query_uuid, record, new_state)
401 var query_ext, key, record_key;
402 query_ext = this.find_analyzed_query_ext(query_uuid);
404 if (typeof(record) == 'object') {
405 key = manifold.metadata.get_key(query_ext.query.object);
406 record_key = manifold.record_get_value(record, key);
411 var record_entry = query_ext.records.get(record_key);
413 query_ext.records.put(record_key, record);
415 manifold.query_store.set_record_state(query_uuid, record_key, STATE_SET, new_state);
418 this.remove_record = function(query_uuid, record, new_state)
420 var query_ext, key, record_key;
421 query_ext = this.find_analyzed_query_ext(query_uuid);
423 if (typeof(record) == 'object') {
424 key = manifold.metadata.get_key(query_ext.query.object);
425 record_key = manifold.record_get_value(record, key);
430 if ((query_ext.query.object == 'lease') && (new_state == STATE_SET_OUT)) {
431 // Leases that are marked out are in fact leases from other slices
432 // We need to _remove_ leases that we mark as OUT
433 manifold.query_store.del_record(query_uuid, record_key);
434 manifold.query_store.del_state(query_uuid, record_key);
436 manifold.query_store.set_record_state(query_uuid, record_key, STATE_SET, new_state);
440 this.iter_records = function(query_uuid, callback)
442 var query_ext = this.find_analyzed_query_ext(query_uuid);
443 query_ext.records.each(callback);
444 //callback = function(record_key, record)
447 this.iter_visible_records = function(query_uuid, callback)
449 var query_ext = this.find_analyzed_query_ext(query_uuid);
450 query_ext.records.each(function(record_key, record) {
451 if (query_ext.state.get(record_key)[STATE_VISIBLE]) // .STATE_VISIBLE would be for the string key
452 callback(record_key, record);
454 //callback = function(record_key, record)
460 this.set_record_state = function(query_uuid, result_key, state, value)
462 var query_ext = this.find_analyzed_query_ext(query_uuid);
463 var state_dict = query_ext.state.get(result_key);
465 state_dict = this.state_dict_create();
467 state_dict[state] = value;
469 query_ext.state.put(result_key, state_dict);
472 this.get_record_state = function(query_uuid, result_key, state)
474 var query_ext = this.find_analyzed_query_ext(query_uuid);
475 var state_dict = query_ext.state.get(result_key);
478 return state_dict[state];
483 this.add_filter = function(query_uuid, filter)
485 var query_ext = this.find_analyzed_query_ext(query_uuid);
486 // XXX When we update a filter
487 query_ext.filters.push(filter);
489 this.apply_filters(query_uuid);
493 this.update_filter = function(query_uuid, filter)
497 this.apply_filters(query_uuid);
500 this.remove_filter = function(query_uuid, filter)
502 var query_ext = this.find_analyzed_query_ext(query_uuid);
503 query_ext.filters = $.grep(query_ext.filters, function(x) {
504 return !(x.equals(filter));
507 this.apply_filters(query_uuid);
510 this.get_filters = function(query_uuid)
512 var query_ext = this.find_analyzed_query_ext(query_uuid);
513 return query_ext.filters;
516 this.recount = function(query_uuid)
519 var is_reserved, is_pending, in_set, is_unconfigured;
521 query_ext = manifold.query_store.find_analyzed_query_ext(query_uuid);
522 query_ext.num_pending = 0;
523 query_ext.num_unconfigured = 0;
525 this.iter_records(query_uuid, function(record_key, record) {
526 var record_state = manifold.query_store.get_record_state(query_uuid, record_key, STATE_SET);
527 var record_warnings = manifold.query_store.get_record_state(query_uuid, record_key, STATE_WARNINGS);
529 is_reserved = (record_state == STATE_SET_IN)
530 || (record_state == STATE_SET_OUT_PENDING)
531 || (record_state == STATE_SET_IN_SUCCESS)
532 || (record_state == STATE_SET_OUT_FAILURE);
534 is_pending = (record_state == STATE_SET_IN_PENDING)
535 || (record_state == STATE_SET_OUT_PENDING);
537 in_set = (record_state == STATE_SET_IN) // should not have warnings
538 || (record_state == STATE_SET_IN_PENDING)
539 || (record_state == STATE_SET_IN_SUCCESS)
540 || (record_state == STATE_SET_OUT_FAILURE); // should not have warnings
542 is_unconfigured = (in_set && !$.isEmptyObject(record_warnings));
544 /* Let's update num_pending and num_unconfigured at this stage */
546 query_ext.num_pending++;
548 query_ext.num_unconfigured++;
553 this.apply_filters = function(query_uuid)
555 var start = new Date().getTime();
557 // Toggle visibility of records according to the different filters.
560 var filters = this.get_filters(query_uuid);
562 /* Let's update num_pending and num_unconfigured at this stage */
564 // Adapted from querytable._querytable_filter()
566 this.iter_records(query_uuid, function(record_key, record) {
567 var is_reserved, is_pending, in_set, is_unconfigured;
569 /* By default, a record is visible unless a filter says the opposite */
572 var record_state = manifold.query_store.get_record_state(query_uuid, record_key, STATE_SET);
573 var record_warnings = manifold.query_store.get_record_state(query_uuid, record_key, STATE_WARNINGS);
575 is_reserved = (record_state == STATE_SET_IN)
576 || (record_state == STATE_SET_OUT_PENDING)
577 || (record_state == STATE_SET_IN_SUCCESS)
578 || (record_state == STATE_SET_OUT_FAILURE);
580 is_pending = (record_state == STATE_SET_IN_PENDING)
581 || (record_state == STATE_SET_OUT_PENDING);
583 in_set = (record_state == STATE_SET_IN) // should not have warnings
584 || (record_state == STATE_SET_IN_PENDING)
585 || (record_state == STATE_SET_IN_SUCCESS)
586 || (record_state == STATE_SET_OUT_FAILURE); // should not have warnings
588 is_unconfigured = (in_set && !$.isEmptyObject(record_warnings));
590 // We go through each filter and decide whether it affects the visibility of the record
591 $.each(filters, function(index, filter) {
594 var value = filter[2];
597 /* We do some special handling for the manifold:status filter
600 if (key == 'manifold:status') {
601 if (op != '=' && op != '==') {
602 // Unsupported filter, let's ignore it
603 console.log("Unsupported filter on manifold:status. Should be EQUAL only.");
604 return true; // ~ continue
609 // true => ~ continue
611 visible = is_reserved;
614 visible = is_unconfigured;
617 visible = is_pending;
620 return false; // ~ break
623 /* Normal filtering behaviour (according to the record content) follows... */
624 col_value = manifold.record_get_value(record, key);
626 // When the filter does not match, we hide the column by default
627 if (col_value === 'undefined') {
629 return false; // ~ break
632 // XXX This should accept pluggable filtering functions.
635 /* Test whether current filter is compatible with the column */
636 if (op == '=' || op == '==') {
637 if ( col_value != value || col_value==null || col_value=="" || col_value=="n/a")
640 }else if (op == 'included') {
641 /* By default, the filter returns false unless the record
642 * field match at least one value of the included statement
645 $.each(value, function(i,x) {
648 return false; // ~ break
651 }else if (op == '!=') {
652 if ( col_value == value || col_value==null || col_value=="" || col_value=="n/a")
655 if ( parseFloat(col_value) >= value || col_value==null || col_value=="" || col_value=="n/a")
658 if ( parseFloat(col_value) <= value || col_value==null || col_value=="" || col_value=="n/a")
660 } else if(op=='<=' || op=='≤') {
661 if ( parseFloat(col_value) > value || col_value==null || col_value=="" || col_value=="n/a")
663 } else if(op=='>=' || op=='≥') {
664 if ( parseFloat(col_value) < value || col_value==null || col_value=="" || col_value=="n/a")
667 // How to break out of a loop ?
668 alert("filter not supported");
669 return false; // break
674 // Set the visibility status in the query store
675 self.set_record_state(query_uuid, record_key, STATE_VISIBLE, visible);
678 var end = new Date().getTime();
679 console.log("APPLY FILTERS [", filters, "] took", end - start, "ms");
686 * This namespace holds functions for globally managing query objects
691 /**************************************************************************
693 **************************************************************************/
697 get_type: function(variable) {
698 switch(Object.toType(variable)) {
705 if ((variable.length > 0) && (Object.toType(variable[0]) === 'object'))
706 return TYPE_LIST_OF_RECORDS;
708 return TYPE_LIST_OF_VALUES;
714 * fields: A String instance (field name), or a set of String instances
715 * (field names) # XXX tuple !!
717 * If fields is a String, return the corresponding value.
718 * If fields is a set, return a tuple of corresponding value.
721 * KeyError if at least one of the fields is not found
723 record_get_value: function(record, fields)
725 if (typeof(fields) === 'string') {
726 if (fields.indexOf('.') != -1) {
727 key_subkey = key.split('.', 2);
729 subkey = key_subkey[1];
731 if (record.indexOf(key) == -1) {
734 // Tests if the following is an array (typeof would give object)
735 if (Object.prototype.toString.call(record[key]) === '[object Array]') {
737 return $.map(record[key], function(subrecord) { return manifold.record_get_value(subrecord, subkey) });
738 } else if (typeof(record) == 'object') {
740 return manifold.record_get_value(record[key], subkey);
742 console.log('Unknown field');
744 // FIX if the record contains a string instead of a key:value
745 // example: select resource, slice_hrn from slice where slice_hrn=='xxx'
746 // Result will be {slice_hrn:'xxx', resource:'urn+zzz'}
747 // We don't have this resource:{urn:'urn+zzz'}
748 } else if(typeof(record) === 'string'){
751 return record[fields];
754 // see. get_map_entries
755 if (fields.length == 1)
756 return manifold.record_get_value(record, fields[0])
758 // Build a new record
760 $.each(fields, function(i, field) {
761 ret[field] = manifold.record_get_value(record, field);
763 ret.hashCode = record.hashCode;
764 ret.equals = record.equals;
766 // this was an array, we want a dictionary
767 //return $.map(fields, function(x) { manifold.record_get_value(record, x) });
772 record_hashcode: function(key_fields)
776 for (var i=0; i < key_fields.length; i++)
777 ret += "@@" + this[key_fields[i]];
782 _record_equals: function(self, other, key_fields)
784 if ((typeof self === "string") && (typeof other === "string")) {
785 return self == other;
787 for (var i=0; i < key_fields.length; i++) {
788 var this_value = self[key_fields[i]];
789 var other_value = other[key_fields[i]];
791 var this_type = manifold.get_type(this_value);
792 var other_type = manifold.get_type(other_value);
793 if (this_type != other_type)
798 case TYPE_LIST_OF_VALUES:
799 case TYPE_LIST_OF_RECORDS:
800 if (this_value != other_value)
804 if (!(_record_equals(this_value, other_value, key_fields)))
808 XXX WARNING = disabled for OpenFlow plugin !!!
810 case TYPE_LIST_OF_RECORDS:
811 if (this_value.length != other_value.length)
813 for (var j = 0; j < this_value.length; j++)
814 if (!(_record_equals(this_value[j], other_value[j], key_fields)))
823 record_equals: function(key_fields)
825 return function(other) {
826 return manifold._record_equals(this, other, key_fields);
830 _in_array: function(element, array, key_fields)
832 if (key_fields.length > 1) {
833 for (var i = 0; i < array.length; i++) {
834 if (manifold._record_equals(element, array[i], key_fields))
839 // XXX TODO If we have a dict, extract the key first
840 return ($.inArray(element, array) != -1);
844 /**************************************************************************
845 * Metadata management
846 **************************************************************************/
850 get_table: function(method) {
851 var table = MANIFOLD_METADATA[method];
852 return (typeof table === 'undefined') ? null : table;
855 get_columns: function(method) {
856 var table = this.get_table(method);
861 return (typeof table.column === 'undefined') ? null : table.column;
864 get_field_names: function(method)
866 var columns = this.get_columns(method);
869 return $.map(columns, function (x) { return x.name });
872 get_key: function(method) {
873 var table = this.get_table(method);
877 return (typeof table.key === 'undefined') ? null : table.key;
881 get_column: function(method, name) {
882 var columns = this.get_columns(method);
886 $.each(columns, function(i, c) {
893 get_type: function(method, name) {
894 var table = this.get_table(method);
898 var match = $.grep(table.column, function(x) { return x.name == name });
899 if (match.length == 0) {
902 return match[0].type;
904 return (typeof table.type === 'undefined') ? null : table.type;
909 /**************************************************************************
911 **************************************************************************/
913 query_store: new QueryStore(),
915 // XXX Remaining functions are deprecated since they are replaced by the query store
918 * Associative array storing the set of queries active on the page
924 * Insert a query in the global hash table associating uuids to queries.
925 * If the query has no been analyzed yet, let's do it.
926 * \fn insert_query(query)
928 * \param ManifoldQuery query Query to be added
930 insert_query : function (query) {
932 manifold.query_store.insert(query);
935 $(document).ready(function() {
936 manifold.run_query(query);
940 if (query.analyzed_query == null) {
941 query.analyze_subqueries();
943 manifold.all_queries[query.query_uuid]=query;
947 * Returns the query associated to a UUID
948 * \fn find_query(query_uuid)
950 * \param string query_uuid The UUID of the query to be returned
952 find_query : function (query_uuid) {
953 return manifold.all_queries[query_uuid];
956 /**************************************************************************
958 **************************************************************************/
960 // trigger a query asynchroneously
961 proxy_url : '/manifold/proxy/json/',
963 // reasonably low-noise, shows manifold requests coming in and out
964 asynchroneous_debug : true,
965 // print our more details on result publication and related callbacks
966 pubsub_debug : false,
969 * \brief We use js function closure to be able to pass the query (array)
970 * to the callback function used when data is received
972 success_closure: function(query, publish_uuid, callback) {
973 return function(data, textStatus) {
974 manifold.asynchroneous_success(data, query, publish_uuid, callback);
978 run_query: function(query, callback)
980 // default value for callback = null
981 if (typeof callback === 'undefined')
984 var query_ext = manifold.query_store.find_query_ext(query.query_uuid);
985 query_ext.query_state = QUERY_STATE_INPROGRESS;
988 If the Query object concerns SFA AM objects, iterate on each AM platform
989 Loop per platform, allows a progressive loading per AM platform
990 Update is run on all platforms at the same time to get a final answer, we don't manage partial answers yet...
992 // Removed slice from the per platform query - it's quick enough...
993 if((query.object == 'resource' || query.object == 'lease') && query.action != "update"){
994 var obj = query.object;
995 $.post("/rest/platform/", function( data ) {
996 $.each(data, function(index, p) {
997 query.object = p.platform+":"+obj;
998 var query_json = JSON.stringify(query);
1000 // Inform plugins about the progress
1001 query.iter_subqueries(function (sq) {
1002 var sq_query_ext = manifold.query_store.find_analyzed_query_ext(sq.query_uuid);
1003 sq_query_ext.query_state = QUERY_STATE_INPROGRESS;
1004 manifold.raise_record_event(sq.query_uuid, IN_PROGRESS);
1007 $.post(manifold.proxy_url, {'json': query_json} , manifold.success_closure(query, null, callback));
1013 var query_json = JSON.stringify(query);
1015 // Inform plugins about the progress
1016 query.iter_subqueries(function (sq) {
1017 var sq_query_ext = manifold.query_store.find_analyzed_query_ext(sq.query_uuid);
1018 sq_query_ext.query_state = QUERY_STATE_INPROGRESS;
1019 manifold.raise_record_event(sq.query_uuid, IN_PROGRESS);
1022 $.post(manifold.proxy_url, {'json': query_json} , manifold.success_closure(query, null, callback));
1028 // Executes all async. queries - intended for the javascript header to initialize queries
1029 // input queries are specified as a list of {'query_uuid': <query_uuid> }
1030 // each plugin is responsible for managing its spinner through on_query_in_progress
1031 asynchroneous_exec : function (query_exec_tuples) {
1033 // Loop through input array, and use publish_uuid to publish back results
1034 $.each(query_exec_tuples, function(index, tuple) {
1035 var query=manifold.find_query(tuple.query_uuid);
1036 var query_json=JSON.stringify (query);
1037 var publish_uuid=tuple.publish_uuid;
1038 // by default we publish using the same uuid of course
1039 if (publish_uuid==undefined) publish_uuid=query.query_uuid;
1040 if (manifold.pubsub_debug) {
1041 messages.debug("sending POST on " + manifold.proxy_url + query.__repr());
1044 query.iter_subqueries(function (sq) {
1045 manifold.raise_record_event(sq.query_uuid, IN_PROGRESS);
1048 // not quite sure what happens if we send a string directly, as POST data is named..
1049 // this gets reconstructed on the proxy side with ManifoldQuery.fill_from_POST
1050 $.post(manifold.proxy_url, {'json':query_json},
1051 manifold.success_closure(query, publish_uuid, tuple.callback));
1056 * \brief Forward a query to the manifold backend
1057 * \param query (dict) the query to be executed asynchronously
1058 * \param callback (function) the function to be called when the query terminates
1060 forward: function(query, callback) {
1061 var query_json = JSON.stringify(query);
1062 $.post(manifold.proxy_url, {'json': query_json} ,
1063 manifold.success_closure(query, query.query_uuid, callback));
1067 * Returns whether a query expects a unique results.
1068 * This is the case when the filters contain a key of the object
1069 * \fn query_expects_unique_result(query)
1070 * \memberof Manifold
1071 * \param ManifoldQuery query Query for which we are testing whether it expects a unique result
1073 query_expects_unique_result: function(query) {
1074 /* XXX we need functions to query metadata */
1075 //var keys = MANIFOLD_METADATA[query.object]['keys']; /* array of array of field names */
1076 /* TODO requires keys in metadata */
1082 * \fn publish_result(query, results)
1083 * \memberof Manifold
1084 * \param ManifoldQuery query Query which has received results
1085 * \param array results results corresponding to query
1087 publish_result: function(query, result) {
1088 if (typeof result === 'undefined')
1092 manifold.raise_record_event(query.query_uuid, CLEAR_RECORDS);
1093 if (manifold.pubsub_debug)
1094 messages.debug(".. publish_result (1) ");
1096 $.each(result, function(i, record) {
1097 manifold.raise_record_event(query.query_uuid, NEW_RECORD, record);
1100 if (manifold.pubsub_debug)
1101 messages.debug(".. publish_result (2) has used NEW API on " + count + " records");
1102 manifold.raise_record_event(query.query_uuid, DONE);
1103 if (manifold.pubsub_debug)
1104 messages.debug(".. publish_result (3) has used NEW API to say DONE");
1106 // OLD PLUGIN API BELOW
1107 /* Publish an update announce */
1108 var channel="/results/" + query.query_uuid + "/changed";
1109 if (manifold.pubsub_debug)
1110 messages.debug(".. publish_result (4) OLD API on channel" + channel);
1112 $.publish(channel, [result, query]);
1114 if (manifold.pubsub_debug)
1115 messages.debug(".. publish_result (5) END q=" + query.__repr());
1118 store_records: function(query, records) {
1120 var query_ext = manifold.query_store.find_analyzed_query_ext(query.query_uuid);
1121 if (query_ext.set_query_ext) {
1122 // We have a domain query
1123 // The results are stored in the corresponding set_query
1124 manifold.query_store.set_records(query_ext.set_query_ext.query.query_uuid, records);
1126 } else if (query_ext.domain_query_ext) {
1127 // We have a set query, it is only used to determine which objects are in the set, we should only retrieve the key
1128 // Has it a domain query, and has it completed ?
1129 $.each(records, function(i, record) {
1130 var key = manifold.metadata.get_key(query.object);
1131 if ( typeof record === "string" ){
1132 var record_key = record;
1134 var record_key = manifold.record_get_value(record, key);
1136 manifold.query_store.set_record_state(query.query_uuid, record_key, STATE_SET, STATE_SET_IN);
1140 // We have a normal query
1141 manifold.query_store.set_records(query.query_uuid, records, STATE_SET_IN);
1146 * Recursively publish result
1147 * \fn publish_result_rec(query, result)
1148 * \memberof Manifold
1149 * \param ManifoldQuery query Query which has received result
1150 * \param array result result corresponding to query
1152 * Note: this function works on the analyzed query
1154 publish_result_rec: function(query, records) {
1155 /* If the result is not unique, only publish the top query;
1156 * otherwise, publish the main object as well as subqueries
1157 * XXX how much recursive are we ?
1159 if (manifold.pubsub_debug)
1160 messages.debug (">>>>> publish_result_rec " + query.object);
1161 if (manifold.query_expects_unique_result(query)) {
1162 /* Also publish subqueries */
1163 $.each(query.subqueries, function(object, subquery) {
1164 manifold.publish_result_rec(subquery, records[0][object]);
1165 /* TODO remove object from result */
1168 if (manifold.pubsub_debug)
1169 messages.debug ("===== publish_result_rec " + query.object);
1171 var query_ext = manifold.query_store.find_analyzed_query_ext(query.query_uuid);
1172 query_ext.query_state = QUERY_STATE_DONE;
1174 this.store_records(query, records);
1178 if (query_ext.set_query_ext) {
1179 if (query_ext.set_query_ext.query_state != QUERY_STATE_DONE)
1181 pub_query = query_ext.set_query_ext.query;
1182 } else if (query_ext.domain_query_ext) {
1183 if (query_ext.domain_query_ext.query_state != QUERY_STATE_DONE)
1189 // We can only publish results if the query (and its related domain query) is complete
1190 manifold.publish_result(pub_query, records);
1192 if (manifold.pubsub_debug)
1193 messages.debug ("<<<<< publish_result_rec " + query.object);
1196 setup_update_query: function(query, records)
1198 // We don't prepare an update query if the result has more than 1 entry
1199 if (records.length != 1)
1201 var query_ext = manifold.query_store.find_query_ext(query.query_uuid);
1203 var record = records[0];
1205 var update_query_ext = query_ext.update_query_ext;
1207 if (!update_query_ext)
1210 var update_query = update_query_ext.query;
1211 var update_query_ext = query_ext.update_query_ext;
1212 var update_query_orig = query_ext.update_query_orig_ext.query;
1214 // Testing whether the result has subqueries (one level deep only)
1215 // iif the query has subqueries
1217 var obj = query.analyzed_query.subqueries;
1218 for (method in obj) {
1219 if (obj.hasOwnProperty(method)) {
1220 var key = manifold.metadata.get_key(method);
1224 var subrecords = record[method];
1227 $.each(subrecords, function (i, subrecord) {
1228 sq_keys.push(manifold.record_get_value(subrecord, key));
1230 update_query.params[method] = sq_keys;
1231 update_query_orig.params[method] = sq_keys.slice();
1237 update_query_ext.disabled = false;
1238 update_query_orig_ext.disabled = false;
1242 process_get_query_records: function(query, records) {
1243 this.setup_update_query(query, records);
1245 var query_ext = manifold.query_store.find_query_ext(query.query_uuid);
1246 query_ext.query_state = QUERY_STATE_DONE;
1248 /* Publish full results */
1249 var tmp_query = manifold.query_store.find_analyzed_query(query.query_uuid);
1250 manifold.publish_result_rec(tmp_query, records);
1253 make_records: function(object, records)
1255 $.each(records, function(i, record) {
1256 manifold.make_record(object, record);
1260 make_record: function(object, record)
1262 // To make an object a record, we just add the hash function
1263 var key, new_object;
1265 if (object.indexOf(':') != -1) {
1266 new_object = object.split(':')[1];
1268 new_object = object;
1271 key = manifold.metadata.get_key(new_object);
1273 console.log("object type: " + new_object + " has no key");
1274 console.log(record);
1277 record.hashCode = manifold.record_hashcode(key.sort());
1278 record.equals = manifold.record_equals(key);
1280 // Looking after subrecords
1281 for (var field in record) {
1282 var result_value = record[field];
1284 switch (this.get_type(result_value)) {
1286 var subobject = manifold.metadata.get_type(object, field);
1287 // if (subobject) XXX Bugs with fields declared string while they are not : network.version is a dict in fact
1288 if (subobject && subobject != 'string')
1289 manifold.make_record(subobject, result_value);
1291 case TYPE_LIST_OF_RECORDS:
1292 var subobject = manifold.metadata.get_type(object, field);
1294 manifold.make_records(subobject, result_value);
1302 * What we need to do when receiving results from an update query:
1303 * - differences between what we had, what we requested, and what we obtained
1304 * . what we had : update_query_orig (simple fields and set fields managed differently)
1305 * . what we requested : update_query
1306 * . what we received : records
1307 * - raise appropriate events
1309 * The normal process is that results similar to Get will be pushed in the
1310 * pubsub mechanism, thus repopulating everything while we only need
1311 * diff's. This means we need to move the publish functionalities in the
1312 * previous 'process_get_query_records' function.
1314 process_update_query_records: function(query, records) {
1315 // First issue: we request everything, and not only what we modify, so will will have to ignore some fields
1316 var query_uuid = query.query_uuid;
1317 var query_ext = manifold.query_store.find_analyzed_query_ext(query_uuid);
1318 var update_query = query_ext.main_query_ext.update_query_ext.query;
1319 var update_query_orig = query_ext.main_query_ext.update_query_orig_ext.query;
1321 // Since we update objects one at a time, we can get the first record
1322 var record = records[0];
1324 // Let's iterate over the object properties
1325 for (var field in record) {
1326 var result_value = record[field];
1327 switch (this.get_type(result_value)) {
1329 // Did we ask for a change ?
1330 var update_value = update_query[field];
1332 // Not requested, if it has changed: OUT OF SYNC
1333 // How we can know ?
1334 // We assume it won't have changed
1338 throw "Internal error";
1344 value : (update_value == result_value) ? STATE_VALUE_CHANGE_SUCCESS : STATE_VALUE_CHANGE_FAILURE,
1346 manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
1350 throw "Not implemented";
1354 case TYPE_LIST_OF_VALUES:
1355 // Same as list of records, but we don't have to extract keys
1357 // The rest of exactly the same (XXX factorize)
1358 var update_keys = update_query_orig.params[field];
1359 var query_keys = update_query.params[field];
1360 var added_keys = $.grep(query_keys, function (x) { return $.inArray(x, update_keys) == -1 });
1361 var removed_keys = $.grep(update_keys, function (x) { return $.inArray(x, query_keys) == -1 });
1364 $.each(added_keys, function(i, key) {
1365 if ($.inArray(key, result_value) == -1) {
1367 request: FIELD_REQUEST_ADD,
1370 status: FIELD_REQUEST_FAILURE,
1374 request: FIELD_REQUEST_ADD,
1377 status: FIELD_REQUEST_SUCCESS,
1380 manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
1382 $.each(removed_keys, function(i, key) {
1383 if ($.inArray(key, result_keys) == -1) {
1385 request: FIELD_REQUEST_REMOVE,
1388 status: FIELD_REQUEST_SUCCESS,
1392 request: FIELD_REQUEST_REMOVE,
1395 status: FIELD_REQUEST_FAILURE,
1398 manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
1404 case TYPE_LIST_OF_VALUES: // XXX Until fixed
1405 case TYPE_LIST_OF_RECORDS:
1406 var key, new_state, cur_query_uuid;
1407 if($.inArray(field,Object.keys(query.analyzed_query.subqueries)) > -1){
1408 cur_query_uuid = query.analyzed_query.subqueries[field].query_uuid;
1411 // example: slice.resource
1412 // - update_query_orig.params.resource = resources in slice before update
1413 // - update_query.params.resource = resource requested in slice
1414 // - keys from field = resources obtained
1416 if (field == 'lease') {
1417 // lease_id has been added to be repeated when
1418 // constructing request rspec. We don't want it for
1420 key = ['start_time', 'end_time', 'resource'];
1422 key = manifold.metadata.get_key(field);
1427 if (key.length > 1) {
1428 throw "Not implemented";
1434 /* XXX should be modified for multiple keys */
1435 var result_keys = $.map(record[field], function(x) { return manifold.record_get_value(x, key); });
1437 // XXX All this could be deduced from record state : STATE_IN_PENDING and STATE_OUT_PENDING
1438 // what we had at the begining
1439 var update_keys = update_query_orig.params[field];
1441 var query_keys = update_query.params[field];
1442 // what we added and removed
1443 var added_keys = $.grep(query_keys, function (x) { return (!(manifold._in_array(x, update_keys, key))); });
1444 var removed_keys = $.grep(update_keys, function (x) { return (!(manifold._in_array(x, query_keys, key))); });
1446 // Send events related to parent query
1447 $.each(added_keys, function(i, added_key) {
1448 new_state = (manifold._in_array(added_key, result_keys, key)) ? STATE_SET_IN_SUCCESS : STATE_SET_IN_FAILURE;
1450 // Update record state for children queries
1451 manifold.query_store.set_record_state(cur_query_uuid, added_key, STATE_SET, new_state);
1453 // XXX This could be optimized
1454 manifold.query_store.recount(cur_query_uuid);
1456 data = { state: STATE_SET, key : field, op : new_state, value: added_key }
1457 manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
1459 // Inform subquery also
1461 manifold.raise_record_event(cur_query_uuid, FIELD_STATE_CHANGED, data);
1462 // XXX Passing no parameters so that they can redraw everything would
1463 // be more efficient but is currently not supported
1464 // XXX We could also need to inform plugins about nodes IN (not pending) that are no more, etc.
1465 // XXX refactor all this when suppressing update_queries, and relying on state instead !
1467 $.each(removed_keys, function(i, removed_key) {
1468 new_state = (manifold._in_array(removed_key, result_keys, key)) ? STATE_SET_OUT_FAILURE : STATE_SET_OUT_SUCCESS;
1470 // Update record state for children queries
1471 manifold.query_store.set_record_state(cur_query_uuid, removed_key, STATE_SET, new_state);
1473 // XXX This could be optimized
1474 manifold.query_store.recount(cur_query_uuid);
1476 data = { state: STATE_SET, key : field, op : new_state, value: removed_key }
1477 manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
1479 // Inform subquery also
1481 manifold.raise_record_event(cur_query_uuid, FIELD_STATE_CHANGED, data);
1488 // XXX Now we need to adapt 'update' and 'update_orig' queries as if we had done a get
1489 this.setup_update_query(query, records);
1491 var query_ext = manifold.query_store.find_query_ext(query.query_uuid);
1492 query_ext.query_state = QUERY_STATE_DONE;
1494 var tmp_query = manifold.query_store.find_analyzed_query(query.query_uuid);
1495 manifold.publish_result_rec(tmp_query, records);
1497 // Send DONE message to plugins
1498 query.iter_subqueries(function(sq, data, parent_query) {
1499 manifold.raise_record_event(sq.query_uuid, DONE);
1504 process_query_records: function(query, records) {
1505 if (query.action == 'get') {
1506 this.process_get_query_records(query, records);
1507 } else if (query.action == 'update') {
1508 this.process_update_query_records(query, records);
1512 // if set callback is provided it is called
1513 // most of the time publish_uuid will be query.query_uuid
1514 // however in some cases we wish to publish the result under a different uuid
1515 // e.g. an updater wants to publish its result as if from the original (get) query
1516 asynchroneous_success : function (data, query, publish_uuid, callback) {
1517 // xxx should have a nicer declaration of that enum in sync with the python code somehow
1519 var start = new Date();
1520 if (manifold.asynchroneous_debug)
1521 messages.debug(">>>>>>>>>> asynchroneous_success query.object=" + query.object);
1523 if (data.code == 2) { // ERROR
1524 // We need to make sense of error codes here
1525 alert("Your session has expired, please log in again");
1526 localStorage.removeItem('user');
1527 window.location="/logout/";
1528 if (manifold.asynchroneous_debug) {
1529 duration=new Date()-start;
1530 messages.debug ("<<<<<<<<<< asynchroneous_success " + query.object + " -- error returned - logging out " + duration + " ms");
1534 if (data.code == 1) { // WARNING
1535 messages.error("Some errors have been received from the manifold backend at " + MANIFOLD_URL + " [" + data.description + "]");
1536 // publish error code and text message on a separate channel for whoever is interested
1538 $.publish("/results/" + publish_uuid + "/failed", [data.code, data.description] );
1542 // If a callback has been specified, we redirect results to it
1545 if (manifold.asynchroneous_debug) {
1546 duration=new Date()-start;
1547 messages.debug ("<<<<<<<<<< asynchroneous_success " + query.object + " -- callback ended " + duration + " ms");
1552 if (manifold.asynchroneous_debug)
1553 messages.debug ("========== asynchroneous_success " + query.object + " -- before process_query_records [" + query.query_uuid +"]");
1555 // once everything is checked we can use the 'value' part of the manifoldresult
1556 var result=data.value;
1558 /* Eventually update the content of related queries (update, etc) */
1559 manifold.make_records(query.object, result);
1560 this.process_query_records(query, result);
1562 /* Publish results: disabled here, done in the previous call */
1563 //tmp_query = manifold.find_query(query.query_uuid);
1564 //manifold.publish_result_rec(tmp_query.analyzed_query, result);
1566 if (manifold.asynchroneous_debug) {
1567 duration=new Date()-start;
1568 messages.debug ("<<<<<<<<<< asynchroneous_success " + query.object + " -- done " + duration + " ms");
1573 /**************************************************************************
1574 * Plugin API helpers
1575 **************************************************************************/
1577 raise_event_handler: function(type, query_uuid, event_type, value) {
1578 if (manifold.pubsub_debug)
1579 messages.debug("raise_event_handler, quuid="+query_uuid+" type="+type+" event_type="+event_type);
1580 if ((type != 'query') && (type != 'record'))
1581 throw 'Incorrect type for manifold.raise_event()';
1582 // xxx we observe quite a lot of incoming calls with an undefined query_uuid
1583 // this should be fixed upstream in manifold I expect
1584 if (query_uuid === undefined) {
1585 messages.warning("undefined query in raise_event_handler");
1589 // notify the change to objects that either listen to this channel specifically,
1590 // or to the wildcard channel
1591 var channels = [ manifold.get_channel(type, query_uuid), manifold.get_channel(type, '*') ];
1593 $.each(channels, function(i, channel) {
1594 if (value === undefined) {
1595 if (manifold.pubsub_debug) messages.debug("triggering [no value] on channel="+channel+" and event_type="+event_type);
1596 $('.pubsub').trigger(channel, [event_type]);
1598 if (manifold.pubsub_debug) messages.debug("triggering [value="+value+"] on channel="+channel+" and event_type="+event_type);
1599 $('.pubsub').trigger(channel, [event_type, value]);
1604 raise_query_event: function(query_uuid, event_type, value) {
1605 manifold.raise_event_handler('query', query_uuid, event_type, value);
1608 raise_record_event: function(query_uuid, event_type, value) {
1609 manifold.raise_event_handler('record', query_uuid, event_type, value);
1613 * Event handler helpers
1615 _get_next_state_add: function(prev_state)
1617 switch (prev_state) {
1619 case STATE_SET_OUT_SUCCESS:
1620 case STATE_SET_IN_FAILURE:
1621 new_state = STATE_SET_IN_PENDING;
1624 case STATE_SET_OUT_PENDING:
1625 new_state = STATE_SET_IN;
1629 case STATE_SET_IN_PENDING:
1630 case STATE_SET_IN_SUCCESS:
1631 case STATE_SET_OUT_FAILURE:
1632 console.log("Inconsistent state: already in");
1638 _get_next_state_remove: function(prev_state)
1640 switch (prev_state) {
1642 case STATE_SET_IN_SUCCESS:
1643 case STATE_SET_OUT_FAILURE:
1644 new_state = STATE_SET_OUT_PENDING;
1647 case STATE_SET_IN_PENDING:
1648 new_state = STATE_SET_OUT;
1652 case STATE_SET_OUT_PENDING:
1653 case STATE_SET_OUT_SUCCESS:
1654 case STATE_SET_IN_FAILURE:
1655 console.log("Inconsistent state: already out");
1661 _grep_active_lease_callback: function(lease_query, resource_key) {
1662 return function(lease_key_lease) {
1663 var state, lease_key, lease;
1665 lease_key = lease_key_lease[0];
1666 lease = lease_key_lease[1];
1668 if (lease['resource'] != resource_key)
1671 state = manifold.query_store.get_record_state(lease_query.query_uuid, lease_key, STATE_SET);;
1674 case STATE_SET_IN_PENDING:
1675 case STATE_SET_IN_SUCCESS:
1676 case STATE_SET_OUT_FAILURE:
1679 case STATE_SET_OUT_PENDING:
1680 case STATE_SET_OUT_SUCCESS:
1681 case STATE_SET_IN_FAILURE:
1687 _enforce_constraints: function(query_ext, record, record_key, event_type)
1691 query = query_ext.query;
1693 switch(query.object) {
1697 var warnings = manifold.query_store.get_record_state(query.query_uuid, record_key, STATE_WARNINGS);
1698 // CONSTRAINT_RESERVABLE_LEASE
1700 // +) If a reservable node is added to the slice, then it should have a corresponding lease
1701 // XXX Not always a resource
1702 var is_reservable = (record.exclusive == true);
1703 if (is_reservable) {
1704 // var warnings = manifold.query_store.get_record_state(query.query_uuid, record_key, STATE_WARNINGS);
1706 if (event_type == STATE_SET_ADD) {
1707 // We should have a lease_query associated
1708 var lease_query = query_ext.parent_query_ext.query.subqueries['lease']; // in options
1709 var lease_query_ext = manifold.query_store.find_analyzed_query_ext(lease_query.query_uuid);
1710 // Do we have lease records (in) with this resource
1711 var lease_records = $.grep(lease_query_ext.records.entries(), this._grep_active_lease_callback(lease_query, record_key));
1712 if (lease_records.length == 0) {
1714 // XXX Need for a better function to manage warnings
1715 var warn = CONSTRAINT_RESERVABLE_LEASE_MSG;
1716 warnings[CONSTRAINT_RESERVABLE_LEASE] = warn;
1718 /*manifold.query_store.set_record_state(query.query_uuid, record_key, STATE_WARNINGS, warnings);
1719 // Signal the change to plugins (even if the constraint does not apply, so that the plugin can display a checkmark)
1721 state: STATE_WARNINGS,
1726 manifold.raise_record_event(query.query_uuid, FIELD_STATE_CHANGED, data);*/
1729 // Lease are defined, delete the warning in case it was set previously
1730 delete warnings[CONSTRAINT_RESERVABLE_LEASE];
1733 // Remove warnings attached to this resource
1734 delete warnings[CONSTRAINT_RESERVABLE_LEASE];
1738 /*var urn_regexp = /\+(.*?)\+/;
1739 var testbed_urn = urn_regexp.exec(record.urn)[1];
1740 var has_sla = $.inArray(testbed_urn, localStorage.getItem("sla_testbeds").split(",")) != -1;
1743 // var warnings = manifold.query_store.get_record_state(query.query_uuid, record_key, STATE_WARNINGS);
1745 if (event_type == STATE_SET_ADD) {
1746 var warn = CONSTRAINT_SLA_MSG;
1747 warnings[CONSTRAINT_SLA] = warn;
1749 delete warnings[CONSTRAINT_SLA];
1753 manifold.query_store.set_record_state(query.query_uuid, record_key, STATE_WARNINGS, warnings);
1754 // Signal the change to plugins (even if the constraint does not apply, so that the plugin can display a checkmark)
1756 state: STATE_WARNINGS,
1761 manifold.raise_record_event(query.query_uuid, FIELD_STATE_CHANGED, data);
1764 /*get_testbeds_with_sla()
1765 .done( function(testbeds) {
1766 var urn_regexp = /\+(.*?)\+/;
1767 var testbed_urn = urn_regexp.exec(record.urn)[1];
1769 var warnings = manifold.query_store.get_record_state(query.query_uuid, record_key, STATE_WARNINGS);
1771 if ($.inArray(testbed_urn, testbeds) != -1) {
1772 // JGLL: Set a warning on resources covered by testbeds offering SLAs
1775 if (event_type == STATE_SET_ADD) {
1776 var warn = CONSTRAINT_SLA_MSG;
1777 warnings[CONSTRAINT_SLA] = warn;
1779 delete warnings[CONSTRAINT_SLA]
1783 manifold.query_store.set_record_state(query.query_uuid, record_key, STATE_WARNINGS, warnings);
1785 // Signal the change to plugins (even if the constraint does not apply, so that the plugin can display a checkmark)
1787 state: STATE_WARNINGS,
1793 manifold.raise_record_event(query.query_uuid, FIELD_STATE_CHANGED, data);
1795 .fail( function(err) {
1796 console.log("SLA - Error retrieving testbeds that support SLAs");
1799 /* This was redundant */
1800 // manifold.query_store.recount(query.query_uuid);
1805 var resource_key = record_key.resource;
1806 var resource_query = query_ext.parent_query_ext.query.subqueries['resource'];
1807 var warnings = manifold.query_store.get_record_state(resource_query.query_uuid, resource_key, STATE_WARNINGS);
1809 if (event_type == STATE_SET_ADD || event_type == STATE_SET_IN_PENDING) {
1810 // A lease is added, it removes the constraint
1811 delete warnings[CONSTRAINT_RESERVABLE_LEASE];
1813 // A lease is removed, it might trigger the warning
1814 var lease_records = $.grep(query_ext.records.entries(), this._grep_active_lease_callback(query, resource_key));
1815 if (lease_records.length == 0) { // XXX redundant cases
1817 // XXX Need for a better function to manage warnings
1818 var warn = CONSTRAINT_RESERVABLE_LEASE_MSG;
1819 warnings[CONSTRAINT_RESERVABLE_LEASE] = warn;
1821 // Signal the change to plugins (even if the constraint does not apply, so that the plugin can display a checkmark)
1823 state: STATE_WARNINGS,
1828 manifold.raise_record_event(resource_query.query_uuid, FIELD_STATE_CHANGED, data);
1830 // Lease are defined, delete the warning in case it was set previously
1831 delete warnings[CONSTRAINT_RESERVABLE_LEASE];
1834 /* Adding a lease can remove a warning and reduce the unconfigured resources */
1835 manifold.query_store.recount(resource_query.query_uuid);
1839 // -) When a lease is added, it might remove the warning associated to a reservable node
1841 // If a NITOS node is reserved, then at least a NITOS channel should be reserved
1842 // - When a NITOS channel is added, it might remove a warning associated to all NITOS nodes
1844 // If a NITOS channel is reserved, then at least a NITOS node should be reserved
1845 // - When a NITOS node is added, it might remove a warning associated to all NITOS channels
1847 // A lease is present while the resource has been removed => Require warnings on nodes not in set !
1851 _get_query_path: function(query_ext) {
1854 while (sq.parent_query_ext) {
1857 path = sq.query.object + path;
1858 sq = sq.parent_query_ext;
1865 * Handling events raised by plugins
1867 raise_event: function(query_uuid, event_type, data)
1869 var query, query_ext;
1871 // Query uuid has been updated with the key of a new element
1872 query_ext = manifold.query_store.find_analyzed_query_ext(query_uuid);
1873 query = query_ext.query;
1875 switch(event_type) {
1876 case STATUS_REMOVE_WARNING:
1877 record = manifold.query_store.get_record(query_uuid, data.value);
1878 this._enforce_constraints(query_ext, record, data.value, STATE_SET_REMOVE);
1881 // XXX At some point, should be renamed to RECORD_STATE_CHANGED
1882 case FIELD_STATE_CHANGED:
1884 // value is an object (request, key, value, status)
1885 // update is only possible is the query is not pending, etc
1886 // SET_ADD is on a subquery, FIELD_STATE_CHANGED on the query itself
1887 // we should map SET_ADD on this...
1889 // 1. Update internal query store about the change in status
1891 // 2. Update the update query
1892 update_query = query_ext.main_query_ext.update_query_ext.query;
1893 update_query_orig = query_ext.main_query_ext.update_query_orig_ext.query;
1895 switch(data.state) {
1900 /* Set parameter data.key in the update_query to VALUE */
1901 if (update_query.params[data.key] === undefined)
1902 update_query.params[data.key] = Array();
1903 update_query.params[data.key] = value.value;
1910 var prev_state, new_state;
1911 var main_query, record, new_data, path;
1913 // We only track state in the analyzed query
1914 prev_state = manifold.query_store.get_record_state(query_uuid, data.value, STATE_SET);
1915 if (prev_state === null)
1916 prev_state = STATE_SET_OUT;
1920 new_state = this._get_next_state_add(prev_state);
1922 /* data.value containts the resource key */
1923 manifold.query_store.add_record(query_uuid, data.value, new_state);
1924 record = manifold.query_store.get_record(query_uuid, data.value);
1925 this._enforce_constraints(query_ext, record, data.value, STATE_SET_ADD);
1927 /* Process update query in parent */
1928 path = this._get_query_path(query_ext);
1929 if (update_query.params[path] === undefined)
1930 update_query.params[path] = Array();
1931 update_query.params[path].push(data.value);
1935 case STATE_SET_REMOVE:
1936 new_state = this._get_next_state_remove(prev_state);
1938 /* data.value contains the resource key */
1939 manifold.query_store.remove_record(query_uuid, data.value, new_state);
1940 record = manifold.query_store.get_record(query_uuid, data.value);
1941 this._enforce_constraints(query_ext, record, data.value, STATE_SET_REMOVE);
1943 /* Process update query in parent */
1944 path = this._get_query_path(query_ext);
1945 arr = update_query.params[path];
1947 var key = manifold.metadata.get_key(query.object);
1948 arr = $.grep(arr, function(x) { return (!(manifold._record_equals(x, data.value, key))); });
1949 if (update_query.params[path] === undefined)
1950 update_query.params[path] = Array();
1951 update_query.params[path] = arr;
1955 /* Inform the parent query: important for update */
1962 main_query = query_ext.main_query_ext.query;
1963 manifold.raise_record_event(main_query.query_uuid, event_type, new_data);
1964 /* Propagate the event to other plugins subscribed to the query */
1965 manifold.query_store.recount(query_uuid);
1967 manifold.raise_record_event(query_uuid, event_type, new_data);
1972 // 3. Inform others about the change
1973 // a) the main query...
1974 manifold.raise_record_event(query_uuid, event_type, data);
1976 // b) subqueries eventually (dot in the key)
1979 var cur_query = query;
1980 if (cur_query.analyzed_query)
1981 cur_query = cur_query.analyzed_query;
1984 var path_array = data.key.split('.');
1985 var value_key = data.key.split('.');
1986 $.each(path_array, function(i, method) {
1987 cur_query = cur_query.subqueries[method];
1988 value_key.shift(); // XXX check that method is indeed shifted
1990 data.key = value_key;
1992 manifold.raise_record_event(cur_query.query_uuid, event_type, data);
1998 query_ext.main_query_ext.update_query_ext.query.fields = [];
1999 manifold.run_query(query_ext.main_query_ext.update_query_ext.query);
2002 /* QUERY STATE CHANGED */
2007 console.log("FILTER ADDED", data);
2008 /* Update internal record state */
2009 manifold.query_store.add_filter(query_uuid, data);
2011 /* Propagate the message to plugins */
2012 manifold.raise_query_event(query_uuid, event_type, data);
2016 case FILTER_REMOVED:
2017 console.log("FILTER REMOVED", data);
2018 /* Update internal record state */
2019 manifold.query_store.remove_filter(query_uuid, data);
2021 /* Propagate the message to plugins */
2022 manifold.raise_query_event(query_uuid, event_type, data);
2027 main_query = query_ext.main_query_ext.query;
2028 main_update_query = query_ext.main_query_ext.update_query;
2031 // Here we need the full path through all subqueries
2033 // XXX We might need the query name in the QueryExt structure
2034 main_query.select(data);
2036 // XXX When is an update query associated ?
2037 // XXX main_update_query.select(value);
2039 manifold.raise_query_event(query_uuid, event_type, data);
2043 query = query_ext.query;
2044 main_query = query_ext.main_query_ext.query;
2045 main_update_query = query_ext.main_query_ext.update_query;
2046 query.unselect(data);
2047 main_query.unselect(data);
2049 // We need to inform about changes in these queries to the respective plugins
2050 // Note: query & main_query have the same UUID
2051 manifold.raise_query_event(query_uuid, event_type, data);
2054 // We need to inform about changes in these queries to the respective plugins
2055 // Note: query, main_query & update_query have the same UUID
2057 // http://trac.myslice.info/ticket/32
2058 // Avoid multiple calls to the same event
2059 //manifold.raise_query_event(query_uuid, event_type, value);
2061 // We are targeting the same object with get and update
2062 // The notion of query is bad, we should have a notion of destination, and issue queries on the destination
2063 // NOTE: Editing a subquery == editing a local view on the destination
2065 // XXX We might need to run the new query again and manage the plugins in the meantime with spinners...
2066 // For the time being, we will collect all columns during the first query
2069 /* Publish/subscribe channels for internal use */
2070 get_channel: function(type, query_uuid) {
2071 if ((type !== 'query') && (type != 'record'))
2073 return '/' + type + '/' + query_uuid;
2076 }; // manifold object
2077 /* ------------------------------------------------------------ */
2081 // OLD PLUGIN API: extend jQuery/$ with pubsub capabilities
2082 // https://gist.github.com/661855
2084 $.subscribe = function( channel, selector, data, fn) {
2085 /* borrowed from jQuery */
2086 if ( data == null && fn == null ) {
2089 data = selector = undefined;
2090 } else if ( fn == null ) {
2091 if ( typeof selector === "string" ) {
2092 // ( channel, selector, fn )
2096 // ( channel, data, fn )
2099 selector = undefined;
2104 /* We use an indirection function that will clone the object passed in
2105 * parameter to the subscribe callback
2107 * FIXME currently we only clone query objects which are the only ones
2108 * supported and editable, we might have the same issue with results but
2109 * the page load time will be severely affected...
2111 o.on.apply(o, [channel, selector, data, function() {
2112 for(i = 1; i < arguments.length; i++) {
2113 if ( arguments[i].constructor.name == 'ManifoldQuery' )
2114 arguments[i] = arguments[i].clone();
2116 fn.apply(o, arguments);
2120 $.unsubscribe = function() {
2121 o.off.apply(o, arguments);
2124 $.publish = function() {
2125 o.trigger.apply(o, arguments);
2130 /* ------------------------------------------------------------ */
2132 //http://stackoverflow.com/questions/5100539/django-csrf-check-failing-with-an-ajax-post-request
2133 //make sure to expose csrf in our outcoming ajax/post requests
2135 beforeSend: function(xhr, settings) {
2136 function getCookie(name) {
2137 var cookieValue = null;
2138 if (document.cookie && document.cookie != '') {
2139 var cookies = document.cookie.split(';');
2140 for (var i = 0; i < cookies.length; i++) {
2141 var cookie = jQuery.trim(cookies[i]);
2142 // Does this cookie string begin with the name we want?
2143 if (cookie.substring(0, name.length + 1) == (name + '=')) {
2144 cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
2151 if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
2152 // Only send the token to relative URLs i.e. locally.
2153 xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));