Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
e5684befd60531d789e9bf42358cd1f2197c406a
[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("file",gras_trp_file_setup);
85      gras_trp_plugin_new("sg",gras_trp_sg_setup);
86
87      /* buf is composed, so it must come after the others */
88      gras_trp_plugin_new("buf", gras_trp_buf_setup);
89   }
90    
91   _gras_trp_started++;
92 }
93
94 void
95 gras_trp_exit(void){
96   xbt_dynar_t sockets = gras_socketset_get();
97   gras_socket_t sock_iter;
98   int cursor;
99
100    if (_gras_trp_started == 0) {
101       return;
102    }
103    
104    if ( --_gras_trp_started == 0 ) {
105 #ifdef HAVE_WINSOCK_H
106       if ( WSACleanup() == SOCKET_ERROR ) {
107          if ( WSAGetLastError() == WSAEINPROGRESS ) {
108             WSACancelBlockingCall();
109             WSACleanup();
110          }
111         }
112 #endif
113
114       /* Close all the sockets */
115       xbt_dynar_foreach(sockets,cursor,sock_iter) {
116         VERB1("Closing the socket %p left open on exit. Maybe a socket leak?",
117               sock_iter);
118         gras_socket_close(sock_iter);
119       }
120       
121       /* Delete the plugins */
122       xbt_dict_free(&_gras_trp_plugins);
123    }
124 }
125
126
127 void gras_trp_plugin_free(void *p) {
128   gras_trp_plugin_t plug = p;
129
130   if (plug) {
131     if (plug->exit) {
132       plug->exit(plug);
133     } else if (plug->data) {
134       DEBUG1("Plugin %s lacks exit(). Free data anyway.",plug->name);
135       free(plug->data);
136     }
137
138     free(plug->name);
139     free(plug);
140   }
141 }
142
143
144 /**
145  * gras_trp_socket_new:
146  *
147  * Malloc a new socket, and initialize it with defaults
148  */
149 void gras_trp_socket_new(int incoming,
150                          gras_socket_t *dst) {
151
152   gras_socket_t sock=xbt_new0(s_gras_socket_t,1);
153
154   DEBUG1("Create a new socket (%p)", (void*)sock);
155
156   sock->plugin = NULL;
157
158   sock->incoming  = incoming ? 1:0;
159   sock->outgoing  = incoming ? 0:1;
160   sock->accepting = incoming ? 1:0;
161   sock->meas = 0;
162
163   sock->sd     = -1;
164   sock->port      = -1;
165   sock->peer_port = -1;
166   sock->peer_name = NULL;
167
168   sock->data   = NULL;
169   sock->bufdata = NULL;
170   
171   *dst = sock;
172
173   xbt_dynar_push(gras_socketset_get(),dst);
174   XBT_OUT;
175 }
176
177
178 /**
179  * gras_socket_server_ext:
180  *
181  * Opens a server socket and make it ready to be listened to.
182  * In real life, you'll get a TCP socket.
183  */
184 gras_socket_t
185 gras_socket_server_ext(unsigned short port,
186                        
187                        unsigned long int bufSize,
188                        int measurement) {
189  
190   xbt_ex_t e;
191   gras_trp_plugin_t trp;
192   gras_socket_t sock;
193
194   DEBUG2("Create a server socket from plugin %s on port %d",
195          gras_if_RL() ? "tcp" : "sg",
196          port);
197   trp = gras_trp_plugin_get_by_name(gras_if_SG() ? "sg":(measurement?"tcp":"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(gras_if_SG() ? "sg":(measurement?"tcp":"buf"));
240
241   DEBUG1("Create a client socket from plugin %s",gras_if_RL() ? "tcp" : "sg");
242   /* defaults settings */
243   gras_trp_socket_new(0,&sock);
244   sock->plugin= trp;
245   sock->peer_port = port;
246   sock->peer_name = (char*)strdup(host?host:"localhost");
247   sock->bufSize = bufSize;
248   sock->meas = measurement;
249
250   /* plugin-specific */
251   TRY {
252     (*trp->socket_client)(trp, sock);
253     DEBUG3("in=%c out=%c accept=%c",
254            sock->incoming?'y':'n', 
255            sock->outgoing?'y':'n',
256            sock->accepting?'y':'n');
257   } CATCH(e) {
258     free(sock);
259     RETHROW;
260   }
261
262   return sock;
263 }
264
265 /**
266  * gras_socket_server:
267  *
268  * Opens a server socket and make it ready to be listened to.
269  * In real life, you'll get a TCP socket.
270  */
271 gras_socket_t
272 gras_socket_server(unsigned short port) {
273    return gras_socket_server_ext(port,32,0);
274 }
275
276 /**
277  * gras_socket_client:
278  *
279  * Opens a client socket to a remote host.
280  * In real life, you'll get a TCP socket.
281  */
282 gras_socket_t
283 gras_socket_client(const char *host,
284                    unsigned short port) {
285    return gras_socket_client_ext(host,port,32,0);
286 }
287
288
289 void gras_socket_close(gras_socket_t sock) {
290   xbt_dynar_t sockets = gras_socketset_get();
291   gras_socket_t sock_iter;
292   int cursor;
293
294   XBT_IN;
295   /* FIXME: Issue an event when the socket is closed */
296   if (sock) {
297     xbt_dynar_foreach(sockets,cursor,sock_iter) {
298       if (sock == sock_iter) {
299         xbt_dynar_cursor_rm(sockets,&cursor);
300         if (sock->plugin->socket_close) 
301           (* sock->plugin->socket_close)(sock);
302
303         /* free the memory */
304         if (sock->peer_name)
305           free(sock->peer_name);
306         free(sock);
307         XBT_OUT;
308         return;
309       }
310     }
311     WARN1("Ignoring request to free an unknown socket (%p)",sock);
312   }
313   XBT_OUT;
314 }
315
316 /**
317  * gras_trp_send:
318  *
319  * Send a bunch of bytes from on socket
320  * (stable if we know the storage will keep as is until the next trp_flush)
321  */
322 void
323 gras_trp_send(gras_socket_t sd, char *data, long int size, int stable) {
324   xbt_assert0(sd->outgoing,"Socket not suited for data send");
325   (*sd->plugin->send)(sd,data,size,stable);
326 }
327 /**
328  * gras_trp_chunk_recv:
329  *
330  * Receive a bunch of bytes from a socket
331  */
332 void
333 gras_trp_recv(gras_socket_t sd, char *data, long int size) {
334   xbt_assert0(sd->incoming,"Socket not suited for data receive");
335   (sd->plugin->recv)(sd,data,size);
336 }
337
338 /**
339  * gras_trp_flush:
340  *
341  * Make sure all pending communications are done
342  */
343 void
344 gras_trp_flush(gras_socket_t sd) {
345   if (sd->plugin->flush)
346     (sd->plugin->flush)(sd);
347 }
348
349 gras_trp_plugin_t
350 gras_trp_plugin_get_by_name(const char *name){
351   return xbt_dict_get(_gras_trp_plugins,name);
352 }
353
354 int   gras_socket_my_port  (gras_socket_t sock) {
355   return sock->port;
356 }
357 int   gras_socket_peer_port(gras_socket_t sock) {
358   return sock->peer_port;
359 }
360 char *gras_socket_peer_name(gras_socket_t sock) {
361   return sock->peer_name;
362 }
363
364 /** \brief Check if the provided socket is a measurement one (or a regular one) */
365 int gras_socket_is_meas(gras_socket_t sock) {
366   return sock->meas;
367 }
368
369 /** \brief Send a chunk of (random) data over a measurement socket 
370  *
371  * @param peer measurement socket to use for the experiment
372  * @param timeout timeout (in seconds)
373  * @param exp_size total amount of data to send (in bytes).
374  * @param msg_size size of each chunk sent over the socket (in bytes).
375  *
376  * Calls to gras_socket_meas_send() and gras_socket_meas_recv() on 
377  * each side of the socket should be paired. 
378  * 
379  * The exchanged data is zeroed to make sure it's initialized, but
380  * there is no way to control what is sent (ie, you cannot use these 
381  * functions to exchange data out of band).
382  */
383 void gras_socket_meas_send(gras_socket_t peer, 
384                            unsigned int timeout,
385                            unsigned long int exp_size, 
386                            unsigned long int msg_size) {
387   char *chunk = xbt_malloc0(msg_size);
388   unsigned long int exp_sofar;
389    
390   XBT_IN;
391
392   xbt_assert0(peer->meas,"Asked to send measurement data on a regular socket");
393   xbt_assert0(peer->outgoing,"Socket not suited for data send");
394
395   for (exp_sofar=0; exp_sofar < exp_size; exp_sofar += msg_size) {
396      CDEBUG5(trp_meas,"Sent %lu of %lu (msg_size=%ld) to %s:%d",
397              exp_sofar,exp_size,msg_size,
398              gras_socket_peer_name(peer), gras_socket_peer_port(peer));
399      (*peer->plugin->raw_send)(peer,chunk,msg_size);
400   }
401   CDEBUG5(trp_meas,"Sent %lu of %lu (msg_size=%ld) to %s:%d",
402           exp_sofar,exp_size,msg_size,
403           gras_socket_peer_name(peer), gras_socket_peer_port(peer));
404              
405   free(chunk);
406
407   XBT_OUT;
408 }
409
410 /** \brief Receive a chunk of data over a measurement socket 
411  *
412  * Calls to gras_socket_meas_send() and gras_socket_meas_recv() on 
413  * each side of the socket should be paired. 
414  */
415 void gras_socket_meas_recv(gras_socket_t peer, 
416                            unsigned int timeout,
417                            unsigned long int exp_size, 
418                            unsigned long int msg_size){
419   
420   char *chunk = xbt_malloc(msg_size);
421   unsigned long int exp_sofar;
422
423   XBT_IN;
424
425   xbt_assert0(peer->meas,
426               "Asked to receive measurement data on a regular socket");
427   xbt_assert0(peer->incoming,"Socket not suited for data receive");
428
429   for (exp_sofar=0; exp_sofar < exp_size; exp_sofar += msg_size) {
430      CDEBUG5(trp_meas,"Recvd %ld of %lu (msg_size=%ld) from %s:%d",
431              exp_sofar,exp_size,msg_size,
432              gras_socket_peer_name(peer), gras_socket_peer_port(peer));
433      (peer->plugin->raw_recv)(peer,chunk,msg_size);
434   }
435   CDEBUG5(trp_meas,"Recvd %ld of %lu (msg_size=%ld) from %s:%d",
436           exp_sofar,exp_size,msg_size,
437           gras_socket_peer_name(peer), gras_socket_peer_port(peer));
438
439   free(chunk);
440   XBT_OUT;
441 }
442
443 /**
444  * \brief Something similar to the good old accept system call. 
445  *
446  * Make sure that there is someone speaking to the provided server socket.
447  * In RL, it does an accept(2) and return the result as last argument. 
448  * In SG, as accepts are useless, it returns the provided argument as result.
449  * You should thus test whether (peer != accepted) before closing both of them.
450  *
451  * You should only call this on measurement sockets. It is automatically 
452  * done for regular sockets, but you usually want more control about 
453  * what's going on with measurement sockets.
454  */
455 gras_socket_t gras_socket_meas_accept(gras_socket_t peer){
456   gras_socket_t res;
457
458   xbt_assert0(peer->meas,
459               "No need to accept on non-measurement sockets (it's automatic)");
460
461   if (!peer->accepting) {
462     /* nothing to accept here */
463     return peer;
464   }
465
466   res = (peer->plugin->socket_accept)(peer);
467   res->meas = peer->meas;
468   CDEBUG1(trp_meas,"meas_accepted onto %d",res->sd);
469
470   return res;
471
472
473
474 /*
475  * Creating procdata for this module
476  */
477 static void *gras_trp_procdata_new() {
478    gras_trp_procdata_t res = xbt_new(s_gras_trp_procdata_t,1);
479    
480    res->name = xbt_strdup("gras_trp");
481    res->name_len = 0;
482    res->sockets   = xbt_dynar_new(sizeof(gras_socket_t*), NULL);
483    
484    return (void*)res;
485 }
486
487 /*
488  * Freeing procdata for this module
489  */
490 static void gras_trp_procdata_free(void *data) {
491    gras_trp_procdata_t res = (gras_trp_procdata_t)data;
492    
493    xbt_dynar_free(&( res->sockets ));
494    free(res);
495 }
496
497 /*
498  * Module registration
499  */
500 int gras_trp_libdata_id;
501 void gras_trp_register() {
502    gras_trp_libdata_id = gras_procdata_add("gras_trp",gras_trp_procdata_new, gras_trp_procdata_free);
503 }
504
505
506 xbt_dynar_t 
507 gras_socketset_get(void) {
508    /* FIXME: KILLME */
509    return ((gras_trp_procdata_t) gras_libdata_by_id(gras_trp_libdata_id))->sockets;
510 }