Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
cefc3e94534a59ea31a97caf38e01776251289f7
[simgrid.git] / src / gras / Transport / transport.c
1 /* transport - low level communication                                      */
2
3 /* Copyright (c) 2004, 2005, 2006, 2007, 2008, 2009, 2010. The SimGrid Team.
4  * All rights reserved.                                                     */
5
6 /* This program is free software; you can redistribute it and/or modify it
7  * under the terms of the license (GNU LGPL) which comes with this package. */
8
9 /***
10  *** Options
11  ***/
12 int gras_opt_trp_nomoredata_on_close = 0;
13
14 #include "xbt/ex.h"
15 #include "xbt/peer.h"
16 #include "portable.h"
17 #include "gras/Transport/transport_private.h"
18 #include "gras/Msg/msg_interface.h"
19
20 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(gras_trp, gras,
21                                 "Conveying bytes over the network");
22 XBT_LOG_NEW_SUBCATEGORY(gras_trp_meas, gras_trp,
23                         "Conveying bytes over the network without formating for perf measurements");
24 static short int _gras_trp_started = 0;
25
26 static xbt_dict_t _gras_trp_plugins;    /* All registered plugins */
27 static void gras_trp_plugin_free(void *p);      /* free one of the plugins */
28
29 static void gras_trp_plugin_new(const char *name, gras_trp_setup_t setup)
30 {
31   xbt_ex_t e;
32
33   gras_trp_plugin_t plug = xbt_new0(s_gras_trp_plugin_t, 1);
34
35   DEBUG1("Create plugin %s", name);
36
37   plug->name = xbt_strdup(name);
38
39   TRY {
40     setup(plug);
41   } CATCH(e) {
42     if (e.category == mismatch_error) {
43       /* SG plugin raise mismatch when in RL mode (and vice versa) */
44       free(plug->name);
45       free(plug);
46       plug = NULL;
47       xbt_ex_free(e);
48     } else {
49       RETHROW;
50     }
51   }
52
53   if (plug)
54     xbt_dict_set(_gras_trp_plugins, name, plug, gras_trp_plugin_free);
55 }
56
57 void gras_trp_init(void)
58 {
59   if (!_gras_trp_started) {
60     /* make room for all plugins */
61     _gras_trp_plugins = xbt_dict_new();
62
63 #ifdef HAVE_WINSOCK2_H
64     /* initialize the windows mechanism */
65     {
66       WORD wVersionRequested;
67       WSADATA wsaData;
68
69       wVersionRequested = MAKEWORD(2, 0);
70       xbt_assert0(WSAStartup(wVersionRequested, &wsaData) == 0,
71                   "Cannot find a usable WinSock DLL");
72
73       /* Confirm that the WinSock DLL supports 2.0. */
74       /* Note that if the DLL supports versions greater    */
75       /* than 2.0 in addition to 2.0, it will still return */
76       /* 2.0 in wVersion since that is the version we      */
77       /* requested.                                        */
78
79       xbt_assert0(LOBYTE(wsaData.wVersion) == 2 &&
80                   HIBYTE(wsaData.wVersion) == 0,
81                   "Cannot find a usable WinSock DLL");
82       INFO0("Found and initialized winsock2");
83     }                           /* The WinSock DLL is acceptable. Proceed. */
84 #elif HAVE_WINSOCK_H
85     {
86       WSADATA wsaData;
87       xbt_assert0(WSAStartup(0x0101, &wsaData) == 0,
88                   "Cannot find a usable WinSock DLL");
89       INFO0("Found and initialized winsock");
90     }
91 #endif
92
93     /* Add plugins */
94     gras_trp_plugin_new("file", gras_trp_file_setup);
95     gras_trp_plugin_new("sg", gras_trp_sg_setup);
96     gras_trp_plugin_new("tcp", gras_trp_tcp_setup);
97   }
98
99   _gras_trp_started++;
100 }
101
102 void gras_trp_exit(void)
103 {
104   DEBUG1("gras_trp value %d", _gras_trp_started);
105   if (_gras_trp_started == 0) {
106     return;
107   }
108
109   if (--_gras_trp_started == 0) {
110 #ifdef HAVE_WINSOCK_H
111     if (WSACleanup() == SOCKET_ERROR) {
112       if (WSAGetLastError() == WSAEINPROGRESS) {
113         WSACancelBlockingCall();
114         WSACleanup();
115       }
116     }
117 #endif
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 {
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, gras_socket_t * dst)
149 {
150
151   gras_socket_t sock = xbt_new0(s_gras_socket_t, 1);
152
153   VERB1("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   sock->recvd = 0;
162   sock->valid = 1;
163   sock->moredata = 0;
164
165   sock->sd = -1;
166
167   sock->data = NULL;
168   sock->bufdata = NULL;
169
170   *dst = sock;
171
172   XBT_OUT;
173 }
174
175 /**
176  * @brief Opens a server socket and makes it ready to be listened to.
177  * @param port: port on which you want to listen
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  * @param measurement: whether this socket is meant to convey measurement (if you don't know, use 0 to exchange regular messages)
180  *
181  * In real life, you'll get a TCP socket.
182  */
183 gras_socket_t
184 gras_socket_server_ext(unsigned short port,
185                        unsigned long int buf_size, int measurement)
186 {
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", port);
194   trp = gras_trp_plugin_get_by_name(gras_if_SG()? "sg" : "tcp");
195
196   /* defaults settings */
197   gras_trp_socket_new(1, &sock);
198   sock->plugin = trp;
199   sock->buf_size = buf_size > 0 ? buf_size : 32 * 1024;
200   sock->meas = measurement;
201
202   /* Call plugin socket creation function */
203   DEBUG1("Prepare socket with plugin (fct=%p)", trp->socket_server);
204   TRY {
205     trp->socket_server(trp, port, sock);
206     DEBUG3("in=%c out=%c accept=%c",
207            sock->incoming ? 'y' : 'n',
208            sock->outgoing ? 'y' : 'n', sock->accepting ? 'y' : 'n');
209   } CATCH(e) {
210
211     free(sock);
212     RETHROW;
213   }
214
215   if (!measurement)
216     ((gras_trp_procdata_t) gras_libdata_by_id(gras_trp_libdata_id))->myport
217         = port;
218   xbt_dynar_push(((gras_trp_procdata_t)
219                   gras_libdata_by_id(gras_trp_libdata_id))->sockets,
220                  &sock);
221
222   gras_msg_listener_awake();
223   return sock;
224 }
225
226 /**
227  * @brief Opens a server socket on any port in the given range
228  *
229  * @param minport: first port we will try
230  * @param maxport: last port we will try
231  * @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)
232  * @param measurement: whether this socket is meant to convey measurement (if you don't know, use 0 to exchange regular messages)
233  *
234  * If none of the provided ports works, raises the exception got when trying the last possibility
235  */
236 gras_socket_t
237 gras_socket_server_range(unsigned short minport, unsigned short maxport,
238                          unsigned long int buf_size, int measurement)
239 {
240
241   int port;
242   gras_socket_t res = NULL;
243   xbt_ex_t e;
244
245   for (port = minport; port < maxport; port++) {
246     TRY {
247       res = gras_socket_server_ext(port, buf_size, measurement);
248     }
249     CATCH(e) {
250       if (port == maxport)
251         RETHROW;
252       xbt_ex_free(e);
253     }
254     if (res)
255       return res;
256   }
257   THROW_IMPOSSIBLE;
258 }
259
260 /**
261  * @brief Opens a client socket to a remote host.
262  * @param host: who you want to connect to
263  * @param port: where you want to connect to on this host
264  * @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)
265  * @param measurement: whether this socket is meant to convey measurement (if you don't know, use 0 to exchange regular messages)
266  *
267  * In real life, you'll get a TCP socket.
268  */
269 gras_socket_t
270 gras_socket_client_ext(const char *host,
271                        unsigned short port,
272                        unsigned long int buf_size, int measurement)
273 {
274
275   xbt_ex_t e;
276   gras_trp_plugin_t trp;
277   gras_socket_t sock;
278
279   trp = gras_trp_plugin_get_by_name(gras_if_SG()? "sg" : "tcp");
280
281   DEBUG1("Create a client socket from plugin %s",
282          gras_if_RL()? "tcp" : "sg");
283   /* defaults settings */
284   gras_trp_socket_new(0, &sock);
285   sock->plugin = trp;
286   sock->buf_size = buf_size > 0 ? buf_size : 32 * 1024;
287   sock->meas = measurement;
288
289   /* plugin-specific */
290   TRY {
291     (*trp->socket_client) (trp,host,port,sock);
292     DEBUG3("in=%c out=%c accept=%c",
293            sock->incoming ? 'y' : 'n',
294            sock->outgoing ? 'y' : 'n', sock->accepting ? 'y' : 'n');
295   } CATCH(e) {
296     free(sock);
297     RETHROW;
298   }
299   xbt_dynar_push(((gras_trp_procdata_t)
300                   gras_libdata_by_id(gras_trp_libdata_id))->sockets,
301                  &sock);
302   gras_msg_listener_awake();
303   return sock;
304 }
305
306 /**
307  * @brief Opens a server socket and make it ready to be listened to.
308  *
309  * In real life, you'll get a TCP socket.
310  */
311 gras_socket_t gras_socket_server(unsigned short port)
312 {
313   return gras_socket_server_ext(port, 32 * 1024, 0);
314 }
315
316 /** @brief Opens a client socket to a remote host */
317 gras_socket_t gras_socket_client(const char *host, unsigned short port)
318 {
319   return gras_socket_client_ext(host, port, 0, 0);
320 }
321
322 /** @brief Opens a client socket to a remote host specified as '\a host:\a port' */
323 gras_socket_t gras_socket_client_from_string(const char *host)
324 {
325   xbt_peer_t p = xbt_peer_from_string(host);
326   gras_socket_t res = gras_socket_client_ext(p->name, p->port, 0, 0);
327   xbt_peer_free(p);
328   return res;
329 }
330
331 void gras_socket_close_voidp(void *sock)
332 {
333   gras_socket_close((gras_socket_t) sock);
334 }
335
336 /** \brief Close socket */
337 void gras_socket_close(gras_socket_t sock)
338 {
339   xbt_dynar_t sockets =
340       ((gras_trp_procdata_t)
341        gras_libdata_by_id(gras_trp_libdata_id))->sockets;
342   gras_socket_t sock_iter = NULL;
343   unsigned int cursor;
344
345   XBT_IN;
346   VERB1("Close %p", sock);
347   if (sock == _gras_lastly_selected_socket) {
348     xbt_assert0(!gras_opt_trp_nomoredata_on_close || !sock->moredata,
349                 "Closing a socket having more data in buffer while the nomoredata_on_close option is activated");
350
351     if (sock->moredata)
352       CRITICAL0
353           ("Closing a socket having more data in buffer. Option nomoredata_on_close disabled, so continuing.");
354     _gras_lastly_selected_socket = NULL;
355   }
356
357   /* FIXME: Issue an event when the socket is closed */
358   DEBUG1("sockets pointer before %p", sockets);
359   if (sock) {
360     /* FIXME: Cannot get the dynar mutex, because it can be already locked */
361 //              _xbt_dynar_foreach(sockets,cursor,sock_iter) {
362     for (cursor = 0; cursor < xbt_dynar_length(sockets); cursor++) {
363       _xbt_dynar_cursor_get(sockets, cursor, &sock_iter);
364       if (sock == sock_iter) {
365         DEBUG2("remove sock cursor %d dize %lu\n", cursor,
366                xbt_dynar_length(sockets));
367         xbt_dynar_cursor_rm(sockets, &cursor);
368         if (sock->plugin->socket_close)
369           (*sock->plugin->socket_close) (sock);
370
371         /* free the memory */
372         free(sock);
373         XBT_OUT;
374         return;
375       }
376     }
377     WARN1
378         ("Ignoring request to free an unknown socket (%p). Execution stack:",
379          sock);
380     xbt_backtrace_display_current();
381   }
382   XBT_OUT;
383 }
384
385 /**
386  * gras_trp_send:
387  *
388  * Send a bunch of bytes from on socket
389  * (stable if we know the storage will keep as is until the next trp_flush)
390  */
391 void gras_trp_send(gras_socket_t sd, char *data, long int size, int stable)
392 {
393   xbt_assert0(sd->outgoing, "Socket not suited for data send");
394   (*sd->plugin->send) (sd, data, size, stable);
395 }
396
397 /**
398  * gras_trp_chunk_recv:
399  *
400  * Receive a bunch of bytes from a socket
401  */
402 void gras_trp_recv(gras_socket_t sd, char *data, long int size)
403 {
404   xbt_assert0(sd->incoming, "Socket not suited for data receive");
405   (sd->plugin->recv) (sd, data, size);
406 }
407
408 /**
409  * gras_trp_flush:
410  *
411  * Make sure all pending communications are done
412  */
413 void gras_trp_flush(gras_socket_t sd)
414 {
415   if (sd->plugin->flush)
416     (sd->plugin->flush) (sd);
417 }
418
419 gras_trp_plugin_t gras_trp_plugin_get_by_name(const char *name)
420 {
421   return xbt_dict_get(_gras_trp_plugins, name);
422 }
423
424 int gras_socket_my_port(gras_socket_t sock)
425 {
426   if (!sock->plugin->my_port)
427     THROW1(unknown_error,0,"Function my_port unimplemented in plugin %s",sock->plugin->name);
428   return (*sock->plugin->my_port)(sock);
429
430 }
431
432 int gras_socket_peer_port(gras_socket_t sock)
433 {
434   if (!sock->plugin->peer_port)
435     THROW1(unknown_error,0,"Function peer_port unimplemented in plugin %s",sock->plugin->name);
436   return (*sock->plugin->peer_port)(sock);
437 }
438
439 const char *gras_socket_peer_name(gras_socket_t sock)
440 {
441   return (*sock->plugin->peer_name)(sock);
442 }
443
444 const char *gras_socket_peer_proc(gras_socket_t sock)
445 {
446   return (*sock->plugin->peer_proc)(sock);
447 }
448
449 void gras_socket_peer_proc_set(gras_socket_t sock, char *peer_proc)
450 {
451   return (*sock->plugin->peer_proc_set)(sock,peer_proc);
452 }
453
454 /** \brief Check if the provided socket is a measurement one (or a regular one) */
455 int gras_socket_is_meas(gras_socket_t sock)
456 {
457   return sock->meas;
458 }
459
460 /** \brief Send a chunk of (random) data over a measurement socket
461  *
462  * @param peer measurement socket to use for the experiment
463  * @param timeout timeout (in seconds)
464  * @param msg_size size of each chunk sent over the socket (in bytes).
465  * @param msg_amount how many of these packets you want to send.
466  *
467  * Calls to gras_socket_meas_send() and gras_socket_meas_recv() on
468  * each side of the socket should be paired.
469  *
470  * The exchanged data is zeroed to make sure it's initialized, but
471  * there is no way to control what is sent (ie, you cannot use these
472  * functions to exchange data out of band).
473  *
474  * @warning: in SimGrid version 3.1 and previous, the numerical arguments
475  *           were the total amount of data to send and the msg_size. This
476  *           was changed for the fool wanting to send more than MAXINT
477  *           bytes in a fat pipe.
478  */
479 void gras_socket_meas_send(gras_socket_t peer,
480                            unsigned int timeout,
481                            unsigned long int msg_size,
482                            unsigned long int msg_amount)
483 {
484   char *chunk = NULL;
485   unsigned long int sent_sofar;
486
487   XBT_IN;
488
489   if (gras_if_RL())
490     chunk = xbt_malloc0(msg_size);
491
492   xbt_assert0(peer->meas,
493               "Asked to send measurement data on a regular socket");
494   xbt_assert0(peer->outgoing,
495               "Socket not suited for data send (was created with gras_socket_server(), not gras_socket_client())");
496
497   for (sent_sofar = 0; sent_sofar < msg_amount; sent_sofar++) {
498     CDEBUG5(gras_trp_meas,
499             "Sent %lu msgs of %lu (size of each: %ld) to %s:%d",
500             sent_sofar, msg_amount, msg_size, gras_socket_peer_name(peer),
501             gras_socket_peer_port(peer));
502     (*peer->plugin->raw_send) (peer, chunk, msg_size);
503   }
504   CDEBUG5(gras_trp_meas,
505           "Sent %lu msgs of %lu (size of each: %ld) to %s:%d", sent_sofar,
506           msg_amount, msg_size, gras_socket_peer_name(peer),
507           gras_socket_peer_port(peer));
508
509   if (gras_if_RL())
510     free(chunk);
511
512   XBT_OUT;
513 }
514
515 /** \brief Receive a chunk of data over a measurement socket
516  *
517  * Calls to gras_socket_meas_send() and gras_socket_meas_recv() on
518  * each side of the socket should be paired.
519  *
520  * @warning: in SimGrid version 3.1 and previous, the numerical arguments
521  *           were the total amount of data to send and the msg_size. This
522  *           was changed for the fool wanting to send more than MAXINT
523  *           bytes in a fat pipe.
524  */
525 void gras_socket_meas_recv(gras_socket_t peer,
526                            unsigned int timeout,
527                            unsigned long int msg_size,
528                            unsigned long int msg_amount)
529 {
530
531   char *chunk = NULL;
532   unsigned long int got_sofar;
533
534   XBT_IN;
535
536   if (gras_if_RL())
537     chunk = xbt_malloc(msg_size);
538
539   xbt_assert0(peer->meas,
540               "Asked to receive measurement data on a regular socket");
541   xbt_assert0(peer->incoming, "Socket not suited for data receive");
542
543   for (got_sofar = 0; got_sofar < msg_amount; got_sofar++) {
544     CDEBUG5(gras_trp_meas,
545             "Recvd %ld msgs of %lu (size of each: %ld) from %s:%d",
546             got_sofar, msg_amount, msg_size, gras_socket_peer_name(peer),
547             gras_socket_peer_port(peer));
548     (peer->plugin->raw_recv) (peer, chunk, msg_size);
549   }
550   CDEBUG5(gras_trp_meas,
551           "Recvd %ld msgs of %lu (size of each: %ld) from %s:%d",
552           got_sofar, msg_amount, msg_size, gras_socket_peer_name(peer),
553           gras_socket_peer_port(peer));
554
555   if (gras_if_RL())
556     free(chunk);
557   XBT_OUT;
558 }
559
560 /**
561  * \brief Something similar to the good old accept system call.
562  *
563  * Make sure that there is someone speaking to the provided server socket.
564  * In RL, it does an accept(2) and return the result as last argument.
565  * In SG, as accepts are useless, it returns the provided argument as result.
566  * You should thus test whether (peer != accepted) before closing both of them.
567  *
568  * You should only call this on measurement sockets. It is automatically
569  * done for regular sockets, but you usually want more control about
570  * what's going on with measurement sockets.
571  */
572 gras_socket_t gras_socket_meas_accept(gras_socket_t peer)
573 {
574   gras_socket_t res;
575
576   xbt_assert0(peer->meas,
577               "No need to accept on non-measurement sockets (it's automatic)");
578
579   if (!peer->accepting) {
580     /* nothing to accept here (must be in SG) */
581     /* BUG: FIXME: this is BAD! it makes tricky to free the accepted socket */
582     return peer;
583   }
584
585   res = (peer->plugin->socket_accept) (peer);
586   res->meas = peer->meas;
587   CDEBUG1(gras_trp_meas, "meas_accepted onto %d", res->sd);
588
589   return res;
590 }
591
592
593 /*
594  * Creating procdata for this module
595  */
596 static void *gras_trp_procdata_new(void)
597 {
598   gras_trp_procdata_t res = xbt_new(s_gras_trp_procdata_t, 1);
599
600   res->name = xbt_strdup("gras_trp");
601   res->name_len = 0;
602   res->sockets = xbt_dynar_new_sync(sizeof(gras_socket_t *), NULL);
603   res->myport = 0;
604
605   return (void *) res;
606 }
607
608 /*
609  * Freeing procdata for this module
610  */
611 static void gras_trp_procdata_free(void *data)
612 {
613   gras_trp_procdata_t res = (gras_trp_procdata_t) data;
614
615   xbt_dynar_free(&(res->sockets));
616   free(res->name);
617   free(res);
618 }
619
620 void gras_trp_socketset_dump(const char *name)
621 {
622   gras_trp_procdata_t procdata =
623       (gras_trp_procdata_t) gras_libdata_by_id(gras_trp_libdata_id);
624
625   unsigned int it;
626   gras_socket_t s;
627
628   INFO1("** Dump the socket set %s", name);
629   xbt_dynar_foreach(procdata->sockets, it, s) {
630     INFO4("  %p -> %s:%d %s",
631           s, gras_socket_peer_name(s), gras_socket_peer_port(s),
632           s->valid ? "(valid)" : "(peer dead)");
633   }
634   INFO1("** End of socket set %s", name);
635 }
636
637 /*
638  * Module registration
639  */
640 int gras_trp_libdata_id;
641 void gras_trp_register()
642 {
643   gras_trp_libdata_id =
644       gras_procdata_add("gras_trp", gras_trp_procdata_new,
645                         gras_trp_procdata_free);
646 }
647
648 int gras_os_myport(void)
649 {
650   return ((gras_trp_procdata_t)
651           gras_libdata_by_id(gras_trp_libdata_id))->myport;
652 }