]> rtime.felk.cvut.cz Git - frescor/frsh.git/blob - fres/cbroker/fcb.c
fcb: Reject direct contract manipulation in transactions
[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 #define WITH_C99                /* For ul_gsa.h iterators */
57 #include <semaphore.h>
58 #include <getopt.h>
59 #include <forb.h>
60 #include <forb/config.h>
61 #include <fcb.h>
62 #include <fcb_contact_info.h>
63 #include <error.h>
64 #include <errno.h>
65 #include <stdio.h>
66 #include <ul_gavlcust.h>
67 #include <ul_gsacust.h>
68 #include <string.h>
69 #include <ul_log.h>
70 #include <ul_logreg.h>
71 #include <forb/server_id.h>
72 #include <fres_contract.h>
73 #include "fcb_config.h"
74 #include <fosa_clocks_and_timers.h>
75 #include "contract_log.h"
76 #if CONFIG_FCB_INET && !CONFIG_FORB_PROTO_INET_DEFAULT
77 #include <forb/proto_inet.h>
78 #endif
79
80 #define COMPILE_TIME_ASSERT(cond, msg) \
81         typedef char msg[(cond) ? 1 : -1]
82
83
84 UL_LOG_CUST(ulogd_fcb);
85 ul_log_domain_t ulogd_fcb = {UL_LOGL_MSG, "main"};
86 UL_LOGREG_SINGLE_DOMAIN_INIT_FUNCTION(init_ulogd_fcb, ulogd_fcb);
87         
88 bool opt_daemon = false;
89 char *opt_pidfile = NULL;
90 fosa_abs_time_t start_time;
91
92 /** List of contracts to be newly reserved or changed by resource manager */
93 struct reservation_list {
94         ul_list_head_t fcb_contracts;
95         unsigned length;
96 };
97
98 /**
99  * Resource identification 
100  */
101 struct res_key {
102         frsh_resource_type_t type;
103         frsh_resource_id_t id;
104 };
105
106 /**
107  * Registered resource
108  */
109 struct resource {
110         gavl_node_t node;
111         struct res_key key;
112         char *name;
113         fres_resource_manager mng; /**< Object reference of the resource manager */
114         gavl_cust_root_field_t allocators; /**< Registered allocators for this resource (from multiple applications/nodes) */
115         ul_list_head_t sc_contracts; /**< Negotiated contracts with spare capacity for this resource */
116         struct reservation_list rl; /**< Temporary list of contracts to be reserved on this resource */
117 };
118
119 /**
120  * Resource allocator registered in different nodes/applications 
121  */
122 struct res_alloc {
123         gavl_node_t node;
124         forb_server_id app;
125         fres_resource_allocator ra;
126 };
127
128 struct fcb_transaction;
129
130 struct fcb_contract {
131         fres_contract_id_t id;
132         struct res_alloc *ra;   /**< Allocator for this contract TODO: Remove contract if allocator is destroyed */
133         gavl_node_t node_fcb;
134         ul_list_node_t node_sc;
135         ul_list_node_t node_reservation;
136         struct fcb_transaction *transaction;
137         struct {
138                 int initial;
139                 int try;
140         } sc_variant;
141         fosa_abs_time_t end_of_stability_period;
142         struct fres_contract *user_contract; /* The contract sent by user. Set after sucessfull neotiation. */
143         struct fres_contract *requested_contract; /* User request for the contract. Set by prepare_reservation_requests() in the beginning of negotiation. */
144         struct fres_contract *to_be_reserved_contract;
145         struct fres_contract *schedulable_contract;
146 };
147
148 struct fcb_transaction {
149         char *name;
150         gavl_node_t node;
151         gsa_array_field_t contracts;
152 };
153
154 /**
155  * Contract broker data
156  */
157 struct fcb {
158         fres_contract_id_t contract_counter;
159         gavl_cust_root_field_t resources; /**< Registered resources */
160         gavl_cust_root_field_t contracts; /**< Contracts negotiated by this FCB */
161         gavl_cust_root_field_t transactions; /**< Transactions negotiated by this FCB */
162 };
163
164 struct fcb_contract *fcb_contract_new(fres_contract_id_t *id)
165 {
166         struct fcb_contract *fcb_contract;
167         
168         fcb_contract = malloc(sizeof(*fcb_contract));
169         if (!fcb_contract) {
170                 return NULL;
171         }
172         memset(fcb_contract, 0, sizeof(*fcb_contract));
173         fcb_contract->id = *id;
174
175         return fcb_contract;
176 }
177
178 void fcb_contract_destroy(struct fcb_contract *fcb_contract)
179 {
180         if (fcb_contract->user_contract) {
181                 fres_contract_destroy(fcb_contract->user_contract);
182         }
183         if (fcb_contract->to_be_reserved_contract) {
184                 fres_contract_destroy(fcb_contract->to_be_reserved_contract);
185         }
186         if (fcb_contract->requested_contract) {
187                 fres_contract_destroy(fcb_contract->requested_contract);
188         }
189         if (fcb_contract->schedulable_contract) {
190                 fres_contract_destroy(fcb_contract->requested_contract);
191         }
192         free(fcb_contract);
193 }
194
195 static inline int
196 unsorted(const void *a, const void *b)
197 { abort(); }
198
199 /* Unordered dynamic array of contracts in transaction */
200 GSA_CUST_DEC(tran_contract      /* cust_prefix */,
201              struct fcb_transaction /* cust_array_t */,
202              struct fcb_contract/* cust_item_t */,
203              fres_contract_id_t /* cust_key_t */,
204              contracts          /* cust_array_field */,
205              id                 /* cust_item_key */,
206              unsorted           /* cust_cmp_fnc */);
207
208 GSA_CUST_IMP(tran_contract      /* cust_prefix */,
209              struct fcb_transaction /* cust_array_t */,
210              struct fcb_contract/* cust_item_t */,
211              fres_contract_id_t /* cust_key_t */,
212              contracts          /* cust_array_field */,
213              id                 /* cust_item_key */,
214              unsorted           /* cust_cmp_fnc */,
215              true               /* cust_ins_fl */);
216
217 struct fcb_transaction *fcb_transaction_new(char *name)
218 {
219         struct fcb_transaction *fcb_transaction;
220         
221         fcb_transaction = malloc(sizeof(*fcb_transaction));
222         if (!fcb_transaction) {
223                 return NULL;
224         }
225         memset(fcb_transaction, 0, sizeof(*fcb_transaction));
226         fcb_transaction->name = strdup(name);
227
228         tran_contract_init_array_field(fcb_transaction);
229
230         return fcb_transaction;
231 }
232
233 void fcb_transaction_destroy(struct fcb_transaction *fcb_transaction)
234 {
235         free(fcb_transaction->name);
236         free(fcb_transaction);
237 }
238
239 static inline int res_key_cmp(const struct res_key *a,
240                               const struct res_key *b)
241 {
242         if (a->type < b->type) {
243                 return -1;
244         } else if (a->type > b->type) {
245                 return +1;
246         } else if (a->id < b->id) {
247                 return -1;
248         } else if (a->id > b->id) {
249                 return +1;
250         } else {
251                 return 0;
252         }
253 }
254
255 /* Container for registered resources */
256 GAVL_CUST_NODE_INT_DEC(fcb_resource   /* cust_prefix */,                \
257                        struct fcb     /* cust_root_t */,                \
258                        struct resource/* cust_item_t */,                \
259                        struct res_key /* cust_key_t */,                 \
260                        resources      /* cust_root_node */,             \
261                        node           /* cust_item_node */,             \
262                        key            /* cust_item_key */,              \
263                        res_key_cmp    /* cust_cmp_fnc */);
264
265 GAVL_CUST_NODE_INT_IMP(fcb_resource   /* cust_prefix */,                \
266                        struct fcb     /* cust_root_t */,                \
267                        struct resource/* cust_item_t */,                \
268                        struct res_key /* cust_key_t */,                 \
269                        resources      /* cust_root_node */,             \
270                        node           /* cust_item_node */,             \
271                        key            /* cust_item_key */,              \
272                        res_key_cmp    /* cust_cmp_fnc */);
273
274 /* Container for allocators registered for a given resource */
275 GAVL_CUST_NODE_INT_DEC(fcb_alloc        /* cust_prefix */,              \
276                        struct resource  /* cust_root_t */,              \
277                        struct res_alloc /* cust_item_t */,              \
278                        forb_server_id   /* cust_key_t */,               \
279                        allocators       /* cust_root_node */,           \
280                        node             /* cust_item_node */,           \
281                        app              /* cust_item_key */,            \
282                        fres_contract_id_cmp /* cust_cmp_fnc */);
283
284 GAVL_CUST_NODE_INT_IMP(fcb_alloc        /* cust_prefix */,              \
285                        struct resource   /* cust_root_t */,             \
286                        struct res_alloc /* cust_item_t */,              \
287                        forb_server_id   /* cust_key_t */,               \
288                        allocators       /* cust_root_node */,           \
289                        node             /* cust_item_node */,           \
290                        app              /* cust_item_key */,            \
291                        forb_server_id_cmp /* cust_cmp_fnc */);
292
293 /* Container for contracts with spare capacity negotiated for a given resource */
294 UL_LIST_CUST_DEC(sc_contracts        /* cust_prefix */,                 \
295                  struct resource  /* cust_head_t */,                    \
296                  struct fcb_contract /* cust_item_t */,                 \
297                  sc_contracts   /* cust_head_field */,                  \
298                  node_sc        /* cust_node_field */);
299
300 UL_LIST_CUST_DEC(reservation_list        /* cust_prefix */,             \
301                  struct reservation_list  /* cust_head_t */,            \
302                  struct fcb_contract /* cust_item_t */,                 \
303                  fcb_contracts  /* cust_head_field */,                  \
304                  node_reservation /* cust_node_field */);
305
306 /* Container for negotiated contracts */
307 GAVL_CUST_NODE_INT_DEC(fcb_contract         /* cust_prefix */,          \
308                        struct fcb           /* cust_root_t */,          \
309                        struct fcb_contract  /* cust_item_t */,          \
310                        fres_contract_id_t   /* cust_key_t */,           \
311                        contracts            /* cust_root_node */,       \
312                        node_fcb             /* cust_item_node */,       \
313                        id                   /* cust_item_key */,        \
314                        fres_contract_id_cmp /* cust_cmp_fnc */);
315
316 #if 1
317 GAVL_CUST_NODE_INT_IMP(fcb_contract         /* cust_prefix */,          \
318                        struct fcb           /* cust_root_t */,          \
319                        struct fcb_contract  /* cust_item_t */,          \
320                        fres_contract_id_t   /* cust_key_t */,           \
321                        contracts            /* cust_root_node */,       \
322                        node_fcb             /* cust_item_node */,       \
323                        id                   /* cust_item_key */,        \
324                        fres_contract_id_cmp /* cust_cmp_fnc */);
325 #else
326 #include "fcb_contract_gavl.inc"
327 #endif
328
329 static inline int
330 fcb_transaction_cmp(char * const *a, char * const *b)
331 { return strcmp(*a, *b); }
332
333 GAVL_CUST_NODE_INT_DEC(fcb_transaction      /* cust_prefix */,          \
334                        struct fcb           /* cust_root_t */,          \
335                        struct fcb_transaction /* cust_item_t */,        \
336                        char*                /* cust_key_t */,           \
337                        transactions         /* cust_root_node */,       \
338                        node                 /* cust_item_node */,       \
339                        name                 /* cust_item_key */,        \
340                        fcb_transaction_cmp /* cust_cmp_fnc */);
341
342 GAVL_CUST_NODE_INT_IMP(fcb_transaction      /* cust_prefix */,          \
343                        struct fcb           /* cust_root_t */,          \
344                        struct fcb_transaction /* cust_item_t */,        \
345                        char*                /* cust_key_t */,           \
346                        transactions         /* cust_root_node */,       \
347                        node                 /* cust_item_node */,       \
348                        name                 /* cust_item_key */,        \
349                        fcb_transaction_cmp /* cust_cmp_fnc */);
350
351 struct res_array {
352         gsa_array_field_t array;
353 };
354
355 GSA_CUST_DEC(res_array          /* cust_prefix */,
356              struct res_array   /* cust_array_t */,
357              struct resource    /* cust_item_t */,
358              struct res_key     /* cust_key_t */,
359              array              /* cust_array_field */,
360              key                /* cust_item_key */,
361              res_key_cmp        /* cust_cmp_fnc */);
362
363 GSA_CUST_IMP(res_array          /* cust_prefix */,
364              struct res_array   /* cust_array_t */,
365              struct resource    /* cust_item_t */,
366              struct res_key     /* cust_key_t */,
367              array              /* cust_array_field */,
368              key                /* cust_item_key */,
369              res_key_cmp        /* cust_cmp_fnc */,
370              true               /* cust_ins_fl */);
371
372
373
374 #define o2fcb(o) (struct fcb*)forb_instance_data(o)
375
376 static struct res_key*
377 get_res_key(const struct fres_contract *contract, struct res_key *key)
378 {
379         fres_block_resource *block_res;
380         
381         block_res = fres_contract_get_resource(contract);
382         if (!block_res) {
383                 ul_logerr("No resource specified\n");
384                 return NULL;
385         } else {
386                 key->type = block_res->resource_type;
387                 key->id = block_res->resource_id;
388         }
389         return key;
390 }
391
392 static struct res_key*
393 get_fc_res_key(const struct fcb_contract *fc, struct res_key *key)
394 {
395         if (fc->user_contract)
396                 get_res_key(fc->user_contract, key);
397         else
398                 get_res_key(fc->requested_contract, key);
399         return key;
400 }
401
402 /** 
403  * Fills in an array of fcb_contracts according to requests submited
404  * by an application through negotiate_contracts() or
405  * negotiate_transaction(). For every contract in @a contracts, there
406  * is allocated one fcb_contract in @a fcb_contracts array.
407  * 
408  * @param fcb
409  * @param fcb_contracts Where to store pointers to fcb_contracts
410  * @param contracts Contracts submited for negotiation 
411  * @param num Number of contracts in contracts (which is the same as the number in fcb_contracts).
412  * 
413  * @return Zero on success, non-zero error code on error.
414  */
415 static int
416 prepare_fcb_contracts(struct fcb *fcb, struct fcb_contract *fcb_contracts[],
417                       struct fres_contract *contracts[], int num)
418 {
419         unsigned i;
420         struct fcb_contract *fc;
421
422         for (i=0; i<num; i++) {
423                 struct fres_contract *c = contracts[i];
424
425                 if (fres_contract_id_is_empty(&c->id)) {
426                         /* Normal negotiation request */
427                         COMPILE_TIME_ASSERT(sizeof(c->id) == sizeof(fcb->contract_counter),
428                                             wrong_size_of_contract_id);
429                         c->id = ++fcb->contract_counter;
430                         fc = fcb_contract_new(&c->id);
431                         if (!fc)
432                                 return errno;
433                         fcb_contracts[i] = fc;
434                         log_contract("Negotiation request", i, c);
435                 } else {
436                         fc = fcb_contract_find(fcb, &c->id);
437                         if (!fc) {
438                                 char str[60];
439                                 fres_contract_id_to_string(str, &c->id, sizeof(str));
440                                 ul_logerr("Attempt to change unknown contract %s\n", str);
441                                 return FRES_ERR_NOTHING_TO_RENEGOTIATE;
442                         } else {
443                                 fcb_contracts[i] = fc;
444                                 if (fres_contract_get_num_blocks(c) == 0) {
445                                         /* Cancelation */
446                                         log_contract("Cancelation request", i, fc->user_contract);
447                                 } else {
448                                         /* Renegotiation */
449                                         log_contract("Renegotiation request", i, fc->user_contract);
450                                 }
451                         }
452                 }
453                 fc->requested_contract = c;
454         }
455         return 0;
456 }
457
458 /**
459  * Ensure that all contracts belong to the same resource and find
460  * resource allocators for the contracts.
461  *
462  * @param fcb 
463  * @param fcb_contracts Array of fcb_contracts prepared by prepare_fcb_contracts()
464  * @param num Number of contracts in @a fcb_contracts
465  * @param resource Resource for which negotiation is being done.
466  * @param app Application which requests negotiation
467  */
468 static int
469 check_and_setup_resource(struct fcb *fcb, struct fcb_contract *fcb_contracts[],
470                          struct resource **resource,
471                          forb_server_id *app,
472                          int num)
473 {
474         unsigned i;
475         struct res_alloc *ra;
476         struct res_key key, key2 = {-1,-1};
477
478         for (i=0; i<num; i++) {
479                 struct fcb_contract *fc = fcb_contracts[i];
480
481                 if (!get_fc_res_key(fc, &key))
482                         return FRSH_ERR_RESOURCE_ID_INVALID;
483
484                 /* Check that all contracts are for the same resource */
485                 if (i==0) {
486                         key2 = key;
487                         *resource = fcb_resource_find(fcb, &key);
488                         if (!*resource) {
489                                 ul_logerr("No resource manager for %d.%d registered\n",
490                                           key.type, key.id);
491                                 return FRES_ERR_NO_RESOURCE_MANAGER;
492                         }
493                         /* Find allocator for this request */
494                         ra = fcb_alloc_find(*resource, app);
495                         if (!ra) {
496                                 char str[60];
497                                 forb_server_id_to_string(str, app, sizeof(str));
498                                 ul_logerr("No resource allocator found for %d.%d and %s\n",
499                                           (*resource)->key.type, (*resource)->key.id, str);
500                                 return FRES_ERR_NO_RESOURCE_ALLOCATOR;
501                         }
502                 }
503                 else if (key.type != key2.type ||
504                          key.id   != key2.id) {
505                         ul_logerr("Contract #%d differs in resource!\n", i);
506                         return FRSH_ERR_RESOURCE_ID_INVALID;
507                 }
508                 fc->ra = ra;
509         }       
510         return 0;
511 }
512
513 /**
514  * Prepares a list of contracts to pass to resource manager for (re)reserving.
515  *
516  * @todo Needs to be changed for compatibility with transactions.
517  * 
518  * @param resource Resource for which to rebalance capacity and negotiate new contracts
519  * @param fcb_contract New requests to negotiate
520  * @param num The number of elements in @a fcb_contract
521  * @param[out] rl List with changed contracts to be commited
522  */
523 static void
524 prepare_reservation_list(struct resource *resource,
525                          struct fcb_contract *fcb_contract[], int num)
526 {
527         int i;
528         fosa_abs_time_t now;
529         struct fcb_contract *fc;
530
531         reservation_list_init_head(&resource->rl);
532         resource->rl.length = 0;
533         for (i=0; i<num; i++) {
534                 assert(fcb_contract[i]->requested_contract != NULL);
535                 reservation_list_insert(&resource->rl, fcb_contract[i]);
536                 resource->rl.length++;
537         }
538         fosa_clock_get_time(CLOCK_REALTIME, &now);
539         ul_list_for_each(sc_contracts, resource, fc) {
540                 if (fosa_abs_time_smaller(fc->end_of_stability_period, now) &&
541                     fc->requested_contract == NULL) /* Do not insert contract inserted above */
542                 {
543                         reservation_list_insert(&resource->rl, fc);
544                         resource->rl.length++;
545                 }
546         }
547 }
548
549 static int
550 reserve_resource(struct resource *resource)
551 {
552         int ret, i;
553         fres_contract_ptr_seq contracts;
554         struct fres_contract *c;
555         struct fcb_contract *fc;
556         CORBA_Environment ev;
557         
558         if (!forb_sequence_alloc_buf(&contracts, resource->rl.length)) {
559                 ret = errno;
560                 goto err;
561         }
562         forb_sequence_length(&contracts) = resource->rl.length;
563
564         i=0;
565         /* Prepare FORB sequence  */
566         ul_list_for_each(reservation_list, &resource->rl, fc) {
567                 c = NULL;
568                 if (fc->to_be_reserved_contract)
569                         /* Contract without spare capacity */
570                         c = fc->to_be_reserved_contract;
571                 else if (fc->requested_contract)
572                         c = fc->requested_contract;
573                 assert(c);
574                 forb_sequence_elem(&contracts, i++) = c;
575         }
576         
577         /* Reserve contract */
578         ret = fres_resource_manager_reserve_contracts(resource->mng, &contracts, &ev);
579         if (forb_exception_occurred(&ev)) {
580                 ret = fres_forbex2err(&ev);
581                 ul_logerr("FORB exception when reserving contracts\n");
582                 goto err_free;
583         }
584         if (ret < 0) {
585                 ul_logerr("Contract reservation error %d\n", ret);
586                 ret = FRES_ERR_ADMISSION_TEST;
587                 goto err_free;
588         } else if (ret == 0)
589                 ret = FRSH_NO_ERROR;
590         else if (ret == 1)
591                 ret = FRSH_ERR_CONTRACT_REJECTED;
592         else
593                 assert(false);
594 err_free:
595         forb_sequence_free_buf(&contracts, forb_no_destructor);
596 err:
597         return ret;
598 }
599
600 /** 
601  * 
602  * 
603  * @param resource Resource for which to rebalance capacity and negotiate new contracts
604  * @param rl List with changed contracts to be commited
605  * 
606  * @return Zero on success, non-zero error code on error
607  */
608 static int
609 rebalance_spare_capacity_and_reserve(struct resource *resource)
610 {
611         int ret;
612         struct reservation_list *rl = &resource->rl;
613         struct fcb_contract *fc;
614         fres_block_spare_capacity *s;
615
616         /* Initialize optimization */
617         ul_list_for_each(reservation_list, rl, fc) {
618                 fc->to_be_reserved_contract =
619                         fc->requested_contract ? fres_contract_duplicate(fc->requested_contract) :
620                         fc->user_contract ? fres_contract_duplicate(fc->user_contract) :
621                         NULL;
622                 assert(fc->to_be_reserved_contract != NULL);
623
624                 s = fres_contract_get_spare_capacity(fc->to_be_reserved_contract);
625                 if (s && s->granularity == FRSH_GR_DISCRETE) {
626                         fc->sc_variant.initial = s->variants._length - 1;
627                         fc->sc_variant.try = fc->sc_variant.initial;
628                 }
629         }
630
631         bool all_combinations_tried;
632         int criterion, best_criterion = -1;
633         struct fcb_contract *fcb_changed;
634         /* Exhaustive search. Try all combinations of spare capacity
635          * variants and find the one with best creterion. */
636         do {
637                 all_combinations_tried = true;
638                 fcb_changed = NULL;
639                 criterion = 0;
640                 /* Prepare spare capacity variant */
641                 ul_list_for_each(reservation_list, rl, fc) {
642                         s = fres_contract_get_spare_capacity(fc->to_be_reserved_contract);
643                         /* TODO: Simulate continuous granularity by discretization */
644                         if (s && s->granularity == FRSH_GR_DISCRETE) {
645                                 fres_container_copy(fc->to_be_reserved_contract->container,
646                                                     forb_sequence_elem(&s->variants, fc->sc_variant.try));
647                                 criterion += fc->sc_variant.try;
648
649                                 if (fcb_changed == NULL) {
650                                         /* Chnage tried variant for the next round */
651                                         fc->sc_variant.try = fc->sc_variant.try > 0 ?
652                                                 fc->sc_variant.try - 1 :
653                                                 s->variants._length - 1;
654                                         /* Do not change other
655                                          * contracts unless we have
656                                          * tried all variants */
657                                         if (fc->sc_variant.try != fc->sc_variant.initial) {
658                                                 fcb_changed = fc;
659                                         }
660                                 }
661                                 if (fc->sc_variant.try != fc->sc_variant.initial)
662                                         all_combinations_tried = false;
663                         }
664                 }
665
666                 if (criterion > best_criterion) {
667                         ret = reserve_resource(resource);
668                         switch (ret) {
669                         case FRSH_NO_ERROR:
670                                 best_criterion = criterion;
671                                 break;
672                         case FRSH_ERR_CONTRACT_REJECTED:
673                                 break;
674                         default:
675                                 goto err;
676                         }
677                 }
678         } while (!all_combinations_tried);
679
680         if (best_criterion == -1) {
681                 ret = FRSH_ERR_CONTRACT_REJECTED;
682         } else {
683                 /* At least some variant succeeded */
684                 ret = 0;
685                 sc_contracts_init_head(resource);
686                 ul_list_for_each(reservation_list, rl, fc) {
687                         s = fres_contract_get_spare_capacity(fc->to_be_reserved_contract);
688                         if (s && s->granularity == FRSH_GR_DISCRETE) {
689                                 sc_contracts_insert(resource, fc);
690                         }
691                 }
692         }
693 err:
694         ul_list_for_each(reservation_list, rl, fc) {
695                 fres_contract_destroy(fc->to_be_reserved_contract);
696                 fc->to_be_reserved_contract = NULL;
697         }
698         return ret;
699 }
700
701 /**
702  * Create/change VReses according to @a schedulable_contracts.
703  *
704  * There might be more allocators for schedulable contracts, so merge
705  * adjacent vreses with the same allocator together and create/change
706  * them in one step. Also the order of schedulable contracts might be
707  * different from the initial order od ids in commit_contracts()
708  * therefore we have to search for every contract.
709  */
710 static int
711 change_vreses(struct fcb *fcb, fres_contract_ptr_seq *schedulable_contracts)
712 {
713         struct res_alloc *last_ra = NULL;
714         fres_contract_ptr_seq vreses;
715         int i, ret = 0;
716         CORBA_Environment ev;
717         
718         if (!forb_sequence_alloc_buf(&vreses, schedulable_contracts->_length)) {
719                 return errno;
720         }
721         vreses._length = 0;
722         
723         for (i=0; i<schedulable_contracts->_length; i++) {
724                 struct fcb_contract *fc;
725                 struct fres_contract *sc = schedulable_contracts->_buffer[i];
726
727                 log_contract("Changing VRES", i, sc);
728
729                 fc = fcb_contract_find(fcb, &sc->id);
730                 assert(fc != NULL);
731
732                 if (true /* TODO: if the schedulable contract is changed */) {
733                         if (last_ra != fc->ra) {
734                                 if (vreses._length) {
735                                         ret = fres_resource_allocator_change_vreses(last_ra->ra,
736                                                                                     &vreses, &ev);
737                                         if (forb_exception_occurred(&ev)) {
738                                                 ret = fres_forbex2err(&ev);
739                                                 goto err;
740                                         }
741                                         if (ret) goto err;
742                                 }
743                                 vreses._length = 0;
744                         }
745                         vreses._buffer[vreses._length] = sc;
746                         vreses._length++;
747                         last_ra = fc->ra;
748                 
749                 }
750         }
751         if (last_ra) {
752                 ret = fres_resource_allocator_change_vreses(last_ra->ra,
753                                                             &vreses, &ev);
754                 if (forb_exception_occurred(&ev))
755                         ret = fres_forbex2err(&ev);
756         }
757 err:
758         forb_sequence_free_buf(&vreses, forb_no_destructor);
759         return ret;
760 }
761
762 void
763 free_fcb_contracts(struct fcb_contract *fcb_contracts[], int num)
764 {
765         int i;
766         struct fcb_contract *fc;
767         for (i=0; i<num; i++) {
768                 fc = fcb_contracts[i];
769                 if (fc && !fc->user_contract) {
770                         fc->requested_contract = NULL; /* Destroyed by FORB */
771                         fcb_contract_destroy(fc);
772                 }
773         }
774         free(fcb_contracts);
775 }
776
777 int
778 commit_resource(struct resource *resource,
779                 fres_contract_ptr_seq **schedulable_contracts)
780 {
781         int ret;
782         fres_contract_id_seq commit_ids;
783         int i;
784         struct fcb_contract *fc;
785         CORBA_Environment ev;
786         
787         if (!forb_sequence_alloc_buf(&commit_ids, resource->rl.length)) {
788                 ret = errno;
789                 goto err;
790         }
791
792         commit_ids._length = resource->rl.length;
793         i=0;
794         ul_list_for_each(reservation_list, &resource->rl, fc) {
795                 forb_sequence_elem(&commit_ids, i) = fc->id;
796                 i++;
797         }
798         
799         fres_resource_manager_commit_contracts(resource->mng, &commit_ids,
800                                                schedulable_contracts, &ev);
801         if (forb_exception_occurred(&ev)) {
802                 ret = fres_forbex2err(&ev);
803                 goto err_free;
804         }
805         return 0;
806 err_free:
807         forb_sequence_free_buf(&commit_ids, forb_no_destructor);
808 err:
809         return ret;
810 }
811
812 int cancel_reservations(struct resource *resource)
813 {
814         int ret;
815         fres_contract_id_seq commit_ids;
816         int i;
817         struct fcb_contract *fc;
818         CORBA_Environment ev;
819         
820         if (!forb_sequence_alloc_buf(&commit_ids, resource->rl.length)) {
821                 ret = errno;
822                 goto err;
823         }
824
825         commit_ids._length = resource->rl.length;
826         i=0;
827         ul_list_for_each(reservation_list, &resource->rl, fc) {
828                 forb_sequence_elem(&commit_ids, i) = fc->id;
829                 i++;
830         }
831         
832         fres_resource_manager_cancel_reservations(resource->mng, &commit_ids, &ev);
833         if (forb_exception_occurred(&ev)) {
834                 ret = fres_forbex2err(&ev);
835                 goto err_free;
836         }
837         
838         return 0;
839 err_free:
840         forb_sequence_free_buf(&commit_ids, forb_no_destructor);
841 err:
842         return ret;
843 }
844
845 /* Add new contracts to our fcb database for later
846  * reference. Canceled contracts are removed below. */
847 int
848 fcb_remember_contracts(struct fcb *fcb,
849                        struct fcb_contract **fcb_contracts, int num)
850 {
851         struct fcb_contract *fc;
852         int i;
853         
854         for (i=0; i<num; i++) {
855                 fc =  fcb_contracts[i];
856
857                 if (fc->user_contract) {
858                         if (fres_contract_get_num_blocks(fc->requested_contract) > 0) {
859                                 /* Renegotiation */
860                                 fres_contract_destroy(fc->user_contract);
861                                 fc->user_contract = fres_contract_duplicate(fc->requested_contract);
862                                 /* Note: requested_contract is also
863                                  * pointed by contracts parameter and
864                                  * will be freed by FORB. */
865                                 fc->requested_contract = NULL;
866                         }
867                 } else {
868                         /* Insert new contracts */
869                         fcb_contract_insert(fcb, fcb_contracts[i]);
870                         fc->user_contract = fres_contract_duplicate(fc->requested_contract);
871                         fc->requested_contract = NULL;
872                         /* See the note above. */
873                 }
874         }
875         return 0;
876 }
877
878 int
879 fcb_remember_schedulable_contracts(struct fcb *fcb,
880                                    fres_contract_ptr_seq *schedulable_contracts)
881 {
882         struct fcb_contract *fc;
883         int i;
884         for (i=0; i<schedulable_contracts->_length; i++) {
885                 struct fres_contract *sc = schedulable_contracts->_buffer[i];
886                 fc = fcb_contract_find(fcb, &sc->id);
887                 assert(fc != NULL);
888                 fres_contract_destroy(fc->schedulable_contract);
889                 fc->schedulable_contract = fres_contract_duplicate(sc);
890                 assert(fc->schedulable_contract);
891         }
892         return 0;
893 }
894
895 static int
896 reject_transactions(struct fcb_contract *fcb_contracts[], int num)
897 {
898         int i;
899         for (i = 0; i < num; i++) {
900                 if (fcb_contracts[i]->transaction)
901                         return FRES_ERR_VRES_PART_OF_TRANSACTION;
902         }
903         return 0;
904 }
905
906 CORBA_long
907 negotiate_contracts(fres_contract_broker obj,
908                     const fres_contract_ptr_seq* contracts,
909                     fres_contract_id_seq** ids_out,
910                     CORBA_Environment *ev)
911 {
912         struct fcb *fcb = o2fcb(obj);
913         struct resource *resource = NULL;
914         int ret = 0;
915         forb_server_id app;
916         fres_contract_ptr_seq *schedulable_contracts;
917         struct fcb_contract **fcb_contracts;
918         unsigned i;
919         int num = contracts->_length;
920
921         /* Prepare output sequence for the case we return eariler with
922          * an error */
923         forb_sequence_alloc(*ids_out, 0);
924         if (!*ids_out) {
925                 ev->major = FORB_EX_NO_MEMORY;
926                 goto err;
927         }
928         CORBA_sequence_set_release(*ids_out, CORBA_TRUE);
929         
930         forb_get_req_source(obj, &app);
931         
932         fcb_contracts = malloc(sizeof(fcb_contracts[0])*num);
933         if (!fcb_contracts) {
934                 ret = errno;
935                 goto err;
936         }
937         memset(fcb_contracts, 0, sizeof(fcb_contracts[0])*num);
938
939         ret = prepare_fcb_contracts(fcb, fcb_contracts,
940                                     contracts->_buffer, num);
941         if (ret)
942                 goto err_free_fcb_contracts;
943
944         ret = reject_transactions(fcb_contracts, num);
945         if (ret)
946                 goto err_free_fcb_contracts;
947         ret = check_and_setup_resource(fcb, fcb_contracts, &resource,
948                                        &app, num);
949         if (ret)
950                 goto err_free_fcb_contracts;
951
952         prepare_reservation_list(resource, fcb_contracts, num);
953
954         /* Reserve contracts */
955         ret = rebalance_spare_capacity_and_reserve(resource);
956         if (ret) {
957                 if (ret == FRSH_ERR_CONTRACT_REJECTED) {
958                         ul_logmsg("Contract(s) was/were rejected\n");
959                 } else {
960                         char msg[100];
961                         fres_strerror(ret, msg, sizeof(msg));
962                         ul_logerr("Reservation error: %s\n", msg);
963                 }
964                 goto err_free_fcb_contracts;
965         }
966
967         /* Commit contracts */
968         ret = commit_resource(resource, &schedulable_contracts);
969         if (ret)
970                 goto err_cancel_reservation;
971
972         fcb_remember_contracts(fcb, fcb_contracts, num);
973         fcb_remember_schedulable_contracts(fcb, schedulable_contracts);
974
975         ret = change_vreses(fcb, schedulable_contracts);
976         if (ret)
977                 goto err_cancel_reservation;
978         
979         forb_sequence_free(schedulable_contracts, fres_contract_ptr_destroy);
980         if (ret != 0) {
981                 ul_logerr("VRes was not created\n");
982                 goto err_cancel_contracts;
983         }
984
985
986         /* Return IDs and delete canceled contracts from out database */
987         if (!forb_sequence_alloc_buf(*ids_out, num)) {
988                 ev->major = FORB_EX_NO_MEMORY;
989                 goto err_cancel_contracts;
990         }
991         (*ids_out)->_length = num;
992         for (i=0; i<num; i++) {
993                 struct fcb_contract *fc =  fcb_contracts[i];
994                 forb_sequence_elem(*ids_out, i) = fc->id;
995
996                 if (fc->requested_contract &&
997                     fres_contract_get_num_blocks(fc->requested_contract) == 0) {
998                         fcb_contract_delete(fcb, fc);
999                         /* Note: requested_contract is also pointed by
1000                          * contracts parameter and will be freed by FORB. */
1001                         fc->requested_contract = NULL;
1002                         fcb_contract_destroy(fc);
1003                 }
1004         }
1005         return 0;
1006
1007 err_cancel_contracts:
1008         /* TODO */
1009         goto err_free_fcb_contracts;
1010 err_cancel_reservation:
1011         cancel_reservations(resource);
1012 err_free_fcb_contracts:
1013         free_fcb_contracts(fcb_contracts, num);
1014 err:
1015         return ret;
1016 }
1017
1018 void redistribute_spare_capacity(fres_contract_broker obj,
1019                                  const frsh_resource_type_t restype,
1020                                  const frsh_resource_id_t resid,
1021                                  CORBA_Environment *ev)
1022 {
1023         struct fcb *fcb = o2fcb(obj);
1024         struct res_key key = {restype, resid };
1025         struct resource *resource;
1026         
1027         resource = fcb_resource_find(fcb, &key);
1028
1029         prepare_reservation_list(resource, NULL, 0);
1030
1031 /*      forb_sequence_alloc(ids, rl.length); */
1032 /*      if (!ids || !ids->_buffer) { */
1033 /*              ev->major = FORB_EX_NO_MEMORY; */
1034 /*              goto err_free_fcb_contracts; */
1035 /*      } */
1036 /*      CORBA_sequence_set_release(ids, CORBA_TRUE); */
1037 /*      *ids_out = ids;         /\* ids is freed by FORB *\/ */
1038         
1039         
1040         rebalance_spare_capacity_and_reserve(resource);
1041         /* Commit */
1042 }
1043
1044 CORBA_long register_resource(fres_contract_broker obj,
1045                             const frsh_resource_type_t restype,
1046                             const frsh_resource_id_t resid,
1047                             const fres_resource_desc *desc,
1048                             CORBA_Environment *ev)
1049 {
1050         struct fcb *fcb = o2fcb(obj);
1051         struct resource *res, *res2;
1052
1053         res = malloc(sizeof(*res));
1054         if (!res) goto err;
1055         memset(res, 0, sizeof(*res));
1056         res->key.type = restype;
1057         res->key.id = resid;
1058         res2 = fcb_resource_find(fcb, &res->key);
1059         if (res2) {
1060                 if (forb_object_is_stale(res2->mng)) {
1061                         ul_logmsg("Removing stale manager for resource %d.%d\n",
1062                                   restype, resid);
1063                         forb_object_release(res2->mng);
1064                         fcb_resource_delete(fcb, res2);
1065                         /* TODO: Delete also all allocators associated
1066                          * with this stale resource manager. */
1067                         free(res);
1068                         res = res2;
1069                 } else {
1070                         ul_logerr("Resource manager %d.%d already registered\n",
1071                                   restype, resid);
1072                         goto free_err;
1073                 }
1074         }
1075         res->mng = forb_object_duplicate(desc->manager);
1076         res->name = desc->name;
1077
1078         fcb_alloc_init_root_field(res);
1079         sc_contracts_init_head(res);
1080         ul_logmsg("Registering manager for resource \"%s\" (%d.%d)\n",
1081                   res->name, restype, resid);
1082         fcb_resource_insert(fcb, res);
1083         return 0;
1084 free_err:
1085         free(res);
1086 err:
1087         return -1;
1088 }
1089
1090
1091 CORBA_long register_allocator(fres_contract_broker obj,
1092                               const frsh_resource_type_t restype,
1093                               const frsh_resource_id_t resid,
1094                               const fres_resource_allocator ra_obj,
1095                               CORBA_Environment *ev)
1096 {
1097         struct fcb *fcb = o2fcb(obj);
1098         struct resource *res;
1099         struct res_alloc *ra;
1100         struct res_key resource;
1101         forb_server_id server_id;
1102         char server_id_str[40];
1103         int ret;
1104
1105         forb_get_server_id(ra_obj, &server_id);
1106         forb_server_id_to_string(server_id_str, &server_id, sizeof(server_id_str));
1107         ul_logmsg("Registering allocator for resource %d.%d in app %s\n",
1108                   restype, resid, server_id_str);
1109         
1110         resource.type = restype;
1111         resource.id = resid;
1112         res = fcb_resource_find(fcb, &resource);
1113         if (!res) {
1114                 ul_logerr("No manager found for %d.%d. Unable to register the allocator!\n",
1115                           restype, resid);
1116                 ret = FRES_ERR_NO_RESOURCE_MANAGER;
1117                 goto err;
1118         }
1119         ra = fcb_alloc_find(res, &server_id);
1120         if (ra) {
1121                 char *str = forb_object_to_string(ra_obj);
1122                 ul_logerr("Allocator from already registered (%s)\n",
1123                           str);
1124                 forb_free(str);
1125                 ret = FRES_ERR_ALLOCATOR_ALREADY_REGISTERED;
1126                 goto err;
1127         }
1128         ra = malloc(sizeof(*ra));
1129         if (!ra) {
1130                 ret = ENOMEM;
1131                 goto err;
1132         }
1133         ra->app = server_id;
1134         ra->ra = forb_object_duplicate(ra_obj);
1135         fcb_alloc_insert(res, ra);
1136         return 0;
1137 err:
1138         return ret;
1139 }
1140
1141 void get_resources(fres_contract_broker obj, fres_resource_seq** resources, CORBA_Environment *ev)
1142 {
1143         struct fcb *fcb = o2fcb(obj);
1144         fres_resource_seq *seq;
1145         struct resource *res;
1146         int n;
1147
1148         seq = malloc(sizeof(*seq));
1149         if (!seq) {
1150                 ev->major = FORB_EX_NO_MEMORY;
1151                 return;
1152         }
1153         memset(seq, 0, sizeof(*seq));
1154
1155         n=0;
1156         gavl_cust_for_each(fcb_resource, fcb, res) {
1157                 n++;
1158         }
1159
1160         seq->_buffer = CORBA_sequence_fres_resource_allocbuf(n);
1161         seq->_maximum = n;
1162         seq->_length = n;
1163
1164         n = 0;
1165         gavl_cust_for_each(fcb_resource, fcb, res) {
1166                 seq->_buffer[n].restype = res->key.type;
1167                 seq->_buffer[n].resid = res->key.id;
1168                 seq->_buffer[n].desc.manager = res->mng;
1169                 seq->_buffer[n].desc.name = res->name;
1170                 n++;
1171         }
1172
1173         *resources = seq;
1174 }
1175
1176 static bool
1177 transaction_has_spare_capacity(const fres_transaction_t* transaction)
1178 {
1179         struct fres_contract **c;
1180         forb_sequence_foreach(&transaction->contracts, c)
1181                 if (fres_contract_get_spare_capacity(*c))
1182                         return true;
1183         return false;
1184 }
1185
1186 static int
1187 transaction_get_resources(struct fcb *fcb, struct fcb_contract *fc[],
1188                           int num, struct res_array *res_array)
1189 {
1190         int i;
1191         struct resource *resource;
1192         struct res_key key;
1193         int ret;
1194
1195         for (i = 0; i < num; i++) {
1196                 get_fc_res_key(fc[i], &key);
1197                 resource = fcb_resource_find(fcb, &key);
1198                 ret = res_array_insert(res_array, resource);
1199                 if (ret == -1) {
1200                         ret = FRSH_ERR_INTERNAL_ERROR;
1201                         goto err;
1202                 }
1203         }
1204         ret = 0;
1205 err:
1206         return ret;
1207 }
1208                                  
1209 CORBA_long
1210 negotiate_transaction(fres_contract_broker _obj,
1211                       const fres_transaction_t* transaction,
1212                       CORBA_Environment *ev)
1213 {
1214         struct fcb *fcb = o2fcb(_obj);
1215         struct fcb_contract **fcb_contracts, *fc;
1216         const fres_contract_ptr_seq* user_contracts = &transaction->contracts;
1217         int i, ret, num = user_contracts->_length;
1218         struct res_array res_array;
1219         struct res_key key;
1220         struct resource *resource;
1221         fres_contract_ptr_seq *schedulable_contracts;
1222         struct fcb_transaction *ft;
1223
1224         ul_logmsg("Negotiating transaction '%s' with %d contracts\n", transaction->name, num);
1225         if (transaction_has_spare_capacity(transaction)) {
1226                 ret =  FRES_ERR_SPARE_CAPACITY_NOT_SUPPORTED;
1227                 goto err;
1228         }
1229
1230         fcb_contracts = malloc(sizeof(*fcb_contracts)*num);
1231         if (!fcb_contracts) {
1232                 ret = errno;
1233                 goto err;
1234         }
1235         memset(fcb_contracts, 0, sizeof(*fcb_contracts)*num);
1236
1237         ret = prepare_fcb_contracts(fcb, fcb_contracts,
1238                                     user_contracts->_buffer, num);
1239         if (ret)
1240                 goto err_free_fcb_contracts;
1241
1242         res_array_init_array_field(&res_array);
1243         ret = transaction_get_resources(fcb, fcb_contracts, num, &res_array);
1244
1245         gsa_cust_for_each(res_array, &res_array, resource) {
1246                 reservation_list_init_head(&resource->rl);
1247                 resource->rl.length = 0;
1248                 for (i = 0; i < num; i++) {
1249                         fc = fcb_contracts[i];
1250                         get_fc_res_key(fc, &key);
1251                         if (res_key_cmp(&key, &resource->key) == 0) {
1252                                 reservation_list_insert(&resource->rl, fc);
1253                                 resource->rl.length++;
1254                         }
1255                 }
1256         }
1257         gsa_cust_for_each(res_array, &res_array, resource) {
1258                 ret = reserve_resource(resource);
1259                 if (ret) {
1260                         ul_logerr("Reservation failed\n");
1261                         goto err_cancel_reservation;
1262                 }
1263         }
1264         fcb_remember_contracts(fcb, fcb_contracts, num);
1265         gsa_cust_for_each(res_array, &res_array, resource) {
1266                 ret = commit_resource(resource, &schedulable_contracts);
1267                 if (ret) {
1268                         ul_logerr("Commit failed\n");
1269                         goto err_cancel_reservation;
1270                 }
1271                 fcb_remember_schedulable_contracts(fcb, schedulable_contracts);
1272                 forb_sequence_free(schedulable_contracts, fres_contract_ptr_destroy);
1273         }
1274
1275         ft = fcb_transaction_new(transaction->name);
1276         if (!ft) {
1277                 ret = errno;
1278                 goto err_cancel_reservation;
1279         }
1280         enum { NONE, CANCELATION, NEGOTIATION } op = NONE;
1281         for (i = 0; i < num; i++) {
1282                 fc =  fcb_contracts[i];
1283                 if (fc->requested_contract &&
1284                     fres_contract_get_num_blocks(fc->requested_contract) == 0) {
1285                         assert(i == 0 || op == CANCELATION);
1286                         op = CANCELATION;
1287                         /* TODO: Review and test transaction cancelation!!! */
1288                         fcb_contract_delete(fcb, fc);
1289                         /* Note: requested_contract is also pointed by
1290                          * contracts parameter and will be freed by FORB. */
1291                         fc->requested_contract = NULL;
1292                         fcb_contract_destroy(fc);
1293                 } else {
1294                         assert(i == 0 || op == NEGOTIATION);
1295                         op = NEGOTIATION;
1296                         tran_contract_insert_at(ft, fc, i);
1297                         fc->transaction = ft;
1298                 }
1299         }
1300         switch (op) {
1301         case NEGOTIATION:
1302                 fcb_transaction_insert(fcb, ft);
1303                 break;
1304         case CANCELATION:
1305                 fcb_transaction_delete(fcb, ft);
1306                 fcb_transaction_destroy(ft);
1307                 break;
1308         default:
1309                 assert(false);
1310         }
1311         res_array_delete_all(&res_array);
1312         return 0;
1313 err_cancel_reservation:
1314         gsa_cust_for_each(res_array, &res_array, resource) {
1315                 cancel_reservations(resource);
1316         }
1317         res_array_delete_all(&res_array);
1318 err_free_fcb_contracts:
1319         free_fcb_contracts(fcb_contracts, num);
1320 err:
1321         return ret;
1322 }
1323
1324 CORBA_long
1325 wait_transaction(fres_contract_broker _obj,
1326                  const CORBA_char * name,
1327                  fres_transaction_t** transaction,
1328                  CORBA_Environment *ev)
1329 {
1330         return FRSH_ERR_NOT_IMPLEMENTED;
1331 }
1332
1333 CORBA_long
1334 allocate_transaction_vres(fres_contract_broker _obj,
1335                           const CORBA_char * name,
1336                           const CORBA_long index,
1337                           fres_contract_id_t *id,
1338                           CORBA_Environment *ev)
1339 {
1340         struct fcb *fcb = o2fcb(_obj);
1341         struct fcb_transaction *ft;
1342         struct fcb_contract *fc;
1343         int ret;
1344         struct res_alloc *ra;
1345         char * const *n = (char * const *)&name;
1346         struct res_key key;
1347         struct resource *resource;
1348         fres_contract_ptr_seq vreses;
1349         CORBA_Environment ev2;
1350         forb_server_id app;
1351 #define GOTO(label, error) do { ret = (error); goto label; } while(0)
1352
1353         ul_logmsg("Allocate transaction VRES '%s'[%d]\n", name, index);
1354         
1355         ft = fcb_transaction_find(fcb, n);
1356         if (!ft) GOTO(err, FRES_ERR_TRANSACTION_NOT_FOUND);
1357
1358         fc = tran_contract_indx2item(ft, index);
1359         if (!fc) GOTO(err, FRSH_ERR_TOO_LARGE);
1360
1361         if (!get_fc_res_key(fc, &key))
1362                 GOTO(err, FRSH_ERR_RESOURCE_ID_INVALID);
1363         resource = fcb_resource_find(fcb, &key);
1364         if (!resource)
1365                 GOTO(err, FRES_ERR_NO_RESOURCE_MANAGER);
1366
1367         forb_get_req_source(_obj, &app);
1368         /* Find allocator for the requested VRES */
1369         ra = fcb_alloc_find(resource, &app);
1370         if (!ra) {
1371                 char str[60];
1372                 forb_server_id_to_string(str, &app, sizeof(str));
1373                 ul_logerr("No resource allocator found for %d.%d and %s\n",
1374                           resource->key.type, resource->key.id, str);
1375                 GOTO(err, FRES_ERR_NO_RESOURCE_ALLOCATOR);
1376         }
1377         fc->ra = ra;
1378
1379         if (!forb_sequence_alloc_buf(&vreses, 1))
1380                 GOTO(err, errno);
1381
1382         assert(fc->schedulable_contract);
1383         forb_sequence_elem(&vreses, 0) = fc->schedulable_contract;
1384         forb_sequence_length(&vreses) = 1;
1385         ret = fres_resource_allocator_change_vreses(ra->ra, &vreses, &ev2);
1386         ul_logerr("Err = %d\n", ret);
1387         if (forb_exception_occurred(&ev2))
1388                 GOTO(err_free, fres_forbex2err(&ev2));
1389         if (ret)
1390                 goto err_free;
1391         *id = fc->id;
1392         
1393         ret = 0;
1394 err_free:
1395         forb_sequence_free_buf(&vreses, forb_no_destructor);
1396 err:
1397         return ret;
1398 }
1399
1400
1401 #if CONFIG_FCB_INET && !CONFIG_FORB_PROTO_INET_DEFAULT
1402 static int register_inet_port(forb_orb orb)
1403 {
1404         forb_port_t *port = forb_malloc(sizeof(*port));
1405         int ret;
1406         struct in_addr listen_on;
1407         
1408         if (!port)
1409                 return -1;
1410         memset(port, 0, sizeof(*port));
1411         listen_on.s_addr = INADDR_ANY;
1412         ret = forb_inet_port_init(&port->desc, listen_on, 0);
1413         if (ret)
1414                 return ret;
1415         ret = forb_register_port(orb, port);
1416         return ret;
1417 }
1418 #endif
1419
1420 struct forb_fres_contract_broker_impl impl = {
1421         .negotiate_contracts = negotiate_contracts,
1422         .register_resource = register_resource,
1423         .register_allocator = register_allocator,
1424         .redistribute_spare_capacity = redistribute_spare_capacity,
1425         .get_resources = get_resources,
1426         .negotiate_transaction = negotiate_transaction,
1427         .wait_transaction = wait_transaction,
1428         .allocate_transaction_vres = allocate_transaction_vres,
1429 };
1430
1431 void peer_discovery_callback(const forb_orb peer_orb, const char *orb_id)
1432 {
1433         forb_server_id server_id;
1434         char server_id_str[sizeof(forb_server_id)*2+1];
1435
1436         forb_get_server_id(peer_orb, &server_id);
1437         forb_server_id_to_string(server_id_str, &server_id, sizeof(server_id_str));
1438 #if 0
1439         ul_logmsg("peer discovered: %s (orb_id '%s')\n", server_id_str, orb_id);
1440 #endif
1441
1442         if (orb_id == NULL)
1443                 return;
1444
1445         if (strcmp(orb_id, "org.frescor.fcb") == 0) {
1446                 fosa_abs_time_t now;
1447                 fosa_rel_time_t delay;
1448                 fosa_clock_get_time(CLOCK_REALTIME, &now);
1449                 delay = fosa_abs_time_extract_interval(start_time, now);
1450                 ul_logmsg("node joined: %s (time %ld ms)\n", server_id_str,
1451                           fosa_rel_time_to_msec(delay));
1452         }
1453 }
1454
1455 void peer_dead_callback(const forb_orb peer_orb, const char *orb_id)
1456 {
1457 }
1458
1459 static struct option long_opts[] = {
1460     { "daemon",   optional_argument, NULL, 'd' },
1461     { "loglevel", required_argument, NULL, 'l' },
1462     { 0, 0, 0, 0}
1463 };
1464
1465 static void
1466 usage(void)
1467 {
1468         printf("usage: fcb [ options ]\n");
1469         printf("  -d, --daemon [pid-file]   go to background after FORB initialization\n");
1470         printf("  -l, --loglevel <number>|<domain>=<number>,...\n");
1471 }
1472
1473 int print_log_domain(ul_log_domain_t *domain, void *context)
1474 {
1475         printf("%s = %d\n", domain->name, domain->level);
1476         return 0;
1477 }
1478
1479 int main(int argc, char *argv[])
1480 {
1481         forb_orb orb;
1482         struct fcb fcb_data;
1483         fres_contract_broker fcb;
1484         forb_executor_t executor;
1485         int ret;
1486         forb_init_attr_t attr = {
1487                 .orb_id = "org.frescor.fcb",
1488                 .peer_discovery_callback = peer_discovery_callback,
1489                 .peer_dead_callback = peer_dead_callback,
1490                 .fixed_tcp_port = FCB_TCP_PORT,
1491 #ifdef CONFIG_FORB_PROTO_INET_DEFAULT           
1492                 .fixed_server_id = FCB_SERVER_ID,
1493                 .redistribute_hellos = true,
1494 #endif
1495         };
1496         int  opt;
1497
1498         while ((opt = getopt_long(argc, argv, "d::l:", &long_opts[0], NULL)) != EOF) {
1499                 switch (opt) {
1500                         case 'l':
1501                                 if (*optarg == '?') {
1502                                         ul_logreg_for_each_domain(print_log_domain, NULL);
1503                                         exit(0);
1504                                 }
1505                                 {
1506                                         int ret;
1507                                         ret = ul_log_domain_arg2levels(optarg);
1508                                         if (ret) 
1509                                                 error(1, EINVAL, "Error parsing -l argument at char %d\n", ret);
1510                                 }
1511                                 break;
1512                         case 'd':
1513                                 opt_daemon = true;
1514                                 opt_pidfile = optarg;
1515                                 break;
1516                         case 'h':
1517                         /*default:*/
1518                                 usage();
1519                                 exit(opt == 'h' ? 0 : 1);
1520                 }
1521         }
1522
1523         memset(&fcb_data, 0, sizeof(fcb_data));
1524         fosa_clock_get_time(CLOCK_REALTIME, &start_time);
1525
1526         if (opt_daemon)
1527                 forb_daemon_prepare(opt_pidfile);
1528
1529         orb = forb_init(&argc, &argv, &attr);
1530         if (!orb) error(1, errno, "FORB initialization failed");
1531
1532 #if CONFIG_FCB_INET && !CONFIG_FORB_PROTO_INET_DEFAULT
1533         ret = register_inet_port(orb);
1534         if (ret) error(0, errno, "INET port registration failed");
1535 #endif
1536
1537         fcb_resource_init_root_field(&fcb_data);
1538         fcb_contract_init_root_field(&fcb_data);
1539         fcb_transaction_init_root_field(&fcb_data);
1540
1541         fcb = forb_fres_contract_broker_new(orb, &impl, &fcb_data);
1542         if (!fcb) error(1, errno, "forb_fres_contract_broker_new failed");
1543
1544         /* Prepare executor before we register the fcb reference,
1545          * so that no reuqests are lost */
1546         ret = forb_executor_init(&executor);
1547         if (ret) error(1, errno, "forb_executor_init failed");
1548         
1549         ret = forb_executor_register_object(&executor, fcb);
1550         if (ret) error(1, errno, "forb_executor_register_object failed");
1551
1552         ret = forb_register_reference(fcb, fres_contract_broker_reg_name);
1553         if (ret) error(1, errno, "forb_register_reference() failed");
1554
1555         ul_logmsg("Waiting for requests\n");
1556         if (opt_daemon)
1557                 forb_daemon_ready();
1558
1559         ret = forb_executor_run(&executor);
1560         if (ret) error(1, errno, "forb_executor_run failed");
1561         
1562         return 0;
1563 }