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