]> rtime.felk.cvut.cz Git - frescor/frsh.git/blob - fres/cbroker/fcb.c
frm_gui: Do not crash when resource manager disappears
[frescor/frsh.git] / fres / cbroker / fcb.c
1 /**************************************************************************/
2 /* ---------------------------------------------------------------------- */
3 /* Copyright (C) 2006 - 2008 FRESCOR consortium partners:                 */
4 /*                                                                        */
5 /*   Universidad de Cantabria,              SPAIN                         */
6 /*   University of York,                    UK                            */
7 /*   Scuola Superiore Sant'Anna,            ITALY                         */
8 /*   Kaiserslautern University,             GERMANY                       */
9 /*   Univ. Politécnica  Valencia,           SPAIN                        */
10 /*   Czech Technical University in Prague,  CZECH REPUBLIC                */
11 /*   ENEA                                   SWEDEN                        */
12 /*   Thales Communication S.A.              FRANCE                        */
13 /*   Visual Tools S.A.                      SPAIN                         */
14 /*   Rapita Systems Ltd                     UK                            */
15 /*   Evidence                               ITALY                         */
16 /*                                                                        */
17 /*   See http://www.frescor.org for a link to partners' websites          */
18 /*                                                                        */
19 /*          FRESCOR project (FP6/2005/IST/5-034026) is funded             */
20 /*       in part by the European Union Sixth Framework Programme          */
21 /*       The European Union is not liable of any use that may be          */
22 /*       made of this code.                                               */
23 /*                                                                        */
24 /*                                                                        */
25 /*  This file is part of FRSH (FRescor ScHeduler)                         */
26 /*                                                                        */
27 /* FRSH is free software; you can redistribute it and/or modify it        */
28 /* under terms of the GNU General Public License as published by the      */
29 /* Free Software Foundation; either version 2, or (at your option) any    */
30 /* later version.  FRSH is distributed in the hope that it will be        */
31 /* useful, but WITHOUT ANY WARRANTY; without even the implied warranty    */
32 /* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU    */
33 /* General Public License for more details. You should have received a    */
34 /* copy of the GNU General Public License along with FRSH; see file       */
35 /* COPYING. If not, write to the Free Software Foundation, 675 Mass Ave,  */
36 /* Cambridge, MA 02139, USA.                                              */
37 /*                                                                        */
38 /* As a special exception, including FRSH header files in a file,         */
39 /* instantiating FRSH generics or templates, or linking other files       */
40 /* with FRSH objects to produce an executable application, does not       */
41 /* by itself cause the resulting executable application to be covered     */
42 /* by the GNU General Public License. This exception does not             */
43 /* however invalidate any other reasons why the executable file might be  */
44 /* covered by the GNU Public License.                                     */
45 /**************************************************************************/
46
47 /**
48  * @file   fcb.c
49  * @author Michal Sojka <sojkam1@fel.cvut.cz>
50  * @date   Mon Oct 20 18:00:18 2008
51  * 
52  * @brief  FRESCOR Contract Broker
53  * 
54  * 
55  */
56 #include <forb.h>
57 #include <fcb.h>
58 #include <error.h>
59 #include <errno.h>
60 #include <stdio.h>
61 #include <ul_gavlcust.h>
62 #include <string.h>
63 #include <ul_log.h>
64 #include <forb/server_id.h>
65 #include <fres_contract.h>
66 #include "fcb_config.h"
67 #include <fosa_clocks_and_timers.h>
68 #ifdef CONFIG_FCB_INET
69 #include <forb/proto_inet.h>
70 #endif
71
72 UL_LOG_CUST(ulogd_fcb);
73 ul_log_domain_t ulogd_fcb = {UL_LOGL_MSG, "fcb"};
74
75 fosa_abs_time_t start_time;
76
77
78 /**
79  * Resource identification 
80  */
81 struct res_key {
82         frsh_resource_type_t type;
83         frsh_resource_id_t id;
84 };
85
86 /**
87  * Registered resource
88  */
89 struct resource {
90         gavl_node_t node;
91         struct res_key key;
92         fres_resource_manager mng; /**< Object reference of the resource manager */
93         gavl_cust_root_field_t allocators; /**< Registered allocators for this resource (from multiple applications/nodes) */
94         ul_list_head_t sc_contracts; /**< Negotiated contracts with spare capacity for this resource */
95 };
96
97 /**
98  * Resource allocator registered in different nodes/applications 
99  */
100 struct res_alloc {
101         gavl_node_t node;
102         forb_server_id app;
103         fres_resource_allocator ra;
104 };
105
106 struct fcb_contract {
107         fres_contract_id_t id;
108         struct res_alloc *ra;   /**< Allocator for this contract TODO: Remove contract if allocator is destroyed */
109         gavl_node_t node_fcb;
110         ul_list_node_t node_sc;
111         ul_list_node_t node_reservation;
112         struct {
113                 int initial;
114                 int try;
115         } sc_variant;
116         fosa_abs_time_t end_of_stability_period;
117         struct fres_contract *user_contract; /* The contract sent by user. Set after sucessfull neotiation. */
118         struct fres_contract *requested_contract; /* User request for the contract. Set by prepare_reservation_requests() in the beginning of negotiation. */
119         struct fres_contract *to_be_reserved_contract;
120         struct fres_contract *schedulable_contract;
121 };
122
123 /**
124  * Contract broker data
125  */
126 struct fcb {
127         gavl_cust_root_field_t resources; /**< Registered resources */
128         gavl_cust_root_field_t contracts; /**< Contracts negotiated by this FCB */
129 };
130
131 /** List of contracts to be reserved during spare capacity rebalancing */
132 struct reservation_list {
133         ul_list_head_t fcb_contracts;
134         unsigned length;
135 };
136
137 struct fcb_contract *fcb_contract_new(fres_contract_id_t *id)
138 {
139         struct fcb_contract *fcb_contract;
140         
141         fcb_contract = malloc(sizeof(*fcb_contract));
142         if (!fcb_contract) {
143                 return NULL;
144         }
145         memset(fcb_contract, 0, sizeof(*fcb_contract));
146         fcb_contract->id = *id;
147
148         return fcb_contract;
149 }
150
151 void fcb_contract_destroy(struct fcb_contract *fcb_contract)
152 {
153         if (fcb_contract->user_contract) {
154                 fres_contract_destroy(fcb_contract->user_contract);
155         }
156         if (fcb_contract->to_be_reserved_contract) {
157                 fres_contract_destroy(fcb_contract->to_be_reserved_contract);
158         }
159         if (fcb_contract->requested_contract) {
160                 fres_contract_destroy(fcb_contract->requested_contract);
161         }
162         if (fcb_contract->schedulable_contract) {
163                 fres_contract_destroy(fcb_contract->requested_contract);
164         }
165         free(fcb_contract);
166 }
167
168 static inline int res_key_cmp(const struct res_key *a,
169                               const struct res_key *b)
170 {
171         if (a->type < b->type) {
172                 return -1;
173         } else if (a->type > b->type) {
174                 return +1;
175         } else if (a->id < b->id) {
176                 return -1;
177         } else if (a->id > b->id) {
178                 return +1;
179         } else {
180                 return 0;
181         }
182 }
183
184 /* Container for registered resources */
185 GAVL_CUST_NODE_INT_DEC(fcb_resource   /* cust_prefix */,                \
186                        struct fcb     /* cust_root_t */,                \
187                        struct resource/* cust_item_t */,                \
188                        struct res_key /* cust_key_t */,                 \
189                        resources      /* cust_root_node */,             \
190                        node           /* cust_item_node */,             \
191                        key            /* cust_item_key */,              \
192                        res_key_cmp    /* cust_cmp_fnc */);
193
194 GAVL_CUST_NODE_INT_IMP(fcb_resource   /* cust_prefix */,                \
195                        struct fcb     /* cust_root_t */,                \
196                        struct resource/* cust_item_t */,                \
197                        struct res_key /* cust_key_t */,                 \
198                        resources      /* cust_root_node */,             \
199                        node           /* cust_item_node */,             \
200                        key            /* cust_item_key */,              \
201                        res_key_cmp    /* cust_cmp_fnc */);
202
203 /* Container for allocators registered for a given resource */
204 GAVL_CUST_NODE_INT_DEC(fcb_alloc        /* cust_prefix */,              \
205                        struct resource  /* cust_root_t */,              \
206                        struct res_alloc /* cust_item_t */,              \
207                        forb_server_id   /* cust_key_t */,               \
208                        allocators       /* cust_root_node */,           \
209                        node             /* cust_item_node */,           \
210                        app              /* cust_item_key */,            \
211                        fres_contract_id_cmp /* cust_cmp_fnc */);
212
213 GAVL_CUST_NODE_INT_IMP(fcb_alloc        /* cust_prefix */,              \
214                        struct resource   /* cust_root_t */,             \
215                        struct res_alloc /* cust_item_t */,              \
216                        forb_server_id   /* cust_key_t */,               \
217                        allocators       /* cust_root_node */,           \
218                        node             /* cust_item_node */,           \
219                        app              /* cust_item_key */,            \
220                        forb_server_id_cmp /* cust_cmp_fnc */);
221
222 /* Container for contracts with spare capacity negotiated for a given resource */
223 UL_LIST_CUST_DEC(sc_contracts        /* cust_prefix */,                 \
224                  struct resource  /* cust_head_t */,                    \
225                  struct fcb_contract /* cust_item_t */,                 \
226                  sc_contracts   /* cust_head_field */,                  \
227                  node_sc        /* cust_node_field */);
228
229 UL_LIST_CUST_DEC(reservation_list        /* cust_prefix */,             \
230                  struct reservation_list  /* cust_head_t */,            \
231                  struct fcb_contract /* cust_item_t */,                 \
232                  fcb_contracts  /* cust_head_field */,                  \
233                  node_reservation /* cust_node_field */);
234
235 /* Container for negotiated contracts */
236 GAVL_CUST_NODE_INT_DEC(fcb_contract         /* cust_prefix */,          \
237                        struct fcb           /* cust_root_t */,          \
238                        struct fcb_contract  /* cust_item_t */,          \
239                        fres_contract_id_t   /* cust_key_t */,           \
240                        contracts            /* cust_root_node */,       \
241                        node_fcb             /* cust_item_node */,       \
242                        id                   /* cust_item_key */,        \
243                        fres_contract_id_cmp /* cust_cmp_fnc */);
244
245 #if 1
246 GAVL_CUST_NODE_INT_IMP(fcb_contract         /* cust_prefix */,          \
247                        struct fcb           /* cust_root_t */,          \
248                        struct fcb_contract  /* cust_item_t */,          \
249                        fres_contract_id_t   /* cust_key_t */,           \
250                        contracts            /* cust_root_node */,       \
251                        node_fcb             /* cust_item_node */,       \
252                        id                   /* cust_item_key */,        \
253                        fres_contract_id_cmp /* cust_cmp_fnc */);
254 #else
255 #include "fcb_contract_gavl.inc"
256 #endif
257
258
259 #define o2fcb(o) (struct fcb*)forb_instance_data(o)
260
261 struct res_key*
262 get_res_key(const struct fres_contract *contract, struct res_key *key)
263 {
264         fres_block_resource *block_res;
265         
266         block_res = fres_contract_get_resource(contract);
267         if (!block_res) {
268                 ul_logerr("No resource specified\n");
269                 return NULL;
270         } else {
271                 key->type = block_res->resource_type;
272                 key->id = block_res->resource_id;
273         }
274         return key;
275 }
276
277 /** 
278  * Fills in an array of fcb_contracts according to requests submited
279  * to negotiate_contracts(). For every contract in @a contracts, there
280  * is one fcb_contract in @a fcb_contracts array.
281  * 
282  * @param fcb
283  * @param fcb_contracts Where to store pointers to fcb_contracts
284  * @param resource Resource for which negotiation is being done.
285  * @param app Application which requests negotiation
286  * @param contracts Contracts submited to negotiate_contracts() 
287  * @param num Number of contracts in contracts (which is the same as the number in fcb_contracts).
288  * 
289  * @return Zero on success, non-zero error code on error.
290  */
291 static int
292 prepare_fcb_contracts(struct fcb *fcb, struct fcb_contract *fcb_contracts[],
293                       struct resource **resource,
294                       forb_server_id *app,
295                       struct fres_contract *contracts[], int num)
296 {
297         unsigned i;
298         struct fcb_contract *fc;
299         struct res_alloc *ra;
300         struct res_key key, key2 = {-1,-1};
301
302         for (i=0; i<num; i++) {
303                 struct fres_contract *c = contracts[i];
304
305                 if (fres_contract_id_is_empty(&c->id)) {
306                         /* Normal negotiation request */
307                         forb_uuid_generate((forb_uuid_t *)&c->id);
308                         fc = fcb_contract_new(&c->id);
309                         if (!fc)
310                                 return errno;
311                         fcb_contracts[i] = fc;
312                         if (!get_res_key(c, &key)) {
313                                 return FRSH_ERR_RESOURCE_ID_INVALID;
314                         }
315                 } else {
316                         fc = fcb_contract_find(fcb, &c->id);
317                         if (!fc) {
318                                 char str[60];
319                                 fres_contract_id_to_string(str, &c->id, sizeof(str));
320                                 ul_logerr("Attempt to change unknown contract %s\n", str);
321                                 return FRES_ERR_NOTHING_TO_RENEGOTIATE;
322                         } else {
323                                 fcb_contracts[i] = fc;
324                                 if (fres_contract_get_num_blocks(c) == 0) {
325                                         /* Cancelation */
326                                         get_res_key(fc->user_contract, &key);
327                                 } else {
328                                         /* Renegotiation */
329                                         if (!get_res_key(c, &key)) {
330                                                 return FRSH_ERR_RESOURCE_ID_INVALID;
331                                         }
332                                 }
333                         }
334                 }
335                 fc->requested_contract = c;
336
337                 /* Check that all contracts are for the same resource */
338                 if (i==0) {
339                         key2 = key;
340                         *resource = fcb_resource_find(fcb, &key);
341                         if (!*resource) {
342                                 ul_logerr("No resource manager for %d.%d registered\n",
343                                           key.type, key.id);
344                                 return FRSH_ERR_RESOURCE_ID_INVALID;
345                         }
346                 }
347                 else if (key.type != key2.type ||
348                          key.id   != key2.id) {
349                         ul_logerr("Contract #%d differs in resource!\n", i);
350                         return FRSH_ERR_RESOURCE_ID_INVALID;
351                 }
352
353                 /* Find allocator for this request */
354                 ra = fcb_alloc_find(*resource, app);
355                 if (!ra) {
356                         char str[60];
357                         forb_server_id_to_string(str, app, sizeof(str));
358                         ul_logerr("No resource allocator found for %d.%d and %s\n",
359                                   (*resource)->key.type, (*resource)->key.id, str);
360                         return FRES_ERR_NO_RESOURCE_ALLOCATOR;
361                 }
362                 fc->ra = ra;
363         }       
364         return 0;
365 }
366
367 /**
368  * @param resource Resource for which to rebalance capacity and negotiate new contracts
369  * @param fcb_contract New requests to negotiate
370  * @param num The number of elements in @a fcb_contract
371  * @param[out] rl List with changed contracts to be commited
372  */
373 static void
374 prepare_reservation_list(struct resource *resource,
375                          struct fcb_contract *fcb_contract[], int num,
376                          struct reservation_list *rl)
377 {
378         int i;
379         fosa_abs_time_t now;
380         struct fcb_contract *fc;
381
382         reservation_list_init_head(rl);
383         rl->length = 0;
384         for (i=0; i<num; i++) {
385                 assert(fcb_contract[i]->requested_contract != NULL);
386                 reservation_list_insert(rl, fcb_contract[i]);
387                 rl->length++;
388         }
389         fosa_clock_get_time(CLOCK_REALTIME, &now);
390         ul_list_for_each(sc_contracts, resource, fc) {
391                 if (fosa_abs_time_smaller(fc->end_of_stability_period, now) &&
392                     fc->requested_contract == NULL) /* Do not insert contract inserted above */
393                 {
394                         reservation_list_insert(rl, fc);
395                         rl->length++;
396                 }
397         }
398 }
399
400 /** 
401  * 
402  * 
403  * @param resource Resource for which to rebalance capacity and negotiate new contracts
404  * @param rl List with changed contracts to be commited
405  * 
406  * @return Zero on success, non-zero error code on error
407  */
408 static int
409 rebalance_spare_capacity_and_reserve(struct resource *resource,
410                                      struct reservation_list *rl)
411 {
412         int ret;
413         unsigned i;
414         struct fcb_contract *fc;
415         fres_block_spare_capacity *s;
416
417         fres_contract_ptr_seq contracts;
418         forb_sequence_alloc_buf(contracts, rl->length);
419         contracts._length = rl->length;
420         i=0;
421         /* Initialize optimization */
422         ul_list_for_each(reservation_list, rl, fc) {
423                 fc->to_be_reserved_contract =
424                         fc->requested_contract ? fres_contract_duplicate(fc->requested_contract) :
425                         fc->user_contract ? fres_contract_duplicate(fc->user_contract) :
426                         NULL;
427                 assert(fc->to_be_reserved_contract != NULL);
428
429                 forb_sequence_elem(contracts, i) = fc->to_be_reserved_contract;
430                 i++;
431                 
432                 s = fres_contract_get_spare_capacity(fc->to_be_reserved_contract);
433                 if (s && s->granularity == FRSH_GR_DISCRETE) {
434                         fc->sc_variant.initial = s->variants._length - 1;
435                         fc->sc_variant.try = fc->sc_variant.initial;
436                 }
437         }
438
439         bool all_combinations_tried;
440         int criterion, best_criterion = -1;
441         struct fcb_contract *fcb_changed;
442         /* Exhaustive search. Try all combinations of spare capacity
443          * variants and find the one with best creterion. */
444         do {
445                 all_combinations_tried = true;
446                 fcb_changed = NULL;
447                 criterion = 0;
448                 /* Prepare spare capacity variant */
449                 ul_list_for_each(reservation_list, rl, fc) {
450                         s = fres_contract_get_spare_capacity(fc->to_be_reserved_contract);
451                         /* TODO: Simulate continuous granularity by discretization */
452                         if (s && s->granularity == FRSH_GR_DISCRETE) {
453                                 fres_container_copy(fc->to_be_reserved_contract->container,
454                                                     forb_sequence_elem(s->variants, fc->sc_variant.try));
455                                 criterion += fc->sc_variant.try;
456
457                                 if (fcb_changed == NULL) {
458                                         /* Chnage tried variant for the next round */
459                                         fc->sc_variant.try = fc->sc_variant.try > 0 ?
460                                                 fc->sc_variant.try - 1 :
461                                                 s->variants._length - 1;
462                                         /* Do not change other
463                                          * contracts unless we have
464                                          * tried all variants */
465                                         if (fc->sc_variant.try != fc->sc_variant.initial) {
466                                                 fcb_changed = fc;
467                                         }
468                                 }
469                                 if (fc->sc_variant.try != fc->sc_variant.initial)
470                                         all_combinations_tried = false;
471                         }
472                 }
473
474                 if (criterion > best_criterion) {
475                         CORBA_Environment ev;
476                         /* Reserve contract */
477                         ret = fres_resource_manager_reserve_contracts(resource->mng, &contracts, &ev);
478                         if (forb_exception_occurred(&ev)) {
479                                 ret = fres_forbex2err(&ev);
480                                 ul_logerr("FORB exception when reserving contracts\n");
481                                 goto err;
482                         }
483                         if (ret < 0) {
484                                 ul_logerr("Contract reservation error %d\n", ret);
485                                 ret = FRES_ERR_ADMISSION_TEST;
486                                 goto err;
487                         }
488                         if (ret == 0) { /* negotiation succeeded */
489                                 best_criterion = criterion;
490                         }
491                 }
492         } while (!all_combinations_tried);
493
494         if (best_criterion == -1) {
495                 ret = FRSH_ERR_CONTRACT_REJECTED;
496         } else {
497                 /* At least some variant succeeded */
498                 ret = 0;
499                 sc_contracts_init_head(resource);
500                 ul_list_for_each(reservation_list, rl, fc) {
501                         s = fres_contract_get_spare_capacity(fc->to_be_reserved_contract);
502                         if (s && s->granularity == FRSH_GR_DISCRETE) {
503                                 sc_contracts_insert(resource, fc);
504                         }
505                 }
506         }
507 err:
508         ul_list_for_each(reservation_list, rl, fc) {
509                 fres_contract_destroy(fc->to_be_reserved_contract);
510                 fc->to_be_reserved_contract = NULL;
511         }
512         forb_sequence_free_buf(contracts, forb_no_destructor);
513         return ret;
514 }
515
516 /**
517  * Create/change VReses according to @a schedulable_contracts.
518  *
519  * There might be more allocators for schedulable contracts, so merge
520  * adjacent vreses with the same allocator together and create/change
521  * them in one step. Also the order of schedulable contracts might be
522  * different from the initial order od ids in commit_contracts()
523  * therefore we have to search for every contract.
524  */
525 static int
526 change_vreses(struct fcb *fcb, fres_contract_ptr_seq *schedulable_contracts)
527 {
528         struct res_alloc *last_ra = NULL;
529         fres_contract_ptr_seq vreses;
530         int i, ret;
531         CORBA_Environment ev;
532         
533         forb_sequence_alloc_buf(vreses, schedulable_contracts->_length);
534         vreses._length = 0;
535         
536         for (i=0; i<schedulable_contracts->_length; i++) {
537                 struct fcb_contract *fc;
538                 struct fres_contract *sc = schedulable_contracts->_buffer[i];
539
540                 fc = fcb_contract_find(fcb, &sc->id);
541                 assert(fc != NULL);
542
543                 if (true /* TODO: if the schedulable contract is changed */) {
544                         if (last_ra != fc->ra) {
545                                 if (vreses._length) {
546                                         ret = fres_resource_allocator_change_vreses(last_ra->ra,
547                                                                                     &vreses, &ev);
548                                         if (forb_exception_occurred(&ev)) {
549                                                 ret = fres_forbex2err(&ev);
550                                                 goto err;
551                                         }
552                                         if (ret) goto err;
553                                 }
554                                 vreses._length = 0;
555                         }
556                         vreses._buffer[vreses._length] = sc;
557                         vreses._length++;
558                         fres_contract_destroy(fc->schedulable_contract);
559                         fc->schedulable_contract = fres_contract_duplicate(sc);
560                         last_ra = fc->ra;
561                 
562                 }
563         }
564         ret = fres_resource_allocator_change_vreses(last_ra->ra,
565                                                     &vreses, &ev);
566         if (forb_exception_occurred(&ev))
567                 ret = fres_forbex2err(&ev);
568 err:
569         forb_sequence_free_buf(vreses, forb_no_destructor);
570         return ret;
571 }
572
573 CORBA_long
574 negotiate_contracts(fres_contract_broker obj,
575                     const fres_contract_ptr_seq* contracts,
576                     fres_contract_id_seq** ids_out,
577                     CORBA_Environment *ev)
578 {
579         struct fcb *fcb = o2fcb(obj);
580         struct resource *resource;
581         int ret;
582         forb_server_id app;
583         fres_contract_ptr_seq *schedulable_contracts;
584         struct fcb_contract **fcb_contracts, *fc;
585         unsigned i;
586         fres_contract_id_seq commit_ids;
587
588         /* Prepare output sequence for the case we return eariler with
589          * an error */
590         forb_sequence_alloc(*ids_out, 0);
591         if (!*ids_out) {
592                 ev->major = FORB_EX_NO_MEMORY;
593                 goto err;
594         }
595         CORBA_sequence_set_release(*ids_out, CORBA_TRUE);
596         
597         forb_get_req_source(obj, &app);
598         
599         fcb_contracts = malloc(sizeof(fcb_contracts[0])*contracts->_length);
600         if (!fcb_contracts) {
601                 ret = errno;
602                 goto err;
603         }
604         memset(fcb_contracts, 0, sizeof(fcb_contracts[0])*contracts->_length);
605
606         ret = prepare_fcb_contracts(fcb, fcb_contracts, &resource,
607                                     &app, contracts->_buffer, contracts->_length);
608         if (ret)
609                 goto err_free_fcb_contracts;
610
611         struct reservation_list rl;
612         prepare_reservation_list(resource,
613                                  fcb_contracts, contracts->_length,
614                                  &rl);
615
616         /* Allocate all the needed memory before doing reservation. If
617          * there is no enough memory, it has no sense to call resource
618          * manager. */
619         forb_sequence_alloc_buf(commit_ids, rl.length);
620         if (!commit_ids._buffer) {
621                 ret = errno;
622                 goto err_free_fcb_contracts;
623         }
624
625         /* Reserve contracts */
626         ret = rebalance_spare_capacity_and_reserve(resource, &rl);
627         if (ret) {
628                 if (ret == FRSH_ERR_CONTRACT_REJECTED) {
629                         ul_logmsg("Contract(s) was/were rejected\n");
630                 } else {
631                         char msg[100];
632                         fres_strerror(ret, msg, sizeof(msg));
633                         ul_logerr("Reservation error: %s\n", msg);
634                 }
635                 goto err_free_fcb_contracts;
636         }
637
638         /* Commit contracts */
639         commit_ids._length = rl.length;
640         i=0;
641         ul_list_for_each(reservation_list, &rl, fc) {
642                 forb_sequence_elem(commit_ids, i) = fc->id;
643                 i++;
644         }
645         
646         fres_resource_manager_commit_contracts(resource->mng, &commit_ids,
647                                                &schedulable_contracts, ev);
648         if (forb_exception_occurred(ev)) {
649                 ret = fres_forbex2err(ev);
650                 goto err_cancel_reservation;
651         }
652
653         /* Add new contracts to our fcb database for later
654          * reference. Canceled contracts are removed below. */
655         for (i=0; i<contracts->_length; i++) {
656                 fc =  fcb_contracts[i];
657
658                 if (fc->user_contract) {
659                         if (fres_contract_get_num_blocks(fc->requested_contract) > 0) {
660                                 /* Renegotiation */
661                                 fres_contract_destroy(fc->user_contract);
662                                 fc->user_contract = fres_contract_duplicate(fc->requested_contract);
663                                 /* Note: requested_contract is also
664                                  * pointed by contracts parameter and
665                                  * will be freed by FORB. */
666                                 fc->requested_contract = NULL;
667                         }
668                 } else {
669                         /* Insert new contracts */
670                         fcb_contract_insert(fcb, fcb_contracts[i]);
671                         fc->user_contract = fres_contract_duplicate(fc->requested_contract);
672                         fc->requested_contract = NULL;
673                         /* See the note above. */
674                 }
675         }
676
677         ret = change_vreses(fcb, schedulable_contracts);
678         if (ret)
679                 goto err_cancel_reservation;
680         
681         forb_sequence_free(schedulable_contracts, fres_contract_ptr_destroy);
682         if (ret != 0) {
683                 ul_logerr("VRes was not created\n");
684                 goto err_cancel_contracts;
685         }
686
687
688         /* Return IDs and delete canceled contracts from out database */
689         forb_sequence_alloc_buf(**ids_out, contracts->_length);
690         if (!(*ids_out)->_buffer) {
691                 ev->major = FORB_EX_NO_MEMORY;
692                 goto err_cancel_contracts;
693         }
694         (*ids_out)->_length = contracts->_length;
695         for (i=0; i<contracts->_length; i++) {
696                 struct fcb_contract *fc =  fcb_contracts[i];
697                 forb_sequence_elem(**ids_out, i) = fc->id;
698
699                 if (fc->requested_contract &&
700                     fres_contract_get_num_blocks(fc->requested_contract) == 0) {
701                         fcb_contract_delete(fcb, fc);
702                         /* Note: requested_contract is also pointed by
703                          * contracts parameter and will be freed by FORB. */
704                         fc->requested_contract = NULL;
705                         fcb_contract_destroy(fc);
706                 }
707         }
708         return 0;
709
710 err_cancel_contracts:
711         /* TODO */
712         goto err_free_fcb_contracts;
713 err_cancel_reservation:
714         fres_resource_manager_cancel_reservations(resource->mng, &commit_ids, ev);
715 err_free_fcb_contracts:
716         for (i=0; i<contracts->_length; i++) {
717                 fc = fcb_contracts[i];
718                 if (fc && !fc->user_contract) {
719                         fcb_contracts[i]->requested_contract = NULL; /* Destroyed by FORB */
720                         fcb_contract_destroy(fcb_contracts[i]);
721                 }
722         }
723         free(fcb_contracts);
724 err:
725         return ret;
726 }
727
728 void redistribute_spare_capacity(fres_contract_broker obj,
729                                  const frsh_resource_type_t restype,
730                                  const frsh_resource_id_t resid,
731                                  CORBA_Environment *ev)
732 {
733         struct fcb *fcb = o2fcb(obj);
734         struct res_key key = {restype, resid };
735         struct resource *resource;
736         struct reservation_list rl;
737         
738         resource = fcb_resource_find(fcb, &key);
739
740         prepare_reservation_list(resource, NULL, 0, &rl);
741
742 /*      forb_sequence_alloc(ids, rl.length); */
743 /*      if (!ids || !ids->_buffer) { */
744 /*              ev->major = FORB_EX_NO_MEMORY; */
745 /*              goto err_free_fcb_contracts; */
746 /*      } */
747 /*      CORBA_sequence_set_release(ids, CORBA_TRUE); */
748 /*      *ids_out = ids;         /\* ids is freed by FORB *\/ */
749         
750         
751         rebalance_spare_capacity_and_reserve(resource, &rl);
752         /* Commit */
753 }
754
755 CORBA_long register_resource(fres_contract_broker obj,
756                             const frsh_resource_type_t restype,
757                             const frsh_resource_id_t resid,
758                             const fres_resource_desc *desc,
759                             CORBA_Environment *ev)
760 {
761         struct fcb *fcb = o2fcb(obj);
762         struct resource *res, *res2;
763
764         res = malloc(sizeof(*res));
765         if (!res) goto err;
766         memset(res, 0, sizeof(*res));
767         res->key.type = restype;
768         res->key.id = resid;
769         res2 = fcb_resource_find(fcb, &res->key);
770         if (res2) {
771                 if (forb_object_is_stale(res2->mng)) {
772                         ul_logmsg("Removing stale manager for resource %d.%d\n",
773                                   restype, resid);
774                         forb_object_release(res2->mng);
775                         fcb_resource_delete(fcb, res2);
776                         /* TODO: Delete also all allocators associated
777                          * with this stale resource manager. */
778                         free(res);
779                         res = res2;
780                 } else {
781                         ul_logerr("Resource manager %d.%d already registered\n",
782                                   restype, resid);
783                         goto free_err;
784                 }
785         }
786         res->mng = forb_object_duplicate(desc->manager);
787
788         fcb_alloc_init_root_field(res);
789         sc_contracts_init_head(res);
790         ul_logmsg("Registering manager for resource %d.%d\n",
791                   restype, resid);
792         fcb_resource_insert(fcb, res);
793         return 0;
794 free_err:
795         free(res);
796 err:
797         return -1;
798 }
799
800
801 CORBA_long register_allocator(fres_contract_broker obj,
802                               const frsh_resource_type_t restype,
803                               const frsh_resource_id_t resid,
804                               const fres_resource_allocator ra_obj,
805                               CORBA_Environment *ev)
806 {
807         struct fcb *fcb = o2fcb(obj);
808         struct resource *res;
809         struct res_alloc *ra;
810         struct res_key resource;
811         forb_server_id server_id;
812         char server_id_str[40];
813
814         forb_get_server_id(ra_obj, &server_id);
815         forb_server_id_to_string(server_id_str, &server_id, sizeof(server_id_str));
816         ul_logmsg("Registering allocator for resource %d.%d in app %s\n",
817                   restype, resid, server_id_str);
818         
819         resource.type = restype;
820         resource.id = resid;
821         res = fcb_resource_find(fcb, &resource);
822         if (!res) {
823                 ul_logerr("No manager found for %d.%d. Unable to register the allocator!\n",
824                           restype, resid);
825                 goto err;
826         }
827         ra = fcb_alloc_find(res, &server_id);
828         if (ra) {
829                 char *str = forb_object_to_string(ra_obj);
830                 ul_logerr("Allocator from already registered (%s)\n",
831                           str);
832                 forb_free(str);
833                 goto err;
834         }
835         ra = malloc(sizeof(*ra));
836         if (!ra) {
837                 goto err;
838         }
839         ra->app = server_id;
840         ra->ra = forb_object_duplicate(ra_obj);
841         fcb_alloc_insert(res, ra);
842         return 0;
843 err:
844         return FRSH_ERR_RESOURCE_ID_INVALID;
845 }
846
847 void get_resources(fres_contract_broker obj, fres_resource_seq** resources, CORBA_Environment *ev)
848 {
849         struct fcb *fcb = o2fcb(obj);
850         fres_resource_seq *seq;
851         struct resource *res;
852         int n;
853
854         seq = malloc(sizeof(*seq));
855         if (!seq) {
856                 ev->major = FORB_EX_NO_MEMORY;
857                 return;
858         }
859         memset(seq, 0, sizeof(*seq));
860
861         n=0;
862         gavl_cust_for_each(fcb_resource, fcb, res) {
863                 n++;
864         }
865
866         seq->_buffer = CORBA_sequence_fres_resource_allocbuf(n);
867         seq->_maximum = n;
868         seq->_length = n;
869
870         n = 0;
871         gavl_cust_for_each(fcb_resource, fcb, res) {
872                 seq->_buffer[n].restype = res->key.type;
873                 seq->_buffer[n].resid = res->key.id;
874                 seq->_buffer[n].desc.manager = res->mng;
875                 n++;
876         }
877
878         *resources = seq;
879 }
880
881 #ifdef CONFIG_FCB_INET
882 static int register_inet_port(forb_orb orb)
883 {
884         forb_port_t *port = forb_malloc(sizeof(*port));
885         int ret;
886         struct in_addr listen_on;
887         
888         if (!port)
889                 return -1;
890         memset(port, 0, sizeof(*port));
891         listen_on.s_addr = INADDR_ANY;
892         ret = forb_inet_port_init(&port->desc, listen_on);
893         if (ret)
894                 return ret;
895         ret = forb_register_port(orb, port);
896         return ret;
897 }
898 #endif
899
900 struct forb_fres_contract_broker_impl impl = {
901         .negotiate_contracts = negotiate_contracts,
902         .register_resource = register_resource,
903         .register_allocator = register_allocator,
904         .redistribute_spare_capacity = redistribute_spare_capacity,
905         .get_resources = get_resources,
906 };
907
908 void peer_discovery_callback(const forb_orb peer_orb, const char *orb_id)
909 {
910         forb_server_id server_id;
911         char server_id_str[sizeof(forb_server_id)*2+1];
912
913         forb_get_server_id(peer_orb, &server_id);
914         forb_server_id_to_string(server_id_str, &server_id, sizeof(server_id_str));
915 #if 0
916         ul_logmsg("peer discovered: %s (orb_id '%s')\n", server_id_str, orb_id);
917 #endif
918
919         if (orb_id == NULL)
920                 return;
921
922         if (strcmp(orb_id, "org.frescor.fcb") == 0) {
923                 fosa_abs_time_t now;
924                 fosa_rel_time_t delay;
925                 fosa_clock_get_time(CLOCK_REALTIME, &now);
926                 delay = fosa_abs_time_extract_interval(start_time, now);
927                 ul_logmsg("node joined: %s (time %ld ms)\n", server_id_str,
928                           fosa_rel_time_to_msec(delay));
929         }
930 }
931
932 void peer_dead_callback(const forb_orb peer_orb, const char *orb_id)
933 {
934 }
935
936 int main(int argc, char *argv[])
937 {
938         forb_orb orb;
939         struct fcb fcb_data;
940         fres_contract_broker fcb;
941         forb_executor_t executor;
942         int ret;
943         forb_init_attr_t attr = {
944                 .orb_id = "org.frescor.fcb",
945                 .peer_discovery_callback = peer_discovery_callback,
946                 .peer_dead_callback = peer_dead_callback,
947         };
948
949
950         fosa_clock_get_time(CLOCK_REALTIME, &start_time);
951
952         orb = forb_init(&argc, &argv, &attr);
953         if (!orb) error(1, errno, "FORB initialization failed");
954
955 #ifdef CONFIG_FCB_INET
956         ret = register_inet_port(orb);
957         if (ret) error(0, errno, "INET port registration failed");
958 #endif
959
960         fcb_resource_init_root_field(&fcb_data);
961         fcb_contract_init_root_field(&fcb_data);
962
963         fcb = forb_fres_contract_broker_new(orb, &impl, &fcb_data);
964         if (!fcb) error(1, errno, "forb_fres_contract_broker_new failed");
965
966         /* Prepare executor before we register the fcb reference,
967          * so that no reuqests are lost */
968         ret = forb_executor_init(&executor);
969         if (ret) error(1, errno, "forb_executor_init failed");
970         
971         ret = forb_executor_register_object(&executor, fcb);
972         if (ret) error(1, errno, "forb_executor_register_object failed");
973
974         ret = forb_register_reference(fcb, fres_contract_broker_reg_name);
975         if (ret) error(1, errno, "forb_register_reference() failed");
976
977         ul_logmsg("Waiting for requests\n");
978         ret = forb_executor_run(&executor);
979         if (ret) error(1, errno, "forb_executor_run failed");
980         
981         return 0;
982 }