Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
6417ea3ebdb99d4887983b734f900c1430ab69a4
[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       xbt_ex_free(e);
39     } else {
40       RETHROW;
41     }
42   }
43
44   xbt_dict_set(_gras_trp_plugins, name, plug, gras_trp_plugin_free);
45 }
46
47 void gras_trp_init(void){
48   if (!_gras_trp_started) {
49      /* make room for all plugins */
50      _gras_trp_plugins=xbt_dict_new();
51
52 #ifdef HAVE_WINSOCK2_H
53      /* initialize the windows mechanism */
54      {  
55         WORD wVersionRequested;
56         WSADATA wsaData;
57         
58         wVersionRequested = MAKEWORD( 2, 0 );
59         xbt_assert0(WSAStartup( wVersionRequested, &wsaData ) == 0,
60                     "Cannot find a usable WinSock DLL");
61         
62         /* Confirm that the WinSock DLL supports 2.0.*/
63         /* Note that if the DLL supports versions greater    */
64         /* than 2.0 in addition to 2.0, it will still return */
65         /* 2.0 in wVersion since that is the version we      */
66         /* requested.                                        */
67         
68         xbt_assert0(LOBYTE( wsaData.wVersion ) == 2 &&
69                     HIBYTE( wsaData.wVersion ) == 0,
70                     "Cannot find a usable WinSock DLL");
71         INFO0("Found and initialized winsock2");
72      }       /* The WinSock DLL is acceptable. Proceed. */
73 #elif HAVE_WINSOCK_H
74      {       WSADATA wsaData;
75         xbt_assert0(WSAStartup( 0x0101, &wsaData ) == 0,
76                     "Cannot find a usable WinSock DLL");
77         INFO0("Found and initialized winsock");
78      }
79 #endif
80    
81      /* Add plugins */
82      gras_trp_plugin_new("tcp", gras_trp_tcp_setup);
83      gras_trp_plugin_new("file",gras_trp_file_setup);
84      gras_trp_plugin_new("sg",gras_trp_sg_setup);
85
86      /* buf is composed, so it must come after the others */
87      gras_trp_plugin_new("buf", gras_trp_buf_setup);
88   }
89    
90   _gras_trp_started++;
91 }
92
93 void
94 gras_trp_exit(void){
95   xbt_dynar_t sockets = gras_socketset_get();
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
167   sock->data   = NULL;
168   sock->bufdata = NULL;
169   
170   *dst = sock;
171
172   xbt_dynar_push(gras_socketset_get(),dst);
173   XBT_OUT;
174 }
175
176
177 /**
178  * gras_socket_server_ext:
179  *
180  * Opens a server socket and make it ready to be listened to.
181  * In real life, you'll get a TCP socket.
182  */
183 gras_socket_t
184 gras_socket_server_ext(unsigned short port,
185                        
186                        unsigned long int bufSize,
187                        int measurement) {
188  
189   xbt_ex_t e;
190   gras_trp_plugin_t trp;
191   gras_socket_t sock;
192
193   DEBUG2("Create a server socket from plugin %s on port %d",
194          gras_if_RL() ? "tcp" : "sg",
195          port);
196   trp = gras_trp_plugin_get_by_name((measurement? (gras_if_RL() ? "tcp" : "sg")
197                                                 :"buf"));
198
199   /* defaults settings */
200   gras_trp_socket_new(1,&sock);
201   sock->plugin= trp;
202   sock->port=port;
203   sock->bufSize = bufSize;
204   sock->meas = measurement;
205
206   /* Call plugin socket creation function */
207   DEBUG1("Prepare socket with plugin (fct=%p)",trp->socket_server);
208   TRY {
209     trp->socket_server(trp, sock);
210     DEBUG3("in=%c out=%c accept=%c",
211            sock->incoming?'y':'n', 
212            sock->outgoing?'y':'n',
213            sock->accepting?'y':'n');
214   } CATCH(e) {
215     free(sock);
216     RETHROW;
217   }
218
219   return sock;
220 }
221    
222 /**
223  * gras_socket_client_ext:
224  *
225  * Opens a client socket to a remote host.
226  * In real life, you'll get a TCP socket.
227  */
228 gras_socket_t
229 gras_socket_client_ext(const char *host,
230                        unsigned short port,
231                        
232                        unsigned long int bufSize,
233                        int measurement) {
234  
235   xbt_ex_t e;
236   gras_trp_plugin_t trp;
237   gras_socket_t sock;
238
239   trp = gras_trp_plugin_get_by_name((measurement? (gras_if_RL() ? "tcp" : "sg")
240                                                 : "buf"));
241
242   DEBUG1("Create a client socket from plugin %s",gras_if_RL() ? "tcp" : "sg");
243   /* defaults settings */
244   gras_trp_socket_new(0,&sock);
245   sock->plugin= trp;
246   sock->peer_port = port;
247   sock->peer_name = (char*)strdup(host?host:"localhost");
248   sock->bufSize = bufSize;
249   sock->meas = measurement;
250
251   /* plugin-specific */
252   TRY {
253     (*trp->socket_client)(trp, sock);
254     DEBUG3("in=%c out=%c accept=%c",
255            sock->incoming?'y':'n', 
256            sock->outgoing?'y':'n',
257            sock->accepting?'y':'n');
258   } CATCH(e) {
259     free(sock);
260     RETHROW;
261   }
262
263   return sock;
264 }
265
266 /**
267  * gras_socket_server:
268  *
269  * Opens a server socket and make it ready to be listened to.
270  * In real life, you'll get a TCP socket.
271  */
272 gras_socket_t
273 gras_socket_server(unsigned short port) {
274    return gras_socket_server_ext(port,32,0);
275 }
276
277 /**
278  * gras_socket_client:
279  *
280  * Opens a client socket to a remote host.
281  * In real life, you'll get a TCP socket.
282  */
283 gras_socket_t
284 gras_socket_client(const char *host,
285                    unsigned short port) {
286    return gras_socket_client_ext(host,port,32,0);
287 }
288
289
290 void gras_socket_close(gras_socket_t sock) {
291   xbt_dynar_t sockets = gras_socketset_get();
292   gras_socket_t sock_iter;
293   int cursor;
294
295   XBT_IN;
296   /* FIXME: Issue an event when the socket is closed */
297   if (sock) {
298     xbt_dynar_foreach(sockets,cursor,sock_iter) {
299       if (sock == sock_iter) {
300         xbt_dynar_cursor_rm(sockets,&cursor);
301         if (sock->plugin->socket_close) 
302           (* sock->plugin->socket_close)(sock);
303
304         /* free the memory */
305         if (sock->peer_name)
306           free(sock->peer_name);
307         free(sock);
308         XBT_OUT;
309         return;
310       }
311     }
312     WARN1("Ignoring request to free an unknown socket (%p)",sock);
313   }
314   XBT_OUT;
315 }
316
317 /**
318  * gras_trp_chunk_send:
319  *
320  * Send a bunch of bytes from on socket
321  */
322 void
323 gras_trp_chunk_send(gras_socket_t sd,
324                     char *data,
325                     long int size) {
326   xbt_assert1(sd->outgoing,
327                "Socket not suited for data send (outgoing=%c)",
328                sd->outgoing?'y':'n');
329   xbt_assert1(sd->plugin->chunk_send,
330                "No function chunk_send on transport plugin %s",
331                sd->plugin->name);
332   (*sd->plugin->chunk_send)(sd,data,size);
333 }
334 /**
335  * gras_trp_chunk_recv:
336  *
337  * Receive a bunch of bytes from a socket
338  */
339 void
340 gras_trp_chunk_recv(gras_socket_t sd,
341                     char *data,
342                     long int size) {
343   xbt_assert0(sd->incoming,
344                "Socket not suited for data receive");
345   xbt_assert1(sd->plugin->chunk_recv,
346                "No function chunk_recv on transport plugin %s",
347                sd->plugin->name);
348   (sd->plugin->chunk_recv)(sd,data,size);
349 }
350
351 /**
352  * gras_trp_flush:
353  *
354  * Make sure all pending communications are done
355  */
356 void
357 gras_trp_flush(gras_socket_t sd) {
358   (sd->plugin->flush)(sd);
359 }
360
361 gras_trp_plugin_t
362 gras_trp_plugin_get_by_name(const char *name){
363   return xbt_dict_get(_gras_trp_plugins,name);
364 }
365
366 int   gras_socket_my_port  (gras_socket_t sock) {
367   return sock->port;
368 }
369 int   gras_socket_peer_port(gras_socket_t sock) {
370   return sock->peer_port;
371 }
372 char *gras_socket_peer_name(gras_socket_t sock) {
373   return sock->peer_name;
374 }
375
376 /** \brief Check if the provided socket is a measurement one (or a regular one) */
377 int gras_socket_is_meas(gras_socket_t sock) {
378   return sock->meas;
379 }
380
381 /** \brief Send a chunk of (random) data over a measurement socket 
382  *
383  * @param peer measurement socket to use for the experiment
384  * @param timeout timeout (in seconds)
385  * @param exp_size total amount of data to send (in bytes).
386  * @param msg_size size of each chunk sent over the socket (in bytes).
387  *
388  * Calls to gras_socket_meas_send() and gras_socket_meas_recv() on 
389  * each side of the socket should be paired. 
390  * 
391  * The exchanged data is zeroed to make sure it's initialized, but
392  * there is no way to control what is sent (ie, you cannot use these 
393  * functions to exchange data out of band).
394  */
395 void gras_socket_meas_send(gras_socket_t peer, 
396                            unsigned int timeout,
397                            unsigned long int exp_size, 
398                            unsigned long int msg_size) {
399   char *chunk = xbt_malloc0(msg_size);
400   unsigned long int exp_sofar;
401    
402   XBT_IN;
403
404   xbt_assert0(peer->meas,"Asked to send measurement data on a regular socket");
405
406   for (exp_sofar=0; exp_sofar < exp_size; exp_sofar += msg_size) {
407      CDEBUG5(trp_meas,"Sent %lu of %lu (msg_size=%ld) to %s:%d",
408              exp_sofar,exp_size,msg_size,
409              gras_socket_peer_name(peer), gras_socket_peer_port(peer));
410      gras_trp_chunk_send(peer,chunk,msg_size);
411   }
412   CDEBUG5(trp_meas,"Sent %lu of %lu (msg_size=%ld) to %s:%d",
413           exp_sofar,exp_size,msg_size,
414           gras_socket_peer_name(peer), gras_socket_peer_port(peer));
415              
416   free(chunk);
417
418   XBT_OUT;
419 }
420
421 /** \brief Receive a chunk of data over a measurement socket 
422  *
423  * Calls to gras_socket_meas_send() and gras_socket_meas_recv() on 
424  * each side of the socket should be paired. 
425  */
426 void gras_socket_meas_recv(gras_socket_t peer, 
427                            unsigned int timeout,
428                            unsigned long int exp_size, 
429                            unsigned long int msg_size){
430   
431   char *chunk = xbt_malloc(msg_size);
432   unsigned long int exp_sofar;
433
434   XBT_IN;
435
436   xbt_assert0(peer->meas,"Asked to receive measurement data on a regular socket\n");
437
438   for (exp_sofar=0; exp_sofar < exp_size; exp_sofar += msg_size) {
439      CDEBUG5(trp_meas,"Recvd %ld of %lu (msg_size=%ld) from %s:%d",
440              exp_sofar,exp_size,msg_size,
441              gras_socket_peer_name(peer), gras_socket_peer_port(peer));
442      gras_trp_chunk_recv(peer,chunk,msg_size);
443   }
444   CDEBUG5(trp_meas,"Recvd %ld of %lu (msg_size=%ld) from %s:%d",
445           exp_sofar,exp_size,msg_size,
446           gras_socket_peer_name(peer), gras_socket_peer_port(peer));
447
448   free(chunk);
449   XBT_OUT;
450 }
451
452 /**
453  * \brief Something similar to the good old accept system call. 
454  *
455  * Make sure that there is someone speaking to the provided server socket.
456  * In RL, it does an accept(2) and return the result as last argument. 
457  * In SG, as accepts are useless, it returns the provided argument as result.
458  * You should thus test whether (peer != accepted) before closing both of them.
459  *
460  * You should only call this on measurement sockets. It is automatically 
461  * done for regular sockets, but you usually want more control about 
462  * what's going on with measurement sockets.
463  */
464 gras_socket_t gras_socket_meas_accept(gras_socket_t peer){
465   gras_socket_t res;
466
467   xbt_assert0(peer->meas,
468               "No need to accept on non-measurement sockets (it's automatic)");
469
470   if (!peer->accepting) {
471     /* nothing to accept here */
472     return peer;
473   }
474
475   res = (peer->plugin->socket_accept)(peer);
476   res->meas = peer->meas;
477   CDEBUG1(trp_meas,"meas_accepted onto %d",res->sd);
478
479   return res;
480
481
482
483 /*
484  * Creating procdata for this module
485  */
486 static void *gras_trp_procdata_new() {
487    gras_trp_procdata_t res = xbt_new(s_gras_trp_procdata_t,1);
488    
489    res->sockets   = xbt_dynar_new(sizeof(gras_socket_t*), NULL);
490    
491    return (void*)res;
492 }
493
494 /*
495  * Freeing procdata for this module
496  */
497 static void gras_trp_procdata_free(void *data) {
498    gras_trp_procdata_t res = (gras_trp_procdata_t)data;
499    
500    xbt_dynar_free(&( res->sockets ));
501    free(res);
502 }
503
504 /*
505  * Module registration
506  */
507 void gras_trp_register() {
508    gras_procdata_add("gras_trp",gras_trp_procdata_new, gras_trp_procdata_free);
509 }
510
511
512 xbt_dynar_t 
513 gras_socketset_get(void) {
514    /* FIXME: KILLME */
515    return ((gras_trp_procdata_t) gras_libdata_get("gras_trp"))->sockets;
516 }