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