Logo AND Algorithmique Numérique Distribuée

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