]> rtime.felk.cvut.cz Git - frescor/forb.git/blob - src/forb.c
dee15872072afbba395de57e31d456172ace6ab3
[frescor/forb.git] / src / forb.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 FORB (Frescor Object Request Broker)             */
26 /*                                                                        */
27 /* FORB 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.  FORB 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 FORB; 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 FORB header files in a file,         */
39 /* instantiating FORB generics or templates, or linking other files       */
40 /* with FORB 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   forb.c
49  * @author Michal Sojka <sojkam1@fel.cvut.cz>
50  * @date   Sun Oct 12 16:57:01 2008
51  * 
52  * @brief  Implementation of basic FORB's functions.
53  * 
54  * 
55  */
56
57 #ifndef _BSD_SOURCE
58 #define _BSD_SOURCE             /* Because of on_exit()  */
59 #endif
60 #include "proto.h"
61 #include "regref.h"
62 #include <forb/config.h>
63 #include <forb/forb-internal.h>
64 #include <forb.h>
65 #include "forb-idl.h"
66 #include <forb/iop.h>
67 #include <forb/object.h>
68 #include <forb/uuid.h>
69 #include <stdio.h>
70 #include <string.h>
71 #include <sys/stat.h>
72 #include <sys/types.h>
73 #include <ul_gavlcust.h>
74 #include <ul_log.h>
75 #include <ul_logreg.h>
76 #include <unistd.h>
77 #include "discovery.h"
78 #ifdef CONFIG_FORB_PROTO_UNIX
79 #include <forb/proto_unix.h>
80 #endif
81 #ifdef CONFIG_FORB_PROTO_INET_DEFAULT
82 #include <forb/proto_inet.h>
83 #endif
84 #ifdef CONFIG_FCB
85 #include <fcb.h>
86 #include <fcb_contact_info.h>
87 #endif
88 #include <fcntl.h>
89
90 #ifdef DEBUG
91 #define UL_LOGL_DEF UL_LOGL_DEB
92 #else
93 #define UL_LOGL_DEF UL_LOGL_ERR
94 #endif
95 #include "log_domains.inc"
96
97 extern UL_LOG_CUST(ulogd_forb);
98 static int init_ul_log(void);
99
100 UL_LOGREG_DOMAINS_INIT_FUNCTION(forb_logreg_domains, forb_logreg_domains_array);
101
102 #if 0
103 static void
104 destroy_forb_on_exit(int exitcode, void *arg)
105 {
106         forb_orb orb = arg;
107         forb_destroy(orb);
108 }
109 #endif
110
111 static void
112 forb_is_alive(forb_orb _obj, CORBA_Environment *ev)
113 {
114         ul_logdeb("%s called\n", __FUNCTION__);
115 }
116
117 static struct forb_forb_orb_impl forb_implementation = {
118         .is_alive = forb_is_alive,
119 };
120
121 /**
122  * Prepares #FORB_TMP_DIR directory for use by forb
123  *
124  * @return Zero on succes, -1 on error and errno is set appropriately.
125  */
126 int
127 forb_init_tmp_dir(void)
128 {
129         struct stat st;
130         int ret;
131
132         ret = stat(FORB_TMP_DIR, &st);
133
134         if (ret == 0 && !S_ISDIR(st.st_mode)) {
135                 ret = unlink(FORB_TMP_DIR);
136                 if (ret) return -1;
137         } else if (ret == 0) {
138                 return 0;
139         }
140         return mkdir(FORB_TMP_DIR, 0777);
141 }
142
143 /** 
144  * Thread for execution of remote requests for a FORB object.
145  * 
146  * @param arg 
147  * 
148  * @return 
149  */
150 static void *
151 forb_execution_thread(void *arg)
152 {
153         forb_orb orb = arg;
154
155         forb_execute_object(orb);
156         return NULL;
157 }
158
159 #ifdef CONFIG_FCB
160 void hack_register_fcb(forb_orb orb, forb_port_t *port)
161 {
162         forb_object fcb = forb_object_new(orb, &FCB_SERVER_ID, 1);
163         if (!fcb) {
164                 ul_logerr("Cannot allocate FCB reference\n");
165                 return;
166         }
167         forb_register_reference(fcb, fres_contract_broker_reg_name);
168         forb_object_release(fcb);
169 }
170 #else
171 #define hack_register_fcb(orb)
172 #endif
173
174
175
176 forb_orb
177 forb_init(int *argc, char **argv[], const struct forb_init_attr *attr)
178 {
179         forb_orb orb;
180         forb_t *forb;
181         int ret;
182
183         forb = forb_malloc(sizeof(*forb));
184         if (!forb) goto err;
185         memset(forb, 0, sizeof(*forb));
186
187         /* Initialize ULUT logging facility */
188         init_ul_log();
189         forb_logreg_domains();
190
191         if (attr) {
192                 forb->attr = *attr;
193         } else {
194                 memset(&forb->attr, 0, sizeof(forb->attr));
195         }
196
197         if (forb_server_id_empty(&forb->attr.fixed_server_id)) {
198                 forb_server_id_init(&forb->server_id);
199         } else {
200                 forb->server_id = forb->attr.fixed_server_id;
201         }
202         forb_server_id_to_string(forb->server_id_str, &forb->server_id,
203                                  sizeof(forb->server_id_str));
204         ul_logdeb("Initializing forb %s\n", forb->server_id_str);
205
206         if (fosa_mutex_init(&forb->request_id_mutex, 0) != 0) goto err2;
207         if (fosa_mutex_init(&forb->port_mutex, 0) != 0) goto err2;
208         forb_port_init_head(forb);
209         
210         if (fosa_mutex_init(&forb->request_mutex, 0) != 0) goto err2;
211         forb_request_nolock_init_root_field(forb);
212
213         if (forb_discovery_init(forb) != 0) goto err2;
214
215         if (fosa_mutex_init(&forb->regref_mutex, 0) != 0) goto err2;
216         forb_regref_nolock_init_root_field(forb);
217
218         ret = forb_init_tmp_dir();
219         if (ret != 0) {
220                 ul_logerr("Cannot prepare " FORB_TMP_DIR "\n");
221                 return NULL;
222         }
223
224         orb = forb_forb_orb_new(NULL, &forb_implementation, forb);
225         if (!orb) goto err2;
226         /* Server ID must be assigned manualy */
227         orb->server = forb->server_id;
228
229         forb->orb = orb;
230
231         /* Insert our object reference to objects tree, so that we
232          * can accept remote request to our new ORB. */
233         forb_objects_nolock_insert(forb, orb);
234
235         ret = fosa_thread_create(&forb->execution_thread, NULL,
236                                  forb_execution_thread, orb);
237         if (ret != 0)
238                 goto err2;
239
240         /* FIXME: I do not know how to deregister the exit handler if
241          * forb_destroy() is called manually. */
242         /* on_exit(destroy_forb_on_exit, orb); */
243
244 #ifdef CONFIG_FORB_PROTO_UNIX
245         {
246                 forb_port_t *port = forb_malloc(sizeof(*port));
247                 if (port) {
248                         memset(port, 0, sizeof(*port));
249                         ret = forb_unix_port_init(&port->desc, &forb->server_id);
250                         if (ret) goto err_free_unix;
251                         ret = forb_register_port(orb, port);
252                         if (ret) goto err_free_unix; /* TODO: forb_unix_port_done() */
253                         goto unix_ok;
254                 }
255         err_free_unix:
256                 free(port);
257                 goto err2;
258         unix_ok:;
259         }
260 #endif
261 #ifdef CONFIG_FORB_PROTO_INET_DEFAULT
262         {
263                 forb_port_t *port = forb_malloc(sizeof(*port));
264                 if (port) {
265                         struct in_addr listen_on;
266
267                         memset(port, 0, sizeof(*port));
268                         listen_on.s_addr = INADDR_ANY;
269                         ret = forb_inet_port_init(&port->desc, listen_on,
270                                                   forb->attr.fixed_tcp_port);
271                         if (ret) goto err_free_inet;
272                         ret = forb_register_port(orb, port);
273                         if (ret) goto err_free_inet; /* TODO: forb_inet_port_done() */
274                         goto inet_ok;
275                 }
276         err_free_inet:
277                 free(port);
278                 goto err2;
279         inet_ok:;
280                 hack_register_fcb(orb, port);
281         }
282 #endif
283         return orb;
284
285 err2:   forb_free(forb);
286 err:    return NULL;
287 }
288
289 void forb_destroy(forb_orb orb)
290 {
291         forb_t *forb = forb_object_to_forb(orb);
292         forb_port_t *port;
293         forb_regref_t *regref;
294
295         pthread_cancel(forb->execution_thread.pthread_id);
296         pthread_join(forb->execution_thread.pthread_id, NULL);
297         
298         /* Unregister all registered references */
299         while ((regref = forb_regref_first(forb))) {
300                 forb_unregister_reference(orb, regref->name.str);
301         }
302         
303         ul_list_for_each_cut(forb_port, forb, port) {
304                 forb_destroy_port(port);
305         }
306         forb_object_release(orb);
307         forb_free(forb);
308 }
309
310 /* void */
311 /* forb_register_interface(const struct forb_interface *interface) */
312 /* { */
313 /*      gavl_insert(&type_registry, &interface->node); */
314 /* } */
315
316 /** 
317  * Initializes server ID variable.
318  * 
319  * @param server_id Serer ID to initialize.
320  */
321 void
322 forb_server_id_init(forb_server_id *server_id)
323 {
324         forb_uuid_generate((forb_uuid_t*)server_id->uuid);
325 }
326
327 /** 
328  * Checks whether the @a object is stale. Stale object is an object
329  * reference whose server cannot be contacted to handle requests.
330  * 
331  * @param object Object reference to check.
332  * 
333  * @return True if the object is stale, false otherwise.
334  */
335 bool forb_object_is_stale(forb_object object)
336 {
337         forb_orb remote_orb;
338         struct forb_env env;
339         bool stale = true;
340         
341         remote_orb = forb_get_orb_of(object);
342         if (!remote_orb) {      /* This shohuld never happen */
343                 goto err;
344         }
345         /* TODO: Check not only the ORB, but also whether the object
346          * is still registered with the remote orb. */
347         forb_orb_is_alive(remote_orb, &env);
348         if (env.major == FORB_EX_COMM_FAILURE) {
349                 /* Orb is not alive */
350                 stale = true;
351         } else {
352                 if (forb_exception_occurred(&env)) {
353                         ul_logerr("%s: unexpected exception: %s\n", __FUNCTION__, forb_strerror(&env));
354                 }
355                 stale = false;  
356         }
357
358         forb_object_release(remote_orb);
359 err:
360         return stale;
361 }
362
363
364 /** 
365  * Returns object reference of forb::orb object associated with the
366  * given object.
367  * 
368  * @param obj 
369  * 
370  * @return 
371  */
372 forb_orb
373 forb_get_orb_of(const forb_object obj)
374 {
375         forb_orb orb;
376
377         if (forb_server_id_cmp(&obj->server, &obj->orb->server) == 0) {
378                 orb = forb_object_duplicate(obj->orb);
379         } else {
380                 orb = forb_object_new(obj->orb, &obj->server, 0);
381         }
382         return orb;
383 }
384
385 /** 
386  * Returns server ID of an object reference.
387  * 
388  * @param obj 
389  * @param dest 
390  */
391 void
392 forb_get_server_id(const forb_object obj, forb_server_id *dest)
393 {
394         if (obj) {
395                 *dest = obj->server;
396         }
397 }
398
399
400 /** 
401  * Return instance data registered when the object was created by
402  * forb_XXX_new().
403  * 
404  * @param obj Object reference
405  * 
406  * @return Pointer to the registered data.
407  */
408 void *
409 forb_instance_data(const forb_object obj)
410 {
411         return forb_object_instance_data(obj);
412 }
413
414 /** 
415  * Returns error message correspondings FORB exception.
416  * 
417  * @param env Environemnt
418  * 
419  * @return Non-NULL pointer to a string.
420  */
421 const char *
422 forb_strerror(CORBA_Environment *env)
423 {
424         if (!env) {
425                 return "Invalid environemnt";
426         }
427 #define ex(e) case FORB_EX_##e: return #e; break;
428         switch (env->major) {
429         ex(NONE);
430         ex(UNKNOWN);
431         ex(BAD_PARAM);
432         ex(NO_MEMORY);
433         ex(IMP_LIMIT);
434         ex(COMM_FAILURE);
435         ex(INV_OBJREF);
436         ex(NO_PERMISSION);
437         ex(INTERNAL);
438         ex(MARSHAL);
439         ex(INITIALIZE);
440         ex(NO_IMPLEMENT);
441         ex(BAD_OPERATION);
442         ex(NO_RESOURCES);
443         ex(NO_RESPONSE);
444         ex(TRANSIENT);
445         ex(FREE_MEM);
446         ex(INV_IDENT);
447         ex(INV_FLAG);
448         ex(DATA_CONVERSION);
449         ex(OBJECT_NOT_EXIST);
450         ex(TIMEOUT);
451         ex(APPLICATION);
452         }
453 #undef ex
454         return "Invalid error number";
455 }
456
457 /** 
458  * Return server id of the requesting application.
459  *
460  * This function should be only called from within interface
461  * implementation,
462  * 
463  * @param[in] obj Object being requested
464  * @param[out] req_source Server ID of the requesting application
465  */
466 void
467 forb_get_req_source(const forb_object obj, forb_server_id *req_source)
468 {
469         if (req_source) {
470                 if (obj && obj->exec_req) {
471                         *req_source = obj->exec_req->source;
472                 } else {
473                         memset(req_source, 0, sizeof(*req_source));
474                 }
475         }
476 }
477
478 /**
479  * Internal function for allocation of sequence bufers. Used by
480  * forb_sequence_alloc_buf().
481  *
482  * @param seq
483  * @param seq_size
484  * @param buf_pptr
485  * @param maximum_ptr
486  * @param num_elements
487  * @param elem_size
488  *
489  * @return CORBA_TRUE if the allocation was sucessfull, CORBA_FALSE if
490  * it wasn't.
491  */
492 CORBA_boolean
493 __forb_sequence_alloc_buf_internal(void *seq, size_t seq_size,
494                                    void **buf_pptr, CORBA_unsigned_long *maximum_ptr,
495                                    unsigned num_elements, size_t elem_size)
496 {
497         memset(seq, 0, seq_size);
498         /*(seq)._length = 0;*/
499         if (num_elements && elem_size) *buf_pptr = forb_malloc(num_elements * elem_size);
500         else *buf_pptr = NULL;
501         *maximum_ptr = *buf_pptr ? num_elements : 0;
502         return (*buf_pptr != NULL) || (num_elements == 0);
503 }
504
505 static FILE *forb_ul_log_file;
506 static char progname[64] = "";
507
508 void
509 forb_ul_log_fnc(ul_log_domain_t *domain, int level,
510                 const char *format, va_list ap)
511 {
512         if(!(level&UL_LOGL_CONT)) {
513                 level&=UL_LOGL_MASK;
514                 if (progname[0])
515                         fprintf(forb_ul_log_file,"%s: ", progname);
516                 if(domain && domain->name)
517                         fprintf(forb_ul_log_file,"%s: ",domain->name);
518         }
519         vfprintf(forb_ul_log_file, format, ap);
520         fflush(forb_ul_log_file);
521 }
522
523 static int init_ul_log(void)
524 {
525         char *s;
526         char *log_fname;
527         int fd;
528         int flg = 0;
529         char path[128];
530
531 /*      if(ul_log_output != NULL) */
532 /*              return 0; */
533
534         fd = open("/proc/self/cmdline", O_RDONLY);
535         if (fd >= 0) {
536                 int ret;
537                 ret = read(fd, path, sizeof(path)-1);
538                 if (ret > 0) {
539                         path[ret]=0;
540                         s = strrchr(path, '/');
541                         if (s) s++;
542                         else s = path;
543                         strncpy(progname, s, sizeof(progname)-1);
544                 }
545                 close(fd);
546         }
547
548         if((log_fname=getenv("UL_LOG_FILENAME"))!=NULL){
549                 forb_ul_log_file=fopen(log_fname,"a");
550         }
551         if(forb_ul_log_file==NULL)
552                 forb_ul_log_file=stderr;
553         
554         if((s=getenv("UL_DEBUG_FLG")) != NULL){
555                 flg=atoi(s);
556         }
557
558         ul_log_redir(forb_ul_log_fnc, flg);
559
560         return 0;
561 }