Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
e668b3f32a77a32a4f8e9fd151c9216f8919c4e7
[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 /***
11  *** Options
12  ***/
13 int gras_opt_trp_nomoredata_on_close=0;
14
15 #include "xbt/ex.h"
16 #include "xbt/peer.h"
17 #include "portable.h"
18 #include "gras/Transport/transport_private.h"
19
20 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(gras_trp,gras,"Conveying bytes over the network");
21 XBT_LOG_NEW_SUBCATEGORY(gras_trp_meas,gras_trp,"Conveying bytes over the network without formating for perf measurements");
22 static short int _gras_trp_started = 0;
23
24 static xbt_dict_t _gras_trp_plugins;      /* All registered plugins */
25 static void gras_trp_plugin_free(void *p); /* free one of the plugins */
26
27 static void
28 gras_trp_plugin_new(const char *name, gras_trp_setup_t setup) {
29   xbt_ex_t e;
30
31   gras_trp_plugin_t plug = xbt_new0(s_gras_trp_plugin_t, 1);
32   
33   DEBUG1("Create plugin %s",name);
34
35   plug->name=xbt_strdup(name);
36
37   TRY {
38     setup(plug);
39   } CATCH(e) {
40     if (e.category == mismatch_error) {
41       /* SG plugin raise mismatch when in RL mode (and vice versa) */
42       free(plug->name);
43       free(plug);
44       plug=NULL;
45       xbt_ex_free(e);
46     } else {
47       RETHROW;
48     }
49   }
50
51   if (plug)
52     xbt_dict_set(_gras_trp_plugins, name, plug, gras_trp_plugin_free);
53 }
54
55 void gras_trp_init(void){
56   if (!_gras_trp_started) {
57      /* make room for all plugins */
58      _gras_trp_plugins=xbt_dict_new();
59
60 #ifdef HAVE_WINSOCK2_H
61      /* initialize the windows mechanism */
62      {  
63         WORD wVersionRequested;
64         WSADATA wsaData;
65         
66         wVersionRequested = MAKEWORD( 2, 0 );
67         xbt_assert0(WSAStartup( wVersionRequested, &wsaData ) == 0,
68                     "Cannot find a usable WinSock DLL");
69         
70         /* Confirm that the WinSock DLL supports 2.0.*/
71         /* Note that if the DLL supports versions greater    */
72         /* than 2.0 in addition to 2.0, it will still return */
73         /* 2.0 in wVersion since that is the version we      */
74         /* requested.                                        */
75         
76         xbt_assert0(LOBYTE( wsaData.wVersion ) == 2 &&
77                     HIBYTE( wsaData.wVersion ) == 0,
78                     "Cannot find a usable WinSock DLL");
79         INFO0("Found and initialized winsock2");
80      }       /* The WinSock DLL is acceptable. Proceed. */
81 #elif HAVE_WINSOCK_H
82      {       WSADATA wsaData;
83         xbt_assert0(WSAStartup( 0x0101, &wsaData ) == 0,
84                     "Cannot find a usable WinSock DLL");
85         INFO0("Found and initialized winsock");
86      }
87 #endif
88    
89      /* Add plugins */
90      gras_trp_plugin_new("file",gras_trp_file_setup);
91      gras_trp_plugin_new("sg",gras_trp_sg_setup);
92      gras_trp_plugin_new("tcp", gras_trp_tcp_setup);
93   }
94    
95   _gras_trp_started++;
96 }
97
98 void
99 gras_trp_exit(void){
100    DEBUG1("gras_trp value %d",_gras_trp_started);
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       /* Delete the plugins */
116       xbt_dict_free(&_gras_trp_plugins);
117    }
118 }
119
120
121 void gras_trp_plugin_free(void *p) {
122   gras_trp_plugin_t plug = p;
123
124   if (plug) {
125     if (plug->exit) {
126       plug->exit(plug);
127     } else if (plug->data) {
128       DEBUG1("Plugin %s lacks exit(). Free data anyway.",plug->name);
129       free(plug->data);
130     }
131
132     free(plug->name);
133     free(plug);
134   }
135 }
136
137
138 /**
139  * gras_trp_socket_new:
140  *
141  * Malloc a new socket, and initialize it with defaults
142  */
143 void gras_trp_socket_new(int incoming,
144                          gras_socket_t *dst) {
145
146   gras_socket_t sock=xbt_new0(s_gras_socket_t,1);
147
148   VERB1("Create a new socket (%p)", (void*)sock);
149
150   sock->plugin = NULL;
151
152   sock->incoming  = incoming ? 1:0;
153   sock->outgoing  = incoming ? 0:1;
154   sock->accepting = incoming ? 1:0;
155   sock->meas = 0;
156   sock->recv_ok = 1;
157   sock->valid = 1;
158   sock->moredata = 0;
159
160   sock->sd     = -1;
161   sock->port      = -1;
162   sock->peer_port = -1;
163   sock->peer_name = NULL;
164   sock->peer_proc = NULL;
165
166   sock->data   = NULL;
167   sock->bufdata = NULL;
168   
169   *dst = sock;
170
171   xbt_dynar_push(((gras_trp_procdata_t) 
172                   gras_libdata_by_id(gras_trp_libdata_id))->sockets,dst);
173   XBT_OUT;
174 }
175  
176 /**
177  * @brief Opens a server socket and makes it ready to be listened to.
178  * @param port: port on which you want to listen
179  * @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)
180  * @param measurement: whether this socket is meant to convey measurement (if you don't know, use 0 to exchange regular messages)
181  * 
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 buf_size,
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":"tcp");
198
199   /* defaults settings */
200   gras_trp_socket_new(1,&sock);
201   sock->plugin= trp;
202   sock->port=port;
203   sock->buf_size = buf_size>0 ? buf_size : 32*1024;
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     int cursor;
216     gras_socket_t sock_iter;
217     xbt_dynar_t socks = ((gras_trp_procdata_t) gras_libdata_by_id(gras_trp_libdata_id))->sockets;
218     xbt_dynar_foreach(socks, cursor, sock_iter) {
219        if (sock_iter==sock) 
220          xbt_dynar_cursor_rm(socks,&cursor);
221     }     
222     free(sock);
223     RETHROW;
224   }
225
226   if (!measurement)
227      ((gras_trp_procdata_t) gras_libdata_by_id(gras_trp_libdata_id))->myport = port;
228   return sock;
229 }
230 /**
231  * @brief Opens a server socket on any port in the given range
232  * 
233  * @param minport: first port we will try
234  * @param maxport: last port we will try
235  * @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)
236  * @param measurement: whether this socket is meant to convey measurement (if you don't know, use 0 to exchange regular messages)
237  * 
238  * If none of the provided ports works, raises the exception got when trying the last possibility
239  */ 
240 gras_socket_t
241 gras_socket_server_range(unsigned short minport, unsigned short maxport,
242                          unsigned long int buf_size, int measurement) {
243    
244   int port;
245   gras_socket_t res=NULL;
246   xbt_ex_t e;
247   
248   for (port=minport; port<maxport;port ++) {
249     TRY {
250       res=gras_socket_server_ext(port,buf_size,measurement);
251     } CATCH(e) {
252       if (port==maxport)
253         RETHROW;
254       xbt_ex_free(e);
255     }
256     if (res)
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 '\a host:\a port' */
327 gras_socket_t
328 gras_socket_client_from_string(const char *host) {
329    xbt_peer_t p = xbt_peer_from_string(host);
330    gras_socket_t res = gras_socket_client_ext(p->name,p->port,0,0);
331    xbt_peer_free(p);
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   VERB1("Close %p",sock);
343   if (sock == _gras_lastly_selected_socket) {
344      xbt_assert0(!gras_opt_trp_nomoredata_on_close || !sock->moredata,
345                  "Closing a socket having more data in buffer while the nomoredata_on_close option is activated");
346                  
347      if (sock->moredata) 
348        CRITICAL0("Closing a socket having more data in buffer. Option nomoredata_on_close disabled, so continuing.");
349      _gras_lastly_selected_socket=NULL;
350   }
351    
352   /* FIXME: Issue an event when the socket is closed */
353         DEBUG1("sockets pointer before %p",sockets);
354   if (sock) {
355                 xbt_dynar_foreach(sockets,cursor,sock_iter) {
356                         if (sock == sock_iter) {
357                                 DEBUG2("remove sock cursor %d dize %lu\n",cursor,xbt_dynar_length(sockets));
358                                 xbt_dynar_cursor_rm(sockets,&cursor);
359                                 if (sock->plugin->socket_close) 
360                                         (* sock->plugin->socket_close)(sock);
361
362                                 /* free the memory */
363                                 if (sock->peer_name)
364                                         free(sock->peer_name);
365                                 free(sock);
366                                 XBT_OUT;
367                                 return;
368                         }
369     }
370     WARN1("Ignoring request to free an unknown socket (%p). Execution stack:",sock);
371     xbt_backtrace_display();
372   }
373   XBT_OUT;
374 }
375
376 /**
377  * gras_trp_send:
378  *
379  * Send a bunch of bytes from on socket
380  * (stable if we know the storage will keep as is until the next trp_flush)
381  */
382 void
383 gras_trp_send(gras_socket_t sd, char *data, long int size, int stable) {
384   xbt_assert0(sd->outgoing,"Socket not suited for data send");
385   (*sd->plugin->send)(sd,data,size,stable);
386 }
387 /**
388  * gras_trp_chunk_recv:
389  *
390  * Receive a bunch of bytes from a socket
391  */
392 void
393 gras_trp_recv(gras_socket_t sd, char *data, long int size) {
394   xbt_assert0(sd->incoming,"Socket not suited for data receive");
395   (sd->plugin->recv)(sd,data,size);
396 }
397
398 /**
399  * gras_trp_flush:
400  *
401  * Make sure all pending communications are done
402  */
403 void
404 gras_trp_flush(gras_socket_t sd) {
405   if (sd->plugin->flush)
406     (sd->plugin->flush)(sd);
407 }
408
409 gras_trp_plugin_t
410 gras_trp_plugin_get_by_name(const char *name){
411   return xbt_dict_get(_gras_trp_plugins,name);
412 }
413
414 int gras_socket_my_port  (gras_socket_t sock) {
415   return sock->port;
416 }
417 int   gras_socket_peer_port(gras_socket_t sock) {
418   return sock->peer_port;
419 }
420 char *gras_socket_peer_name(gras_socket_t sock) {
421   return sock->peer_name;
422 }
423 char *gras_socket_peer_proc(gras_socket_t sock) {
424   return sock->peer_proc;
425 }
426
427 void gras_socket_peer_proc_set(gras_socket_t sock,char*peer_proc) {
428   sock->peer_proc = peer_proc;
429 }
430
431 /** \brief Check if the provided socket is a measurement one (or a regular one) */
432 int gras_socket_is_meas(gras_socket_t sock) {
433   return sock->meas;
434 }
435
436 /** \brief Send a chunk of (random) data over a measurement socket 
437  *
438  * @param peer measurement socket to use for the experiment
439  * @param timeout timeout (in seconds)
440  * @param msg_size size of each chunk sent over the socket (in bytes).
441  * @param msg_amount how many of these packets you want to send. 
442  *
443  * Calls to gras_socket_meas_send() and gras_socket_meas_recv() on 
444  * each side of the socket should be paired. 
445  * 
446  * The exchanged data is zeroed to make sure it's initialized, but
447  * there is no way to control what is sent (ie, you cannot use these 
448  * functions to exchange data out of band).
449  * 
450  * @warning: in SimGrid version 3.1 and previous, the numerical arguments 
451  *           were the total amount of data to send and the msg_size. This 
452  *           was changed for the fool wanting to send more than MAXINT 
453  *           bytes in a fat pipe. 
454  */
455 void gras_socket_meas_send(gras_socket_t peer, 
456                            unsigned int timeout,
457                            unsigned long int msg_size, 
458                            unsigned long int msg_amount) {
459   char *chunk=NULL;
460   unsigned long int sent_sofar;
461   
462   XBT_IN;
463
464   if (gras_if_RL()) 
465     chunk=xbt_malloc0(msg_size);
466
467   xbt_assert0(peer->meas,"Asked to send measurement data on a regular socket");
468   xbt_assert0(peer->outgoing,"Socket not suited for data send (was created with gras_socket_server(), not gras_socket_client())");
469
470   for (sent_sofar=0; sent_sofar < msg_amount; sent_sofar++) {
471      CDEBUG5(gras_trp_meas,"Sent %lu msgs of %lu (size of each: %ld) to %s:%d",
472              sent_sofar,msg_amount,msg_size,
473              gras_socket_peer_name(peer), gras_socket_peer_port(peer));
474      (*peer->plugin->raw_send)(peer,chunk,msg_size);
475   }
476   CDEBUG5(gras_trp_meas,"Sent %lu msgs of %lu (size of each: %ld) to %s:%d",
477           sent_sofar,msg_amount,msg_size,
478           gras_socket_peer_name(peer), gras_socket_peer_port(peer));
479              
480   if (gras_if_RL()) 
481     free(chunk);
482
483   XBT_OUT;
484 }
485
486 /** \brief Receive a chunk of data over a measurement socket 
487  *
488  * Calls to gras_socket_meas_send() and gras_socket_meas_recv() on 
489  * each side of the socket should be paired. 
490  *
491  * @warning: in SimGrid version 3.1 and previous, the numerical arguments 
492  *           were the total amount of data to send and the msg_size. This 
493  *           was changed for the fool wanting to send more than MAXINT 
494  *           bytes in a fat pipe. 
495  */
496 void gras_socket_meas_recv(gras_socket_t peer, 
497                            unsigned int timeout,
498                            unsigned long int msg_size, 
499                            unsigned long int msg_amount){
500   
501   char *chunk=NULL;
502   unsigned long int got_sofar;
503
504   XBT_IN;
505
506   if (gras_if_RL()) 
507     chunk = xbt_malloc(msg_size);
508
509   xbt_assert0(peer->meas,
510               "Asked to receive measurement data on a regular socket");
511   xbt_assert0(peer->incoming,"Socket not suited for data receive");
512
513   for (got_sofar=0; got_sofar < msg_amount; got_sofar ++) {
514      CDEBUG5(gras_trp_meas,"Recvd %ld msgs of %lu (size of each: %ld) from %s:%d",
515              got_sofar,msg_amount,msg_size,
516              gras_socket_peer_name(peer), gras_socket_peer_port(peer));
517      (peer->plugin->raw_recv)(peer,chunk,msg_size);
518   }
519   CDEBUG5(gras_trp_meas,"Recvd %ld msgs of %lu (size of each: %ld) from %s:%d",
520           got_sofar,msg_amount,msg_size,
521           gras_socket_peer_name(peer), gras_socket_peer_port(peer));
522
523   if (gras_if_RL()) 
524     free(chunk);
525   XBT_OUT;
526 }
527
528 /**
529  * \brief Something similar to the good old accept system call. 
530  *
531  * Make sure that there is someone speaking to the provided server socket.
532  * In RL, it does an accept(2) and return the result as last argument. 
533  * In SG, as accepts are useless, it returns the provided argument as result.
534  * You should thus test whether (peer != accepted) before closing both of them.
535  *
536  * You should only call this on measurement sockets. It is automatically 
537  * done for regular sockets, but you usually want more control about 
538  * what's going on with measurement sockets.
539  */
540 gras_socket_t gras_socket_meas_accept(gras_socket_t peer){
541   gras_socket_t res;
542
543   xbt_assert0(peer->meas,
544               "No need to accept on non-measurement sockets (it's automatic)");
545
546   if (!peer->accepting) {
547     /* nothing to accept here (must be in SG) */
548     /* BUG: FIXME: this is BAD! it makes tricky to free the accepted socket*/
549     return peer;
550   }
551
552   res = (peer->plugin->socket_accept)(peer);
553   res->meas = peer->meas;
554   CDEBUG1(gras_trp_meas,"meas_accepted onto %d",res->sd);
555
556   return res;
557
558
559
560 /*
561  * Creating procdata for this module
562  */
563 static void *gras_trp_procdata_new() {
564    gras_trp_procdata_t res = xbt_new(s_gras_trp_procdata_t,1);
565    
566    res->name = xbt_strdup("gras_trp");
567    res->name_len = 0;
568    res->sockets = xbt_dynar_new(sizeof(gras_socket_t*), NULL);
569    res->myport = 0;
570    
571    return (void*)res;
572 }
573
574 /*
575  * Freeing procdata for this module
576  */
577 static void gras_trp_procdata_free(void *data) {
578   gras_trp_procdata_t res = (gras_trp_procdata_t)data;
579   
580   xbt_dynar_free(&( res->sockets ));
581   free(res->name);
582   free(res);
583 }
584
585 void gras_trp_socketset_dump(const char *name) {
586   gras_trp_procdata_t procdata = 
587     (gras_trp_procdata_t)gras_libdata_by_id(gras_trp_libdata_id);
588
589   int it;
590   gras_socket_t s;
591
592   INFO1("** Dump the socket set %s",name);
593   xbt_dynar_foreach(procdata->sockets, it, s) {
594     INFO4("  %p -> %s:%d %s",
595           s,gras_socket_peer_name(s),gras_socket_peer_port(s),
596           s->valid?"(valid)":"(peer dead)");
597   }
598   INFO1("** End of socket set %s",name);
599 }
600
601 /*
602  * Module registration
603  */
604 int gras_trp_libdata_id;
605 void gras_trp_register() {
606    gras_trp_libdata_id = gras_procdata_add("gras_trp",gras_trp_procdata_new, gras_trp_procdata_free);
607 }
608
609 int gras_os_myport(void)  {
610    return ((gras_trp_procdata_t) gras_libdata_by_id(gras_trp_libdata_id))->myport;
611 }
612