]> rtime.felk.cvut.cz Git - frescor/forb.git/blob - src/forb.c
Added forb_get_server_id()
[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 #define _BSD_SOURCE             /* Because of on_exit()  */
58 #include "proto.h"
59 #include "regref.h"
60 #include "regref.h"
61 #include <fcntl.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 <stdlib.h>
71 #include <string.h>
72 #include <sys/stat.h>
73 #include <sys/types.h>
74 #include <ul_gavlcust.h>
75 #include <ul_log.h>
76 #include <ul_logreg.h>
77 #include <unistd.h>
78 #ifdef CONFIG_FORB_PROTO_UNIX
79 #include <forb/proto_unix.h>
80 #endif
81
82 #ifdef DEBUG
83 #define UL_LOGL_DEF UL_LOGL_DEB
84 #else
85 #define UL_LOGL_DEF UL_LOGL_ERR
86 #endif
87 #include "log_domains.inc"
88
89 extern UL_LOG_CUST(ulogd_forb);
90
91
92 static void
93 destroy_forb_on_exit(int exitcode, void *arg)
94 {
95         forb_orb orb = arg;
96         forb_destroy(orb);
97 }
98
99 static void
100 forb_is_alive(forb_orb _obj, CORBA_Environment *ev)
101 {
102         ul_logdeb("%s called\n", __FUNCTION__);
103 }
104
105 static struct forb_forb_orb_impl forb_implementation = {
106         .is_alive = forb_is_alive,
107 };
108
109 /**
110  * Prepares #FORB_TMP_DIR directory for use by forb
111  *
112  * @return Zero on succes, -1 on error and errno is set appropriately.
113  */
114 int
115 forb_init_tmp_dir(void)
116 {
117         struct stat st;
118         int ret;
119
120         ret = stat(FORB_TMP_DIR, &st);
121
122         if (ret == 0 && !S_ISDIR(st.st_mode)) {
123                 ret = unlink(FORB_TMP_DIR);
124                 if (ret) return -1;
125         } else if (ret == 0) {
126                 return 0;
127         }
128         return mkdir(FORB_TMP_DIR, 0777);
129 }
130
131 /** 
132  * Thread for execution of remote requests for a FORB object.
133  * 
134  * @param arg 
135  * 
136  * @return 
137  */
138 static void *
139 forb_execution_thread(void *arg)
140 {
141         forb_orb orb = arg;
142
143         forb_execute_object(orb);
144         return NULL;
145 }
146
147 forb_orb
148 forb_init(int *argc, char **argv[], const char *orb_id)
149 {
150         forb_orb orb;
151         forb_t *forb;
152         int ret;
153
154         forb = forb_malloc(sizeof(*forb));
155         if (!forb) goto err;
156         memset(forb, 0, sizeof(*forb));
157
158         /* Initialize ULUT logging facility */
159         ul_logreg_domains_static(ul_log_domains_array,
160                                  sizeof(ul_log_domains_array)/sizeof(ul_log_domains_array[0]));
161         
162         forb_server_id_init(&forb->server_id);
163         forb_server_id_to_string(forb->server_id_str, &forb->server_id,
164                                  sizeof(forb->server_id_str));
165         ul_logdeb("Initializing forb %s\n", forb->server_id_str);
166
167         if (fosa_mutex_init(&forb->request_id_mutex, 0) != 0) goto err2;
168         if (fosa_mutex_init(&forb->port_mutex, 0) != 0) goto err2;
169         forb_port_init_head(forb);
170         
171         if (fosa_mutex_init(&forb->request_mutex, 0) != 0) goto err2;
172         forb_request_nolock_init_root_field(forb);
173         
174         if (fosa_mutex_init(&forb->peer_mutex, 0) != 0) goto err2;
175         forb_peer_nolock_init_root_field(forb);
176
177         if (fosa_mutex_init(&forb->objkey_mutex, 0) != 0) goto err2;
178         forb_objects_nolock_init_root_field(forb);
179
180         if (fosa_mutex_init(&forb->regref_mutex, 0) != 0) goto err2;
181         forb_regref_nolock_init_root_field(forb);
182
183         ret = forb_init_tmp_dir();
184         if (ret != 0) {
185                 ul_logerr("Cannot prepare " FORB_TMP_DIR "\n");
186                 return NULL;
187         }
188
189         orb = forb_forb_orb_new(NULL, &forb_implementation, forb);
190         if (!orb) goto err2;
191         /* Server ID must be assigned manualy */
192         orb->server = forb->server_id;
193
194         /* Insert our object reference to objects tree, so that we
195          * can accept remote request to our new ORB. */
196         forb_objects_nolock_insert(forb, orb);
197
198         ret = fosa_thread_create(&forb->execution_thread, NULL,
199                                  forb_execution_thread, orb);
200         if (ret != 0)
201                 goto err2;
202         
203         on_exit(destroy_forb_on_exit, orb);
204
205 #ifdef CONFIG_FORB_PROTO_UNIX
206         {
207                 forb_port_t *port = forb_malloc(sizeof(*port));
208                 if (port) {
209                         forb_unix_port_init(port, &forb->server_id);
210                         forb_register_port(forb, port);
211                 }
212         }
213 #endif
214         return orb;
215
216 err2:   forb_free(forb);
217 err:    return NULL;
218 }
219
220 /* FIXME: forb_destroy is now called automatically on exit. Therefore
221  * forb_destroy() should be either static or should deregister on_exit
222  * handler (how???).  */
223 void forb_destroy(forb_orb orb)
224 {
225         forb_t *forb = forb_object_to_forb(orb);
226         forb_port_t *port;
227         forb_regref_t *regref;
228
229         pthread_cancel(forb->execution_thread.pthread_id);
230         pthread_join(forb->execution_thread.pthread_id, NULL);
231         
232         /* Unregister all registered references */
233         while ((regref = forb_regref_first(forb))) {
234                 forb_unregister_reference(orb, regref->name);
235         }
236         
237         ul_list_for_each_cut(forb_port, forb, port) {
238                 forb_destroy_port(port);
239         }
240         forb_object_release(orb);
241         forb_free(forb);
242 }
243
244 /* void */
245 /* forb_register_interface(const struct forb_interface *interface) */
246 /* { */
247 /*      gavl_insert(&type_registry, &interface->node); */
248 /* } */
249
250 /** 
251  * Initializes server ID variable.
252  * 
253  * @param server_id Serer ID to initialize.
254  */
255 void
256 forb_server_id_init(forb_server_id *server_id)
257 {
258         forb_uuid_generate((forb_uuid_t*)server_id->uuid);
259 }
260
261 /** 
262  * 
263  * 
264  * @param fd 
265  * @param objref 
266  * 
267  * @return Zero on success, -1 on error.
268  */
269 static int
270 rewrite_regref(int fd, const char *objref)
271 {
272         int ret;
273         int len = strlen(objref);
274         lseek(fd, 0, SEEK_SET);
275         ftruncate(fd, 0);
276                 
277         while (len > 0) {
278                 ret = write(fd, objref, len);
279                 if (ret < 0) goto out;
280                 len -= ret;
281                 objref += ret;
282         }
283         ret = 0;        /* Success */
284 out:
285         return ret;
286 }
287
288 /** 
289  * 
290  * 
291  * @param orb 
292  * @param fn File name
293  * @param objref string form of the object reference
294  * 
295  * @return -1 on error, 0 if reference was replaced and 1 in the
296  * reference is valid.
297  */
298 static int
299 replace_regref_if_stale(forb_orb orb, const char *fn, const char *objref)
300 {
301         int fd, ret = 0; 
302         char str[100];
303         forb_object object;
304         forb_orb remote_orb;
305         CORBA_Environment env;
306         
307         fd = open(fn, O_RDWR);
308         if (fd < 0) {
309                 ret = -1;
310                 goto out;
311         }
312         ret = lockf(fd, F_LOCK, 0);
313         if (ret < 0) goto close_err;
314         ret = read(fd, str, sizeof(str)-1);
315         if (ret < 0) goto unlock_err;
316         /* TODO: Check that we have read the whole file */
317         
318         str[ret] = '\0';
319         object = forb_string_to_object(orb, str);
320         if (!object) {
321                 /* reference is unreadable, so we can replace it */
322                 ret = rewrite_regref(fd, objref);
323                 /* We are done for now */
324                 goto unlock_err;
325         }
326         remote_orb = forb_get_orb_of(object);
327         if (!remote_orb) {      /* This shohuld never happen */
328                 ret = -1;
329                 goto object_release_err;
330         }
331         forb_orb_is_alive(remote_orb, &env);
332         if (env.major == FORB_EX_COMM_FAILURE) {
333                 /* Orb is not alive */
334                 rewrite_regref(fd, objref);
335         } else {
336                 if (forb_exception_occured(&env)) {
337                         ul_logerr("%s: unexpected exception: %s\n", __FUNCTION__, forb_strerror(&env));
338                 }
339                 /* Reference's FORB is alive :-( */
340                 ret = 1;        
341         }
342
343         forb_object_release(remote_orb);
344 object_release_err:
345         forb_object_release(object);
346 unlock_err:     
347         lockf(fd, F_ULOCK, 0);
348 close_err:
349         close(fd);
350 out:
351         return ret;
352 }
353
354
355 /** 
356  * Registers a given object reference so that other FORBs on the same
357  * node can find it by using forb_resolve_reference().
358  * 
359  * @param object Object reference to register.
360  * @param name Name under which to register the reference.
361  *
362  * @return Zero on success, -1 on error.
363  */
364 int
365 forb_register_reference(forb_object object, const char *name)
366 {
367         forb_regref_t *regref;
368         forb_regref_name_t regname;
369         forb_t *forb = forb_object_to_forb(object);
370         char fn[100], fntmp[100];
371         char *objref;
372         FILE *f;
373         int ret;
374
375         strncpy(regname, name, FORB_REGREF_NAME_LEN-1);
376         regname[FORB_REGREF_NAME_LEN-1]='\0';
377
378         regref = forb_regref_new(object, regname);
379         if (!regref) goto err;
380
381         forb_regref_insert(forb, regref);
382
383         snprintf(fn,    sizeof(fn),    FORB_TMP_DIR "/%s",    regname);
384         snprintf(fntmp, sizeof(fntmp), FORB_TMP_DIR "/%s.%s", regname,
385                  forb->server_id_str);
386
387         f = fopen(fntmp, "w");
388         if (!f) goto unalloc_err;
389         
390         objref = forb_object_to_string(object);
391         if (!objref) goto unlink_err;
392
393         ret = fprintf(f, "%s", objref);
394         if (ret < 0) goto free_objref_err;
395
396         ret = fclose(f);
397         if (ret == EOF) goto free_objref_err;
398
399         /* Make the atomic registration in filesystem */
400         ret = link(fntmp, fn);
401         
402         if (ret < 0 && errno == EEXIST) {
403                 /* The reference exists. Try whether it is still
404                  * active. */
405                 if (replace_regref_if_stale(object->orb, fn, objref) != 0) {
406                         goto free_objref_err;
407                 }
408                 ul_logdeb("Stale registration replaced\n");
409         } else if (ret < 0) {
410                 goto free_objref_err;
411         }
412
413         forb_free(objref);
414
415         /* Unlink the temporary filename */
416         unlink(fntmp);
417         
418         return 0;
419 free_objref_err:
420         ret = errno;
421         forb_free(objref);
422         errno = ret;
423 unlink_err:
424         ret = errno;
425         unlink(fntmp);
426         errno = ret;
427 unalloc_err:
428         ret = errno;
429         forb_regref_delete(forb, regref);
430         forb_regref_release(regref);
431         errno = ret;
432 err:
433         return -1;
434 }
435
436 /** 
437  * Unregister reference previously registered by
438  * forb_register_reference().
439  * 
440  * @param orb forb::orb reference
441  * @param name Name to unregister.
442  * 
443  * @return Zero on success, -1 on error.
444  */
445 int
446 forb_unregister_reference(forb_orb orb, const char *name)
447 {
448         forb_regref_t *regref;
449         forb_regref_name_t regname;
450         forb_t *forb = forb_object_to_forb(orb);
451         char fn[100];
452
453         strncpy(regname, name, FORB_REGREF_NAME_LEN-1);
454         regname[FORB_REGREF_NAME_LEN-1]='\0';
455
456         regref = forb_regref_find(forb, &regname);
457         if (!regref) goto err;
458
459         forb_regref_delete(forb, regref);
460         forb_regref_release(regref);
461
462         snprintf(fn,    sizeof(fn),    FORB_TMP_DIR "/%s",    regname);
463         return unlink(fn);
464
465         return 0;
466 err:
467         return -1;
468 }
469
470 /** 
471  * Returns a named reference previously registered by
472  * forb_register_reference(). This function can be called event if the
473  * reference was registered in a diferent process (but on the same
474  * node).
475  * 
476  * @param orb Local orb object reference
477  * @param name Name under which the reference was registered.
478  * 
479  * @return Object reference on NULL in case of error.
480  */
481 forb_object
482 forb_resolve_reference(const forb_orb orb, const char *name)
483 {
484         forb_regref_name_t regname;
485         char fn[100];
486         char str[100];
487         int fd, ret;
488         forb_object object;
489
490         strncpy(regname, name, FORB_REGREF_NAME_LEN-1);
491         regname[FORB_REGREF_NAME_LEN-1]='\0';
492
493         snprintf(fn,    sizeof(fn),    FORB_TMP_DIR "/%s",    regname);
494
495         fd = open(fn, 0);
496         if (fd < 0) {
497                 return NULL;
498         }
499         ret = read(fd, str, sizeof(str)-1);
500         /* TODO: Check that we have read the whole file */
501         str[ret] = '\0';
502         object = forb_string_to_object(orb, str);
503         close(fd);
504         
505         return object;
506 }
507
508 /** 
509  * Returns object reference of forb::orb object associated with a
510  * given object.
511  * 
512  * @param obj 
513  * 
514  * @return 
515  */
516 forb_orb
517 forb_get_orb_of(const forb_object obj)
518 {
519         forb_orb orb;
520
521         if (forb_server_id_cmp(&obj->server, &obj->orb->server) == 0) {
522                 orb = forb_object_duplicate(orb);
523         } else {
524                 orb = forb_object_new(obj->orb, &obj->server, 0);
525         }
526         return orb;
527 }
528
529 /** 
530  * Returns server ID of an object reference.
531  * 
532  * @param obj 
533  * @param dest 
534  */
535 void
536 forb_get_server_id(const forb_object obj, forb_server_id *dest)
537 {
538         if (obj) {
539                 *dest = obj->server;
540         }
541 }
542
543
544 /** 
545  * Return instance data registered when the object was created by
546  * forb_XXX_new().
547  * 
548  * @param obj Object reference
549  * 
550  * @return Pointer to the registered data.
551  */
552 void *
553 forb_instance_data(const forb_object obj)
554 {
555         return forb_object_instance_data(obj);
556 }
557
558 /** 
559  * Returns error message correspondings FORB exception.
560  * 
561  * @param env Environemnt
562  * 
563  * @return Non-NULL pointer to a string.
564  */
565 const char *
566 forb_strerror(CORBA_Environment *env)
567 {
568         if (!env) {
569                 return "Invalid environemnt";
570         }
571 #define ex(e) case FORB_EX_##e: return #e; break;
572         switch (env->major) {
573         ex(NONE);
574         ex(UNKNOWN);
575         ex(BAD_PARAM);
576         ex(NO_MEMORY);
577         ex(IMP_LIMIT);
578         ex(COMM_FAILURE);
579         ex(INV_OBJREF);
580         ex(NO_PERMISSION);
581         ex(INTERNAL);
582         ex(MARSHAL);
583         ex(INITIALIZE);
584         ex(NO_IMPLEMENT);
585         ex(BAD_OPERATION);
586         ex(NO_RESOURCES);
587         ex(NO_RESPONSE);
588         ex(TRANSIENT);
589         ex(FREE_MEM);
590         ex(INV_IDENT);
591         ex(INV_FLAG);
592         ex(DATA_CONVERSION);
593         ex(OBJECT_NOT_EXIST);
594         ex(TIMEOUT);
595         }
596 #undef ex
597         return "Invalid error number";
598 }