Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Fix copyright headers
[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   sock->port = -1;
167   sock->peer_port = -1;
168   sock->peer_name = NULL;
169   sock->peer_proc = NULL;
170
171   sock->data = NULL;
172   sock->bufdata = NULL;
173
174   *dst = sock;
175
176   XBT_OUT;
177 }
178
179 /**
180  * @brief Opens a server socket and makes it ready to be listened to.
181  * @param port: port on which you want to listen
182  * @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)
183  * @param measurement: whether this socket is meant to convey measurement (if you don't know, use 0 to exchange regular messages)
184  *
185  * In real life, you'll get a TCP socket.
186  */
187 gras_socket_t
188 gras_socket_server_ext(unsigned short port,
189                        unsigned long int buf_size, int measurement)
190 {
191
192   xbt_ex_t e;
193   gras_trp_plugin_t trp;
194   gras_socket_t sock;
195
196   DEBUG2("Create a server socket from plugin %s on port %d",
197          gras_if_RL()? "tcp" : "sg", port);
198   trp = gras_trp_plugin_get_by_name(gras_if_SG()? "sg" : "tcp");
199
200   /* defaults settings */
201   gras_trp_socket_new(1, &sock);
202   sock->plugin = trp;
203   sock->port = port;
204   sock->buf_size = buf_size > 0 ? buf_size : 32 * 1024;
205   sock->meas = measurement;
206
207   /* Call plugin socket creation function */
208   DEBUG1("Prepare socket with plugin (fct=%p)", trp->socket_server);
209   TRY {
210     trp->socket_server(trp, sock);
211     DEBUG3("in=%c out=%c accept=%c",
212            sock->incoming ? 'y' : 'n',
213            sock->outgoing ? 'y' : 'n', sock->accepting ? 'y' : 'n');
214   } CATCH(e) {
215
216     free(sock);
217     RETHROW;
218   }
219
220   if (!measurement)
221     ((gras_trp_procdata_t) gras_libdata_by_id(gras_trp_libdata_id))->myport =
222       port;
223   xbt_dynar_push(((gras_trp_procdata_t)
224                   gras_libdata_by_id(gras_trp_libdata_id))->sockets, &sock);
225
226   gras_msg_listener_awake();
227   return sock;
228 }
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
245   int port;
246   gras_socket_t res = NULL;
247   xbt_ex_t e;
248
249   for (port = minport; port < maxport; port++) {
250     TRY {
251       res = gras_socket_server_ext(port, buf_size, measurement);
252     }
253     CATCH(e) {
254       if (port == maxport)
255         RETHROW;
256       xbt_ex_free(e);
257     }
258     if (res)
259       return res;
260   }
261   THROW_IMPOSSIBLE;
262 }
263
264 /**
265  * @brief Opens a client socket to a remote host.
266  * @param host: who you want to connect to
267  * @param port: where you want to connect to on this host
268  * @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)
269  * @param measurement: whether this socket is meant to convey measurement (if you don't know, use 0 to exchange regular messages)
270  *
271  * In real life, you'll get a TCP socket.
272  */
273 gras_socket_t
274 gras_socket_client_ext(const char *host,
275                        unsigned short port,
276                        unsigned long int buf_size, int measurement)
277 {
278
279   xbt_ex_t e;
280   gras_trp_plugin_t trp;
281   gras_socket_t sock;
282
283   trp = gras_trp_plugin_get_by_name(gras_if_SG()? "sg" : "tcp");
284
285   DEBUG1("Create a client socket from plugin %s", gras_if_RL()? "tcp" : "sg");
286   /* defaults settings */
287   gras_trp_socket_new(0, &sock);
288   sock->plugin = trp;
289   sock->peer_port = port;
290   sock->peer_name = (char *) strdup(host ? host : "localhost");
291   sock->buf_size = buf_size > 0 ? buf_size : 32 * 1024;
292   sock->meas = measurement;
293
294   /* plugin-specific */
295   TRY {
296     (*trp->socket_client) (trp, sock);
297     DEBUG3("in=%c out=%c accept=%c",
298            sock->incoming ? 'y' : 'n',
299            sock->outgoing ? 'y' : 'n', sock->accepting ? 'y' : 'n');
300   } CATCH(e) {
301     free(sock);
302     RETHROW;
303   }
304   xbt_dynar_push(((gras_trp_procdata_t)
305                   gras_libdata_by_id(gras_trp_libdata_id))->sockets, &sock);
306   gras_msg_listener_awake();
307   return sock;
308 }
309
310 /**
311  * @brief Opens a server socket and make it ready to be listened to.
312  *
313  * In real life, you'll get a TCP socket.
314  */
315 gras_socket_t gras_socket_server(unsigned short port)
316 {
317   return gras_socket_server_ext(port, 32 * 1024, 0);
318 }
319
320 /** @brief Opens a client socket to a remote host */
321 gras_socket_t gras_socket_client(const char *host, unsigned short port)
322 {
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 gras_socket_client_from_string(const char *host)
328 {
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 void gras_socket_close_voidp(void *sock) {
336   gras_socket_close((gras_socket_t)sock);
337 }
338
339 /** \brief Close socket */
340 void gras_socket_close(gras_socket_t sock)
341 {
342   xbt_dynar_t sockets =
343     ((gras_trp_procdata_t) gras_libdata_by_id(gras_trp_libdata_id))->sockets;
344   gras_socket_t sock_iter = NULL;
345   unsigned int cursor;
346
347   XBT_IN;
348   VERB1("Close %p", sock);
349   if (sock == _gras_lastly_selected_socket) {
350     xbt_assert0(!gras_opt_trp_nomoredata_on_close || !sock->moredata,
351                 "Closing a socket having more data in buffer while the nomoredata_on_close option is activated");
352
353     if (sock->moredata)
354       CRITICAL0
355         ("Closing a socket having more data in buffer. Option nomoredata_on_close disabled, so continuing.");
356     _gras_lastly_selected_socket = NULL;
357   }
358
359   /* FIXME: Issue an event when the socket is closed */
360   DEBUG1("sockets pointer before %p", sockets);
361   if (sock) {
362     /* FIXME: Cannot get the dynar mutex, because it can be already locked */
363 //              _xbt_dynar_foreach(sockets,cursor,sock_iter) {
364     for (cursor = 0; cursor < xbt_dynar_length(sockets); cursor++) {
365       _xbt_dynar_cursor_get(sockets, cursor, &sock_iter);
366       if (sock == sock_iter) {
367         DEBUG2("remove sock cursor %d dize %lu\n", cursor,
368                xbt_dynar_length(sockets));
369         xbt_dynar_cursor_rm(sockets, &cursor);
370         if (sock->plugin->socket_close)
371           (*sock->plugin->socket_close) (sock);
372
373         /* free the memory */
374         if (sock->peer_name)
375           free(sock->peer_name);
376         free(sock);
377         XBT_OUT;
378         return;
379       }
380     }
381     WARN1("Ignoring request to free an unknown socket (%p). Execution stack:",
382           sock);
383     xbt_backtrace_display_current();
384   }
385   XBT_OUT;
386 }
387
388 /**
389  * gras_trp_send:
390  *
391  * Send a bunch of bytes from on socket
392  * (stable if we know the storage will keep as is until the next trp_flush)
393  */
394 void gras_trp_send(gras_socket_t sd, char *data, long int size, int stable)
395 {
396   xbt_assert0(sd->outgoing, "Socket not suited for data send");
397   (*sd->plugin->send) (sd, data, size, stable);
398 }
399
400 /**
401  * gras_trp_chunk_recv:
402  *
403  * Receive a bunch of bytes from a socket
404  */
405 void gras_trp_recv(gras_socket_t sd, char *data, long int size)
406 {
407   xbt_assert0(sd->incoming, "Socket not suited for data receive");
408   (sd->plugin->recv) (sd, data, size);
409 }
410
411 /**
412  * gras_trp_flush:
413  *
414  * Make sure all pending communications are done
415  */
416 void gras_trp_flush(gras_socket_t sd)
417 {
418   if (sd->plugin->flush)
419     (sd->plugin->flush) (sd);
420 }
421
422 gras_trp_plugin_t gras_trp_plugin_get_by_name(const char *name)
423 {
424   return xbt_dict_get(_gras_trp_plugins, name);
425 }
426
427 int gras_socket_my_port(gras_socket_t sock)
428 {
429   return sock->port;
430 }
431
432 int gras_socket_peer_port(gras_socket_t sock)
433 {
434   return sock->peer_port;
435 }
436
437 char *gras_socket_peer_name(gras_socket_t sock)
438 {
439   return sock->peer_name;
440 }
441
442 char *gras_socket_peer_proc(gras_socket_t sock)
443 {
444   return sock->peer_proc;
445 }
446
447 void gras_socket_peer_proc_set(gras_socket_t sock, char *peer_proc)
448 {
449   sock->peer_proc = peer_proc;
450 }
451
452 /** \brief Check if the provided socket is a measurement one (or a regular one) */
453 int gras_socket_is_meas(gras_socket_t sock)
454 {
455   return sock->meas;
456 }
457
458 /** \brief Send a chunk of (random) data over a measurement socket
459  *
460  * @param peer measurement socket to use for the experiment
461  * @param timeout timeout (in seconds)
462  * @param msg_size size of each chunk sent over the socket (in bytes).
463  * @param msg_amount how many of these packets you want to send.
464  *
465  * Calls to gras_socket_meas_send() and gras_socket_meas_recv() on
466  * each side of the socket should be paired.
467  *
468  * The exchanged data is zeroed to make sure it's initialized, but
469  * there is no way to control what is sent (ie, you cannot use these
470  * functions to exchange data out of band).
471  *
472  * @warning: in SimGrid version 3.1 and previous, the numerical arguments
473  *           were the total amount of data to send and the msg_size. This
474  *           was changed for the fool wanting to send more than MAXINT
475  *           bytes in a fat pipe.
476  */
477 void gras_socket_meas_send(gras_socket_t peer,
478                            unsigned int timeout,
479                            unsigned long int msg_size,
480                            unsigned long int msg_amount)
481 {
482   char *chunk = NULL;
483   unsigned long int sent_sofar;
484
485   XBT_IN;
486
487   if (gras_if_RL())
488     chunk = xbt_malloc0(msg_size);
489
490   xbt_assert0(peer->meas,
491               "Asked to send measurement data on a regular socket");
492   xbt_assert0(peer->outgoing,
493               "Socket not suited for data send (was created with gras_socket_server(), not gras_socket_client())");
494
495   for (sent_sofar = 0; sent_sofar < msg_amount; sent_sofar++) {
496     CDEBUG5(gras_trp_meas,
497             "Sent %lu msgs of %lu (size of each: %ld) to %s:%d", sent_sofar,
498             msg_amount, msg_size, gras_socket_peer_name(peer),
499             gras_socket_peer_port(peer));
500     (*peer->plugin->raw_send) (peer, chunk, msg_size);
501   }
502   CDEBUG5(gras_trp_meas, "Sent %lu msgs of %lu (size of each: %ld) to %s:%d",
503           sent_sofar, msg_amount, msg_size,
504           gras_socket_peer_name(peer), gras_socket_peer_port(peer));
505
506   if (gras_if_RL())
507     free(chunk);
508
509   XBT_OUT;
510 }
511
512 /** \brief Receive a chunk of data over a measurement socket
513  *
514  * Calls to gras_socket_meas_send() and gras_socket_meas_recv() on
515  * each side of the socket should be paired.
516  *
517  * @warning: in SimGrid version 3.1 and previous, the numerical arguments
518  *           were the total amount of data to send and the msg_size. This
519  *           was changed for the fool wanting to send more than MAXINT
520  *           bytes in a fat pipe.
521  */
522 void gras_socket_meas_recv(gras_socket_t peer,
523                            unsigned int timeout,
524                            unsigned long int msg_size,
525                            unsigned long int msg_amount)
526 {
527
528   char *chunk = NULL;
529   unsigned long int got_sofar;
530
531   XBT_IN;
532
533   if (gras_if_RL())
534     chunk = xbt_malloc(msg_size);
535
536   xbt_assert0(peer->meas,
537               "Asked to receive measurement data on a regular socket");
538   xbt_assert0(peer->incoming, "Socket not suited for data receive");
539
540   for (got_sofar = 0; got_sofar < msg_amount; got_sofar++) {
541     CDEBUG5(gras_trp_meas,
542             "Recvd %ld msgs of %lu (size of each: %ld) from %s:%d", got_sofar,
543             msg_amount, msg_size, gras_socket_peer_name(peer),
544             gras_socket_peer_port(peer));
545     (peer->plugin->raw_recv) (peer, chunk, msg_size);
546   }
547   CDEBUG5(gras_trp_meas,
548           "Recvd %ld msgs of %lu (size of each: %ld) from %s:%d", got_sofar,
549           msg_amount, msg_size, gras_socket_peer_name(peer),
550           gras_socket_peer_port(peer));
551
552   if (gras_if_RL())
553     free(chunk);
554   XBT_OUT;
555 }
556
557 /**
558  * \brief Something similar to the good old accept system call.
559  *
560  * Make sure that there is someone speaking to the provided server socket.
561  * In RL, it does an accept(2) and return the result as last argument.
562  * In SG, as accepts are useless, it returns the provided argument as result.
563  * You should thus test whether (peer != accepted) before closing both of them.
564  *
565  * You should only call this on measurement sockets. It is automatically
566  * done for regular sockets, but you usually want more control about
567  * what's going on with measurement sockets.
568  */
569 gras_socket_t gras_socket_meas_accept(gras_socket_t peer)
570 {
571   gras_socket_t res;
572
573   xbt_assert0(peer->meas,
574               "No need to accept on non-measurement sockets (it's automatic)");
575
576   if (!peer->accepting) {
577     /* nothing to accept here (must be in SG) */
578     /* BUG: FIXME: this is BAD! it makes tricky to free the accepted socket */
579     return peer;
580   }
581
582   res = (peer->plugin->socket_accept) (peer);
583   res->meas = peer->meas;
584   CDEBUG1(gras_trp_meas, "meas_accepted onto %d", res->sd);
585
586   return res;
587 }
588
589
590 /*
591  * Creating procdata for this module
592  */
593 static void *gras_trp_procdata_new(void)
594 {
595   gras_trp_procdata_t res = xbt_new(s_gras_trp_procdata_t, 1);
596
597   res->name = xbt_strdup("gras_trp");
598   res->name_len = 0;
599   res->sockets = xbt_dynar_new_sync(sizeof(gras_socket_t *), NULL);
600   res->myport = 0;
601
602   return (void *) res;
603 }
604
605 /*
606  * Freeing procdata for this module
607  */
608 static void gras_trp_procdata_free(void *data)
609 {
610   gras_trp_procdata_t res = (gras_trp_procdata_t) data;
611
612   xbt_dynar_free(&(res->sockets));
613   free(res->name);
614   free(res);
615 }
616
617 void gras_trp_socketset_dump(const char *name)
618 {
619   gras_trp_procdata_t procdata =
620     (gras_trp_procdata_t) gras_libdata_by_id(gras_trp_libdata_id);
621
622   unsigned int it;
623   gras_socket_t s;
624
625   INFO1("** Dump the socket set %s", name);
626   xbt_dynar_foreach(procdata->sockets, it, s) {
627     INFO4("  %p -> %s:%d %s",
628           s, gras_socket_peer_name(s), gras_socket_peer_port(s),
629           s->valid ? "(valid)" : "(peer dead)");
630   }
631   INFO1("** End of socket set %s", name);
632 }
633
634 /*
635  * Module registration
636  */
637 int gras_trp_libdata_id;
638 void gras_trp_register()
639 {
640   gras_trp_libdata_id =
641     gras_procdata_add("gras_trp", gras_trp_procdata_new,
642                       gras_trp_procdata_free);
643 }
644
645 int gras_os_myport(void)
646 {
647   return ((gras_trp_procdata_t)
648           gras_libdata_by_id(gras_trp_libdata_id))->myport;
649 }