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