Logo AND Algorithmique Numérique Distribuée

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