]> rtime.felk.cvut.cz Git - frescor/frsh.git/blob - fres/cbroker/fcb.c
Better error reporting of FORB exceptions
[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 static void fres_contract_ptr_destroy(struct fres_contract **p)
368 {
369         fres_contract_destroy(*p);
370 }
371
372 /**
373  * @param resource Resource for which to rebalance capacity and negotiate new contracts
374  * @param fcb_contract New requests to negotiate
375  * @param num The number of elements in @a fcb_contract
376  * @param[out] rl List with changed contracts to be commited
377  */
378 static void
379 prepare_reservation_list(struct resource *resource,
380                          struct fcb_contract *fcb_contract[], int num,
381                          struct reservation_list *rl)
382 {
383         int i;
384         fosa_abs_time_t now;
385         struct fcb_contract *fc;
386
387         reservation_list_init_head(rl);
388         rl->length = 0;
389         for (i=0; i<num; i++) {
390                 assert(fcb_contract[i]->requested_contract != NULL);
391                 reservation_list_insert(rl, fcb_contract[i]);
392                 rl->length++;
393         }
394         fosa_clock_get_time(CLOCK_REALTIME, &now);
395         ul_list_for_each(sc_contracts, resource, fc) {
396                 if (fosa_abs_time_smaller(fc->end_of_stability_period, now) &&
397                     fc->requested_contract == NULL) /* Do not insert contract inserted above */
398                 {
399                         reservation_list_insert(rl, fc);
400                         rl->length++;
401                 }
402         }
403 }
404
405 /** 
406  * 
407  * 
408  * @param resource Resource for which to rebalance capacity and negotiate new contracts
409  * @param rl List with changed contracts to be commited
410  * 
411  * @return Zero on success, non-zero error code on error
412  */
413 static int
414 rebalance_spare_capacity_and_reserve(struct resource *resource,
415                                      struct reservation_list *rl)
416 {
417         int ret;
418         unsigned i;
419         struct fcb_contract *fc;
420         fres_block_spare_capacity *s;
421
422         fres_contract_ptr_seq contracts;
423         forb_sequence_alloc_buf(contracts, rl->length);
424         contracts._length = rl->length;
425         i=0;
426         /* Initialize optimization */
427         ul_list_for_each(reservation_list, rl, fc) {
428                 fc->to_be_reserved_contract =
429                         fc->requested_contract ? fres_contract_duplicate(fc->requested_contract) :
430                         fc->user_contract ? fres_contract_duplicate(fc->user_contract) :
431                         NULL;
432                 assert(fc->to_be_reserved_contract != NULL);
433
434                 forb_sequence_elem(contracts, i) = fc->to_be_reserved_contract;
435                 i++;
436                 
437                 s = fres_contract_get_spare_capacity(fc->to_be_reserved_contract);
438                 if (s && s->granularity == FRSH_GR_DISCRETE) {
439                         fc->sc_variant.initial = s->variants._length - 1;
440                         fc->sc_variant.try = fc->sc_variant.initial;
441                 }
442         }
443
444         bool all_combinations_tried;
445         int criterion, best_criterion = -1;
446         struct fcb_contract *fcb_changed;
447         /* Exhaustive search. Try all combinations of spare capacity
448          * variants and find the one with best creterion. */
449         do {
450                 all_combinations_tried = true;
451                 fcb_changed = NULL;
452                 criterion = 0;
453                 /* Prepare spare capacity variant */
454                 ul_list_for_each(reservation_list, rl, fc) {
455                         s = fres_contract_get_spare_capacity(fc->to_be_reserved_contract);
456                         /* TODO: Simulate continuous granularity by discretization */
457                         if (s && s->granularity == FRSH_GR_DISCRETE) {
458                                 fres_container_copy(fc->to_be_reserved_contract->container,
459                                                     forb_sequence_elem(s->variants, fc->sc_variant.try));
460                                 criterion += fc->sc_variant.try;
461
462                                 if (fcb_changed == NULL) {
463                                         /* Chnage tried variant for the next round */
464                                         fc->sc_variant.try = fc->sc_variant.try > 0 ?
465                                                 fc->sc_variant.try - 1 :
466                                                 s->variants._length - 1;
467                                         /* Do not change other
468                                          * contracts unless we have
469                                          * tried all variants */
470                                         if (fc->sc_variant.try != fc->sc_variant.initial) {
471                                                 fcb_changed = fc;
472                                         }
473                                 }
474                                 if (fc->sc_variant.try != fc->sc_variant.initial)
475                                         all_combinations_tried = false;
476                         }
477                 }
478
479                 if (criterion > best_criterion) {
480                         CORBA_Environment ev;
481                         /* Reserve contract */
482                         ret = fres_resource_manager_reserve_contracts(resource->mng, &contracts, &ev);
483                         if (forb_exception_occurred(&ev)) {
484                                 ret = fres_forbex2err(&ev);
485                                 ul_logerr("FORB exception when reserving contracts\n");
486                                 goto err;
487                         }
488                         if (ret < 0) {
489                                 ul_logerr("Contract reservation error %d\n", ret);
490                                 ret = FRES_ERR_ADMISSION_TEST;
491                                 goto err;
492                         }
493                         if (ret == 0) { /* negotiation succeeded */
494                                 best_criterion = criterion;
495                         }
496                 }
497         } while (!all_combinations_tried);
498
499         if (best_criterion == -1) {
500                 ret = FRSH_ERR_CONTRACT_REJECTED;
501         } else {
502                 /* At least some variant succeeded */
503                 ret = 0;
504                 sc_contracts_init_head(resource);
505                 ul_list_for_each(reservation_list, rl, fc) {
506                         s = fres_contract_get_spare_capacity(fc->to_be_reserved_contract);
507                         if (s && s->granularity == FRSH_GR_DISCRETE) {
508                                 sc_contracts_insert(resource, fc);
509                         }
510                 }
511         }
512 err:
513         ul_list_for_each(reservation_list, rl, fc) {
514                 fres_contract_destroy(fc->to_be_reserved_contract);
515                 fc->to_be_reserved_contract = NULL;
516         }
517         forb_sequence_free_buf(contracts, forb_no_destructor);
518         return ret;
519 }
520
521 /**
522  * Create/change VReses according to @a schedulable_contracts.
523  *
524  * There might be more allocators for schedulable contracts, so merge
525  * adjacent vreses with the same allocator together and create/change
526  * them in one step. Also the order of schedulable contracts might be
527  * different from the initial order od ids in commit_contracts()
528  * therefore we have to search for every contract.
529  */
530 static int
531 change_vreses(struct fcb *fcb, fres_contract_ptr_seq *schedulable_contracts)
532 {
533         struct res_alloc *last_ra = NULL;
534         fres_contract_ptr_seq vreses;
535         int i, ret;
536         CORBA_Environment ev;
537         
538         forb_sequence_alloc_buf(vreses, schedulable_contracts->_length);
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;
586         int ret;
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         forb_sequence_alloc_buf(commit_ids, rl.length);
625         if (!commit_ids._buffer) {
626                 ret = errno;
627                 goto err_free_fcb_contracts;
628         }
629
630         /* Reserve contracts */
631         ret = rebalance_spare_capacity_and_reserve(resource, &rl);
632         if (ret) {
633                 if (ret == FRSH_ERR_CONTRACT_REJECTED) {
634                         ul_logmsg("Contract(s) was/were rejected\n");
635                 } else {
636                         char msg[100];
637                         fres_strerror(ret, msg, sizeof(msg));
638                         ul_logerr("Reservation error: %s\n", msg);
639                 }
640                 goto err_free_fcb_contracts;
641         }
642
643         /* Commit contracts */
644         commit_ids._length = rl.length;
645         i=0;
646         ul_list_for_each(reservation_list, &rl, fc) {
647                 forb_sequence_elem(commit_ids, i) = fc->id;
648                 i++;
649         }
650         
651         fres_resource_manager_commit_contracts(resource->mng, &commit_ids,
652                                                &schedulable_contracts, ev);
653         if (forb_exception_occurred(ev)) {
654                 ret = fres_forbex2err(ev);
655                 goto err_cancel_reservation;
656         }
657
658         /* Add new contracts to our fcb database for later
659          * reference. Canceled contracts are removed below. */
660         for (i=0; i<contracts->_length; i++) {
661                 fc =  fcb_contracts[i];
662
663                 if (fc->user_contract) {
664                         if (fres_contract_get_num_blocks(fc->requested_contract) > 0) {
665                                 /* Renegotiation */
666                                 fres_contract_destroy(fc->user_contract);
667                                 fc->user_contract = fres_contract_duplicate(fc->requested_contract);
668                                 /* Note: requested_contract is also
669                                  * pointed by contracts parameter and
670                                  * will be freed by FORB. */
671                                 fc->requested_contract = NULL;
672                         }
673                 } else {
674                         /* Insert new contracts */
675                         fcb_contract_insert(fcb, fcb_contracts[i]);
676                         fc->user_contract = fres_contract_duplicate(fc->requested_contract);
677                         fc->requested_contract = NULL;
678                         /* See the note above. */
679                 }
680         }
681
682         ret = change_vreses(fcb, schedulable_contracts);
683         if (ret)
684                 goto err_cancel_reservation;
685         
686         forb_sequence_free(schedulable_contracts, fres_contract_ptr_destroy);
687         if (ret != 0) {
688                 ul_logerr("VRes was not created\n");
689                 goto err_cancel_contracts;
690         }
691
692
693         /* Return IDs and delete canceled contracts from out database */
694         forb_sequence_alloc_buf(**ids_out, contracts->_length);
695         if (!(*ids_out)->_buffer) {
696                 ev->major = FORB_EX_NO_MEMORY;
697                 goto err_cancel_contracts;
698         }
699         (*ids_out)->_length = contracts->_length;
700         for (i=0; i<contracts->_length; i++) {
701                 struct fcb_contract *fc =  fcb_contracts[i];
702                 forb_sequence_elem(**ids_out, i) = fc->id;
703
704                 if (fc->requested_contract &&
705                     fres_contract_get_num_blocks(fc->requested_contract) == 0) {
706                         fcb_contract_delete(fcb, fc);
707                         /* Note: requested_contract is also pointed by
708                          * contracts parameter and will be freed by FORB. */
709                         fc->requested_contract = NULL;
710                         fcb_contract_destroy(fc);
711                 }
712         }
713         return 0;
714
715 err_cancel_contracts:
716         /* TODO */
717         goto err_free_fcb_contracts;
718 err_cancel_reservation:
719         fres_resource_manager_cancel_reservations(resource->mng, &commit_ids, ev);
720 err_free_fcb_contracts:
721         for (i=0; i<contracts->_length; i++) {
722                 fc = fcb_contracts[i];
723                 if (fc && !fc->user_contract) {
724                         fcb_contracts[i]->requested_contract = NULL; /* Destroyed by FORB */
725                         fcb_contract_destroy(fcb_contracts[i]);
726                 }
727         }
728         free(fcb_contracts);
729 err:
730         return ret;
731 }
732
733 void redistribute_spare_capacity(fres_contract_broker obj,
734                                  const frsh_resource_type_t restype,
735                                  const frsh_resource_id_t resid,
736                                  CORBA_Environment *ev)
737 {
738         struct fcb *fcb = o2fcb(obj);
739         struct res_key key = {restype, resid };
740         struct resource *resource;
741         struct reservation_list rl;
742         
743         resource = fcb_resource_find(fcb, &key);
744
745         prepare_reservation_list(resource, NULL, 0, &rl);
746
747 /*      forb_sequence_alloc(ids, rl.length); */
748 /*      if (!ids || !ids->_buffer) { */
749 /*              ev->major = FORB_EX_NO_MEMORY; */
750 /*              goto err_free_fcb_contracts; */
751 /*      } */
752 /*      CORBA_sequence_set_release(ids, CORBA_TRUE); */
753 /*      *ids_out = ids;         /\* ids is freed by FORB *\/ */
754         
755         
756         rebalance_spare_capacity_and_reserve(resource, &rl);
757         /* Commit */
758 }
759
760 CORBA_long register_resource(fres_contract_broker obj,
761                             const frsh_resource_type_t restype,
762                             const frsh_resource_id_t resid,
763                             const fres_resource_desc *desc,
764                             CORBA_Environment *ev)
765 {
766         struct fcb *fcb = o2fcb(obj);
767         struct resource *res, *res2;
768
769         res = malloc(sizeof(*res));
770         if (!res) goto err;
771         memset(res, 0, sizeof(*res));
772         res->key.type = restype;
773         res->key.id = resid;
774         res2 = fcb_resource_find(fcb, &res->key);
775         if (res2) {
776                 if (forb_object_is_stale(res2->mng)) {
777                         ul_logmsg("Removing stale manager for resource %d.%d\n",
778                                   restype, resid);
779                         forb_object_release(res2->mng);
780                         fcb_resource_delete(fcb, res2);
781                         /* TODO: Delete also all allocators associated
782                          * with this stale resource manager. */
783                         free(res);
784                         res = res2;
785                 } else {
786                         ul_logerr("Resource manager %d.%d already registered\n",
787                                   restype, resid);
788                         goto free_err;
789                 }
790         }
791         res->mng = forb_object_duplicate(desc->manager);
792
793         fcb_alloc_init_root_field(res);
794         sc_contracts_init_head(res);
795         ul_logmsg("Registering manager for resource %d.%d\n",
796                   restype, resid);
797         fcb_resource_insert(fcb, res);
798         return 0;
799 free_err:
800         free(res);
801 err:
802         return -1;
803 }
804
805
806 CORBA_long register_allocator(fres_contract_broker obj,
807                               const frsh_resource_type_t restype,
808                               const frsh_resource_id_t resid,
809                               const fres_resource_allocator ra_obj,
810                               CORBA_Environment *ev)
811 {
812         struct fcb *fcb = o2fcb(obj);
813         struct resource *res;
814         struct res_alloc *ra;
815         struct res_key resource;
816         forb_server_id server_id;
817         char server_id_str[40];
818
819         forb_get_server_id(ra_obj, &server_id);
820         forb_server_id_to_string(server_id_str, &server_id, sizeof(server_id_str));
821         ul_logmsg("Registering allocator for resource %d.%d in app %s\n",
822                   restype, resid, server_id_str);
823         
824         resource.type = restype;
825         resource.id = resid;
826         res = fcb_resource_find(fcb, &resource);
827         if (!res) {
828                 ul_logerr("No manager found for %d.%d. Unable to register the allocator!\n",
829                           restype, resid);
830                 goto err;
831         }
832         ra = fcb_alloc_find(res, &server_id);
833         if (ra) {
834                 char *str = forb_object_to_string(ra_obj);
835                 ul_logerr("Allocator from already registered (%s)\n",
836                           str);
837                 forb_free(str);
838                 goto err;
839         }
840         ra = malloc(sizeof(*ra));
841         if (!ra) {
842                 goto err;
843         }
844         ra->app = server_id;
845         ra->ra = forb_object_duplicate(ra_obj);
846         fcb_alloc_insert(res, ra);
847         return 0;
848 err:
849         return FRSH_ERR_RESOURCE_ID_INVALID;
850 }
851
852 void get_resources(fres_contract_broker obj, fres_resource_seq** resources, CORBA_Environment *ev)
853 {
854         struct fcb *fcb = o2fcb(obj);
855         fres_resource_seq *seq;
856         struct resource *res;
857         int n;
858
859         seq = malloc(sizeof(*seq));
860         if (!seq) {
861                 ev->major = FORB_EX_NO_MEMORY;
862                 return;
863         }
864         memset(seq, 0, sizeof(*seq));
865
866         n=0;
867         gavl_cust_for_each(fcb_resource, fcb, res) {
868                 n++;
869         }
870
871         seq->_buffer = CORBA_sequence_fres_resource_allocbuf(n);
872         seq->_maximum = n;
873         seq->_length = n;
874
875         n = 0;
876         gavl_cust_for_each(fcb_resource, fcb, res) {
877                 seq->_buffer[n].restype = res->key.type;
878                 seq->_buffer[n].resid = res->key.id;
879                 seq->_buffer[n].desc.manager = res->mng;
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 }