Logo AND Algorithmique Numérique Distribuée

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