Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Avoid a useless bprintf (and test whether NULL msg exceptions are ok)
[simgrid.git] / src / gras / Transport / transport.c
1 /* $Id$ */
2
3 /* transport - low level communication                                      */
4
5 /* Copyright (c) 2004 Martin Quinson. All rights reserved.                  */
6
7 /* This program is free software; you can redistribute it and/or modify it
8  * under the terms of the license (GNU LGPL) which comes with this package. */
9
10 #include "xbt/ex.h"
11 #include "portable.h"
12 #include "gras/Transport/transport_private.h"
13
14 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(transport,gras,"Conveying bytes over the network");
15 XBT_LOG_NEW_SUBCATEGORY(trp_meas,transport,"Conveying bytes over the network without formating for perf measurements");
16 static short int _gras_trp_started = 0;
17
18 static xbt_dict_t _gras_trp_plugins;      /* All registered plugins */
19 static void gras_trp_plugin_free(void *p); /* free one of the plugins */
20
21 static void
22 gras_trp_plugin_new(const char *name, gras_trp_setup_t setup) {
23   xbt_ex_t e;
24
25   gras_trp_plugin_t plug = xbt_new0(s_gras_trp_plugin_t, 1);
26   
27   DEBUG1("Create plugin %s",name);
28
29   plug->name=xbt_strdup(name);
30
31   TRY {
32     setup(plug);
33   } CATCH(e) {
34     if (e.category == mismatch_error) {
35       /* SG plugin raise mismatch when in RL mode (and vice versa) */
36       free(plug->name);
37       free(plug);
38       plug=NULL;
39       xbt_ex_free(e);
40     } else {
41       RETHROW;
42     }
43   }
44
45   if (plug)
46     xbt_dict_set(_gras_trp_plugins, name, plug, gras_trp_plugin_free);
47 }
48
49 void gras_trp_init(void){
50   if (!_gras_trp_started) {
51      /* make room for all plugins */
52      _gras_trp_plugins=xbt_dict_new();
53
54 #ifdef HAVE_WINSOCK2_H
55      /* initialize the windows mechanism */
56      {  
57         WORD wVersionRequested;
58         WSADATA wsaData;
59         
60         wVersionRequested = MAKEWORD( 2, 0 );
61         xbt_assert0(WSAStartup( wVersionRequested, &wsaData ) == 0,
62                     "Cannot find a usable WinSock DLL");
63         
64         /* Confirm that the WinSock DLL supports 2.0.*/
65         /* Note that if the DLL supports versions greater    */
66         /* than 2.0 in addition to 2.0, it will still return */
67         /* 2.0 in wVersion since that is the version we      */
68         /* requested.                                        */
69         
70         xbt_assert0(LOBYTE( wsaData.wVersion ) == 2 &&
71                     HIBYTE( wsaData.wVersion ) == 0,
72                     "Cannot find a usable WinSock DLL");
73         INFO0("Found and initialized winsock2");
74      }       /* The WinSock DLL is acceptable. Proceed. */
75 #elif HAVE_WINSOCK_H
76      {       WSADATA wsaData;
77         xbt_assert0(WSAStartup( 0x0101, &wsaData ) == 0,
78                     "Cannot find a usable WinSock DLL");
79         INFO0("Found and initialized winsock");
80      }
81 #endif
82    
83      /* Add plugins */
84      gras_trp_plugin_new("tcp", gras_trp_tcp_setup);
85      gras_trp_plugin_new("file",gras_trp_file_setup);
86      gras_trp_plugin_new("sg",gras_trp_sg_setup);
87
88      /* buf is composed, so it must come after the others */
89      gras_trp_plugin_new("buf", gras_trp_buf_setup);
90   }
91    
92   _gras_trp_started++;
93 }
94
95 void
96 gras_trp_exit(void){
97   xbt_dynar_t sockets = gras_socketset_get();
98   gras_socket_t sock_iter;
99   int cursor;
100
101    if (_gras_trp_started == 0) {
102       return;
103    }
104    
105    if ( --_gras_trp_started == 0 ) {
106 #ifdef HAVE_WINSOCK_H
107       if ( WSACleanup() == SOCKET_ERROR ) {
108          if ( WSAGetLastError() == WSAEINPROGRESS ) {
109             WSACancelBlockingCall();
110             WSACleanup();
111          }
112         }
113 #endif
114
115       /* Close all the sockets */
116       xbt_dynar_foreach(sockets,cursor,sock_iter) {
117         VERB1("Closing the socket %p left open on exit. Maybe a socket leak?",
118               sock_iter);
119         gras_socket_close(sock_iter);
120       }
121       
122       /* Delete the plugins */
123       xbt_dict_free(&_gras_trp_plugins);
124    }
125 }
126
127
128 void gras_trp_plugin_free(void *p) {
129   gras_trp_plugin_t plug = p;
130
131   if (plug) {
132     if (plug->exit) {
133       plug->exit(plug);
134     } else if (plug->data) {
135       DEBUG1("Plugin %s lacks exit(). Free data anyway.",plug->name);
136       free(plug->data);
137     }
138
139     free(plug->name);
140     free(plug);
141   }
142 }
143
144
145 /**
146  * gras_trp_socket_new:
147  *
148  * Malloc a new socket, and initialize it with defaults
149  */
150 void gras_trp_socket_new(int incoming,
151                          gras_socket_t *dst) {
152
153   gras_socket_t sock=xbt_new0(s_gras_socket_t,1);
154
155   DEBUG1("Create a new socket (%p)", (void*)sock);
156
157   sock->plugin = NULL;
158
159   sock->incoming  = incoming ? 1:0;
160   sock->outgoing  = incoming ? 0:1;
161   sock->accepting = incoming ? 1:0;
162   sock->meas = 0;
163
164   sock->sd     = -1;
165   sock->port      = -1;
166   sock->peer_port = -1;
167   sock->peer_name = NULL;
168
169   sock->data   = NULL;
170   sock->bufdata = NULL;
171   
172   *dst = sock;
173
174   xbt_dynar_push(gras_socketset_get(),dst);
175   XBT_OUT;
176 }
177
178
179 /**
180  * gras_socket_server_ext:
181  *
182  * Opens a server socket and make it ready to be listened to.
183  * In real life, you'll get a TCP socket.
184  */
185 gras_socket_t
186 gras_socket_server_ext(unsigned short port,
187                        
188                        unsigned long int bufSize,
189                        int measurement) {
190  
191   xbt_ex_t e;
192   gras_trp_plugin_t trp;
193   gras_socket_t sock;
194
195   DEBUG2("Create a server socket from plugin %s on port %d",
196          gras_if_RL() ? "tcp" : "sg",
197          port);
198   trp = gras_trp_plugin_get_by_name((measurement? (gras_if_RL() ? "tcp" : "sg")
199                                                 :"buf"));
200
201   /* defaults settings */
202   gras_trp_socket_new(1,&sock);
203   sock->plugin= trp;
204   sock->port=port;
205   sock->bufSize = bufSize;
206   sock->meas = measurement;
207
208   /* Call plugin socket creation function */
209   DEBUG1("Prepare socket with plugin (fct=%p)",trp->socket_server);
210   TRY {
211     trp->socket_server(trp, sock);
212     DEBUG3("in=%c out=%c accept=%c",
213            sock->incoming?'y':'n', 
214            sock->outgoing?'y':'n',
215            sock->accepting?'y':'n');
216   } CATCH(e) {
217     free(sock);
218     RETHROW;
219   }
220
221   return sock;
222 }
223    
224 /**
225  * gras_socket_client_ext:
226  *
227  * Opens a client socket to a remote host.
228  * In real life, you'll get a TCP socket.
229  */
230 gras_socket_t
231 gras_socket_client_ext(const char *host,
232                        unsigned short port,
233                        
234                        unsigned long int bufSize,
235                        int measurement) {
236  
237   xbt_ex_t e;
238   gras_trp_plugin_t trp;
239   gras_socket_t sock;
240
241   trp = gras_trp_plugin_get_by_name((measurement? (gras_if_RL() ? "tcp" : "sg")
242                                                 : "buf"));
243
244   DEBUG1("Create a client socket from plugin %s",gras_if_RL() ? "tcp" : "sg");
245   /* defaults settings */
246   gras_trp_socket_new(0,&sock);
247   sock->plugin= trp;
248   sock->peer_port = port;
249   sock->peer_name = (char*)strdup(host?host:"localhost");
250   sock->bufSize = bufSize;
251   sock->meas = measurement;
252
253   /* plugin-specific */
254   TRY {
255     (*trp->socket_client)(trp, sock);
256     DEBUG3("in=%c out=%c accept=%c",
257            sock->incoming?'y':'n', 
258            sock->outgoing?'y':'n',
259            sock->accepting?'y':'n');
260   } CATCH(e) {
261     free(sock);
262     RETHROW;
263   }
264
265   return sock;
266 }
267
268 /**
269  * gras_socket_server:
270  *
271  * Opens a server socket and make it ready to be listened to.
272  * In real life, you'll get a TCP socket.
273  */
274 gras_socket_t
275 gras_socket_server(unsigned short port) {
276    return gras_socket_server_ext(port,32,0);
277 }
278
279 /**
280  * gras_socket_client:
281  *
282  * Opens a client socket to a remote host.
283  * In real life, you'll get a TCP socket.
284  */
285 gras_socket_t
286 gras_socket_client(const char *host,
287                    unsigned short port) {
288    return gras_socket_client_ext(host,port,32,0);
289 }
290
291
292 void gras_socket_close(gras_socket_t sock) {
293   xbt_dynar_t sockets = gras_socketset_get();
294   gras_socket_t sock_iter;
295   int cursor;
296
297   XBT_IN;
298   /* FIXME: Issue an event when the socket is closed */
299   if (sock) {
300     xbt_dynar_foreach(sockets,cursor,sock_iter) {
301       if (sock == sock_iter) {
302         xbt_dynar_cursor_rm(sockets,&cursor);
303         if (sock->plugin->socket_close) 
304           (* sock->plugin->socket_close)(sock);
305
306         /* free the memory */
307         if (sock->peer_name)
308           free(sock->peer_name);
309         free(sock);
310         XBT_OUT;
311         return;
312       }
313     }
314     WARN1("Ignoring request to free an unknown socket (%p)",sock);
315   }
316   XBT_OUT;
317 }
318
319 /**
320  * gras_trp_chunk_send:
321  *
322  * Send a bunch of bytes from on socket
323  */
324 void
325 gras_trp_chunk_send(gras_socket_t sd,
326                     char *data,
327                     long int size) {
328   xbt_assert1(sd->outgoing,
329                "Socket not suited for data send (outgoing=%c)",
330                sd->outgoing?'y':'n');
331   xbt_assert1(sd->plugin->chunk_send,
332                "No function chunk_send on transport plugin %s",
333                sd->plugin->name);
334   (*sd->plugin->chunk_send)(sd,data,size);
335 }
336 /**
337  * gras_trp_chunk_recv:
338  *
339  * Receive a bunch of bytes from a socket
340  */
341 void
342 gras_trp_chunk_recv(gras_socket_t sd,
343                     char *data,
344                     long int size) {
345   xbt_assert0(sd->incoming,
346                "Socket not suited for data receive");
347   xbt_assert1(sd->plugin->chunk_recv,
348                "No function chunk_recv on transport plugin %s",
349                sd->plugin->name);
350   (sd->plugin->chunk_recv)(sd,data,size);
351 }
352
353 /**
354  * gras_trp_flush:
355  *
356  * Make sure all pending communications are done
357  */
358 void
359 gras_trp_flush(gras_socket_t sd) {
360   (sd->plugin->flush)(sd);
361 }
362
363 gras_trp_plugin_t
364 gras_trp_plugin_get_by_name(const char *name){
365   return xbt_dict_get(_gras_trp_plugins,name);
366 }
367
368 int   gras_socket_my_port  (gras_socket_t sock) {
369   return sock->port;
370 }
371 int   gras_socket_peer_port(gras_socket_t sock) {
372   return sock->peer_port;
373 }
374 char *gras_socket_peer_name(gras_socket_t sock) {
375   return sock->peer_name;
376 }
377
378 /** \brief Check if the provided socket is a measurement one (or a regular one) */
379 int gras_socket_is_meas(gras_socket_t sock) {
380   return sock->meas;
381 }
382
383 /** \brief Send a chunk of (random) data over a measurement socket 
384  *
385  * @param peer measurement socket to use for the experiment
386  * @param timeout timeout (in seconds)
387  * @param exp_size total amount of data to send (in bytes).
388  * @param msg_size size of each chunk sent over the socket (in bytes).
389  *
390  * Calls to gras_socket_meas_send() and gras_socket_meas_recv() on 
391  * each side of the socket should be paired. 
392  * 
393  * The exchanged data is zeroed to make sure it's initialized, but
394  * there is no way to control what is sent (ie, you cannot use these 
395  * functions to exchange data out of band).
396  */
397 void gras_socket_meas_send(gras_socket_t peer, 
398                            unsigned int timeout,
399                            unsigned long int exp_size, 
400                            unsigned long int msg_size) {
401   char *chunk = xbt_malloc0(msg_size);
402   unsigned long int exp_sofar;
403    
404   XBT_IN;
405
406   xbt_assert0(peer->meas,"Asked to send measurement data on a regular socket");
407
408   for (exp_sofar=0; exp_sofar < exp_size; exp_sofar += msg_size) {
409      CDEBUG5(trp_meas,"Sent %lu of %lu (msg_size=%ld) to %s:%d",
410              exp_sofar,exp_size,msg_size,
411              gras_socket_peer_name(peer), gras_socket_peer_port(peer));
412      gras_trp_chunk_send(peer,chunk,msg_size);
413   }
414   CDEBUG5(trp_meas,"Sent %lu of %lu (msg_size=%ld) to %s:%d",
415           exp_sofar,exp_size,msg_size,
416           gras_socket_peer_name(peer), gras_socket_peer_port(peer));
417              
418   free(chunk);
419
420   XBT_OUT;
421 }
422
423 /** \brief Receive a chunk of data over a measurement socket 
424  *
425  * Calls to gras_socket_meas_send() and gras_socket_meas_recv() on 
426  * each side of the socket should be paired. 
427  */
428 void gras_socket_meas_recv(gras_socket_t peer, 
429                            unsigned int timeout,
430                            unsigned long int exp_size, 
431                            unsigned long int msg_size){
432   
433   char *chunk = xbt_malloc(msg_size);
434   unsigned long int exp_sofar;
435
436   XBT_IN;
437
438   xbt_assert0(peer->meas,"Asked to receive measurement data on a regular socket\n");
439
440   for (exp_sofar=0; exp_sofar < exp_size; exp_sofar += msg_size) {
441      CDEBUG5(trp_meas,"Recvd %ld of %lu (msg_size=%ld) from %s:%d",
442              exp_sofar,exp_size,msg_size,
443              gras_socket_peer_name(peer), gras_socket_peer_port(peer));
444      gras_trp_chunk_recv(peer,chunk,msg_size);
445   }
446   CDEBUG5(trp_meas,"Recvd %ld of %lu (msg_size=%ld) from %s:%d",
447           exp_sofar,exp_size,msg_size,
448           gras_socket_peer_name(peer), gras_socket_peer_port(peer));
449
450   free(chunk);
451   XBT_OUT;
452 }
453
454 /**
455  * \brief Something similar to the good old accept system call. 
456  *
457  * Make sure that there is someone speaking to the provided server socket.
458  * In RL, it does an accept(2) and return the result as last argument. 
459  * In SG, as accepts are useless, it returns the provided argument as result.
460  * You should thus test whether (peer != accepted) before closing both of them.
461  *
462  * You should only call this on measurement sockets. It is automatically 
463  * done for regular sockets, but you usually want more control about 
464  * what's going on with measurement sockets.
465  */
466 gras_socket_t gras_socket_meas_accept(gras_socket_t peer){
467   gras_socket_t res;
468
469   xbt_assert0(peer->meas,
470               "No need to accept on non-measurement sockets (it's automatic)");
471
472   if (!peer->accepting) {
473     /* nothing to accept here */
474     return peer;
475   }
476
477   res = (peer->plugin->socket_accept)(peer);
478   res->meas = peer->meas;
479   CDEBUG1(trp_meas,"meas_accepted onto %d",res->sd);
480
481   return res;
482
483
484
485 /*
486  * Creating procdata for this module
487  */
488 static void *gras_trp_procdata_new() {
489    gras_trp_procdata_t res = xbt_new(s_gras_trp_procdata_t,1);
490    
491    res->sockets   = xbt_dynar_new(sizeof(gras_socket_t*), NULL);
492    
493    return (void*)res;
494 }
495
496 /*
497  * Freeing procdata for this module
498  */
499 static void gras_trp_procdata_free(void *data) {
500    gras_trp_procdata_t res = (gras_trp_procdata_t)data;
501    
502    xbt_dynar_free(&( res->sockets ));
503    free(res);
504 }
505
506 /*
507  * Module registration
508  */
509 void gras_trp_register() {
510    gras_procdata_add("gras_trp",gras_trp_procdata_new, gras_trp_procdata_free);
511 }
512
513
514 xbt_dynar_t 
515 gras_socketset_get(void) {
516    /* FIXME: KILLME */
517    return ((gras_trp_procdata_t) gras_libdata_get("gras_trp"))->sockets;
518 }