Logo AND Algorithmique Numérique Distribuée

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