-LCFContext
[oweals/gnunet.git] / src / testbed / testbed_api.c
1 /*
2       This file is part of GNUnet
3       (C) 2008--2012 Christian Grothoff (and other contributing authors)
4
5       GNUnet is free software; you can redistribute it and/or modify
6       it under the terms of the GNU General Public License as published
7       by the Free Software Foundation; either version 3, or (at your
8       option) any later version.
9
10       GNUnet is distributed in the hope that it will be useful, but
11       WITHOUT ANY WARRANTY; without even the implied warranty of
12       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13       General Public License for more details.
14
15       You should have received a copy of the GNU General Public License
16       along with GNUnet; see the file COPYING.  If not, write to the
17       Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18       Boston, MA 02111-1307, USA.
19  */
20
21 /**
22  * @file testbed/testbed_api.c
23  * @brief API for accessing the GNUnet testing service.
24  *        This library is supposed to make it easier to write
25  *        testcases and script large-scale benchmarks.
26  * @author Christian Grothoff
27  */
28 #include "platform.h"
29 #include "gnunet_testbed_service.h"
30 #include "gnunet_core_service.h"
31 #include "gnunet_constants.h"
32 #include "gnunet_transport_service.h"
33 #include "gnunet_hello_lib.h"
34 #include <zlib.h>
35
36 #include "testbed.h"
37 #include "testbed_api_hosts.h"
38
39 /**
40  * Generic logging shorthand
41  */
42 #define LOG(kind, ...)                          \
43   GNUNET_log_from (kind, "testbed-api", __VA_ARGS__);
44
45 /**
46  * Debug logging
47  */
48 #define LOG_DEBUG(...)                          \
49   LOG (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__);
50
51
52 /**
53  * The message queue for sending messages to the controller service
54  */
55 struct MessageQueue
56 {
57   /**
58    * The message to be sent
59    */
60   struct GNUNET_MessageHeader *msg;
61
62   /**
63    * next pointer for DLL
64    */
65   struct MessageQueue *next;
66   
67   /**
68    * prev pointer for DLL
69    */
70   struct MessageQueue *prev;
71 };
72
73
74 /**
75  * Structure for a controller link
76  */
77 struct ControllerLink
78 {
79   /**
80    * The next ptr for DLL
81    */
82   struct ControllerLink *next;
83
84   /**
85    * The prev ptr for DLL
86    */
87   struct ControllerLink *prev;
88
89   /**
90    * The host which will be referred in the peer start request. This is the
91    * host where the peer should be started
92    */
93   struct GNUNET_TESTBED_Host *delegated_host;
94
95   /**
96    * The host which will contacted to delegate the peer start request
97    */
98   struct GNUNET_TESTBED_Host *slave_host;
99
100   /**
101    * The configuration to be used to connect to slave host
102    */
103   const struct GNUNET_CONFIGURATION_Handle *slave_cfg;
104
105   /**
106    * GNUNET_YES if the slave should be started (and stopped) by us; GNUNET_NO
107    * if we are just allowed to use the slave via TCP/IP
108    */
109   int is_subordinate;
110 };
111
112
113 /**
114  * Handle to interact with a GNUnet testbed controller.  Each
115  * controller has at least one master handle which is created when the
116  * controller is created; this master handle interacts with the
117  * controller process, destroying it destroys the controller (by
118  * closing stdin of the controller process).  Additionally,
119  * controllers can interact with each other (in a P2P fashion); those
120  * links are established via TCP/IP on the controller's service port.
121  */
122 struct GNUNET_TESTBED_Controller
123 {
124
125   /**
126    * The host where the controller is running
127    */
128   const struct GNUNET_TESTBED_Host *host;
129
130   /**
131    * The helper handle
132    */
133   struct GNUNET_TESTBED_HelperHandle *helper;
134
135   /**
136    * The controller callback
137    */
138   GNUNET_TESTBED_ControllerCallback cc;
139
140   /**
141    * The closure for controller callback
142    */
143   void *cc_cls;
144
145   /**
146    * The configuration to use while connecting to controller
147    */
148   struct GNUNET_CONFIGURATION_Handle *cfg;
149
150   /**
151    * The client connection handle to the controller service
152    */
153   struct GNUNET_CLIENT_Connection *client;
154   
155   /**
156    * The head of the message queue
157    */
158   struct MessageQueue *mq_head;
159
160   /**
161    * The tail of the message queue
162    */
163   struct MessageQueue *mq_tail;
164
165   /**
166    * The head of the ControllerLink list
167    */
168   struct ControllerLink *cl_head;
169
170   /**
171    * The tail of the ControllerLink list
172    */
173   struct ControllerLink *cl_tail;
174
175   /**
176    * The client transmit handle
177    */
178   struct GNUNET_CLIENT_TransmitHandle *th;
179
180   /**
181    * The host registration handle; NULL if no current registration requests are
182    * present 
183    */
184   struct GNUNET_TESTBED_HostRegistrationHandle *rh;
185
186   /**
187    * The controller event mask
188    */
189   uint64_t event_mask;
190
191   /**
192    * Did we start the receive loop yet?
193    */
194   int in_receive;
195 };
196
197
198 /**
199  * handle for host registration
200  */
201 struct GNUNET_TESTBED_HostRegistrationHandle
202 {
203   /**
204    * The host being registered
205    */
206   struct GNUNET_TESTBED_Host *host;
207
208   /**
209    * The controller at which this host is being registered
210    */
211   struct GNUNET_TESTBED_Controller *c;
212
213   /**
214    * The Registartion completion callback
215    */
216   GNUNET_TESTBED_HostRegistrationCompletion cc;
217
218   /**
219    * The closure for above callback
220    */
221   void *cc_cls;
222 };
223
224
225 /**
226  * Handler for GNUNET_MESSAGE_TYPE_TESTBED_ADDHOSTCONFIRM message from
227  * controller (testbed service)
228  *
229  * @param c the controller handler
230  * @param msg message received
231  * @return GNUNET_YES if we can continue receiving from service; GNUNET_NO if
232  *           not
233  */
234 static int
235 handle_addhostconfirm (struct GNUNET_TESTBED_Controller *c,
236                        const struct GNUNET_TESTBED_HostConfirmedMessage *msg)
237 {
238   struct GNUNET_TESTBED_HostRegistrationHandle *rh;
239   char *emsg;
240   uint16_t msg_size;
241
242   rh = c->rh;
243   if (NULL == rh)
244   {  
245     return GNUNET_OK;    
246   }
247   if (GNUNET_TESTBED_host_get_id_ (rh->host) != ntohl (msg->host_id))
248   {
249     LOG_DEBUG ("Mismatch in host id's %u, %u of host confirm msg\n",
250                GNUNET_TESTBED_host_get_id_ (rh->host), ntohl (msg->host_id));
251     return GNUNET_OK;
252   }
253   c->rh = NULL;
254   msg_size = ntohs (msg->header.size);
255   if (sizeof (struct GNUNET_TESTBED_HostConfirmedMessage) == msg_size)
256   {
257     LOG_DEBUG ("Host %u successfully registered\n", ntohl (msg->host_id));
258     GNUNET_TESTBED_mark_host_registered_at_  (rh->host, c);
259     rh->cc (rh->cc_cls, NULL);
260     GNUNET_free (rh);
261     return GNUNET_OK;
262   } 
263   /* We have an error message */
264   emsg = (char *) &msg[1];
265   if ('\0' != emsg[msg_size - 
266                    sizeof (struct GNUNET_TESTBED_HostConfirmedMessage)])
267   {
268     GNUNET_break (0);
269     GNUNET_free (rh);
270     return GNUNET_NO;
271   }  
272   LOG (GNUNET_ERROR_TYPE_ERROR, _("Adding host %u failed with error: %s\n"),
273        ntohl (msg->host_id), emsg);
274   rh->cc (rh->cc_cls, emsg);
275   GNUNET_free (rh);
276   return GNUNET_OK;
277 }
278
279
280 /**
281  * Handler for messages from controller (testbed service)
282  *
283  * @param cls the controller handler
284  * @param msg message received, NULL on timeout or fatal error
285  */
286 static void 
287 message_handler (void *cls, const struct GNUNET_MessageHeader *msg)
288 {
289   struct GNUNET_TESTBED_Controller *c = cls;  
290   int status;
291
292   /* FIXME: Add checks for message integrity */
293   if (NULL == msg)
294   {
295     LOG_DEBUG ("Receive timed out or connection to service dropped\n");
296     return;
297   }
298   status = GNUNET_OK;
299   switch (ntohs (msg->type))
300   {
301   case GNUNET_MESSAGE_TYPE_TESTBED_ADDHOSTCONFIRM:
302     status =
303       handle_addhostconfirm (c, (const struct
304                                  GNUNET_TESTBED_HostConfirmedMessage *) msg);   
305     break;
306   default:
307     GNUNET_break (0);
308   }
309   if (GNUNET_OK == status)
310     GNUNET_CLIENT_receive (c->client, &message_handler, c,
311                            GNUNET_TIME_UNIT_FOREVER_REL);
312 }
313
314
315 /**
316  * Function called to notify a client about the connection begin ready to queue
317  * more data.  "buf" will be NULL and "size" zero if the connection was closed
318  * for writing in the meantime.
319  *
320  * @param cls closure
321  * @param size number of bytes available in buf
322  * @param buf where the callee should write the message
323  * @return number of bytes written to buf
324  */
325 static size_t
326 transmit_ready_notify (void *cls, size_t size, void *buf)
327 {
328   struct GNUNET_TESTBED_Controller *c = cls;
329   struct MessageQueue *mq_entry;
330
331   c->th = NULL;
332   mq_entry = c->mq_head;
333   GNUNET_assert (NULL != mq_entry);
334   GNUNET_assert (ntohs (mq_entry->msg->size) <= size);
335   size = ntohs (mq_entry->msg->size);
336   memcpy (buf, mq_entry->msg, size);
337   GNUNET_free (mq_entry->msg);
338   GNUNET_CONTAINER_DLL_remove (c->mq_head, c->mq_tail, mq_entry);
339   GNUNET_free (mq_entry);
340   mq_entry = c->mq_head;
341   if (NULL != mq_entry)
342     c->th = 
343       GNUNET_CLIENT_notify_transmit_ready (c->client,
344                                            ntohs (mq_entry->msg->size),
345                                            GNUNET_TIME_UNIT_FOREVER_REL,
346                                            GNUNET_NO, &transmit_ready_notify,
347                                            c);
348   if ( (GNUNET_NO == c->in_receive) &&
349        (size > 0) )
350   {
351     c->in_receive = GNUNET_YES;
352     GNUNET_CLIENT_receive (c->client, &message_handler, c,
353                            GNUNET_TIME_UNIT_FOREVER_REL);
354   }
355   return size;
356 }
357
358
359 /**
360  * Queues a message in send queue for sending to the service
361  *
362  * @param controller the handle to the controller
363  * @param msg the message to queue
364  */
365 static void
366 queue_message (struct GNUNET_TESTBED_Controller *controller,
367                struct GNUNET_MessageHeader *msg)
368 {
369   struct MessageQueue *mq_entry;
370   uint16_t type;
371   uint16_t size;
372
373   type = ntohs (msg->type);
374   size = ntohs (msg->size);
375   GNUNET_assert ((GNUNET_MESSAGE_TYPE_TESTBED_INIT <= type) &&
376                  (GNUNET_MESSAGE_TYPE_TESTBED_MAX > type));                 
377   mq_entry = GNUNET_malloc (sizeof (struct MessageQueue));
378   mq_entry->msg = msg;
379   LOG (GNUNET_ERROR_TYPE_DEBUG,
380        "Queueing message of type %u, size %u for sending\n", type,
381        ntohs (msg->size));
382   GNUNET_CONTAINER_DLL_insert_tail (controller->mq_head, controller->mq_tail,
383                                     mq_entry);
384   if (NULL == controller->th)
385     controller->th = 
386       GNUNET_CLIENT_notify_transmit_ready (controller->client, size,
387                                            GNUNET_TIME_UNIT_FOREVER_REL,
388                                            GNUNET_NO, &transmit_ready_notify,
389                                            controller);
390 }
391
392
393 /**
394  * Start a controller process using the given configuration at the
395  * given host.
396  *
397  * @param cfg configuration to use
398  * @param host host to run the controller on, NULL for 'localhost'
399  * @param event_mask bit mask with set of events to call 'cc' for;
400  *                   or-ed values of "1LL" shifted by the
401  *                   respective 'enum GNUNET_TESTBED_EventType'
402  *                   (i.e.  "(1LL << GNUNET_TESTBED_ET_CONNECT) | ...")
403  * @param cc controller callback to invoke on events
404  * @param cc_cls closure for cc
405  * @return handle to the controller
406  */
407 struct GNUNET_TESTBED_Controller *
408 GNUNET_TESTBED_controller_start (const struct GNUNET_CONFIGURATION_Handle *cfg,
409                                  struct GNUNET_TESTBED_Host *host,
410                                  uint64_t event_mask,
411                                  GNUNET_TESTBED_ControllerCallback cc,
412                                  void *cc_cls)
413 {
414   struct GNUNET_TESTBED_Controller *controller;
415   char * const binary_argv[] = {
416     "gnunet-service-testbed",
417     "gnunet-service-testbed",
418     NULL
419   };
420   struct GNUNET_TESTBED_InitMessage *msg;
421
422   controller = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_Controller));
423   controller->helper = GNUNET_TESTBED_host_run_ (host, binary_argv);
424   if (NULL == controller->helper)
425   {
426     GNUNET_free (controller);
427     return NULL;
428   }
429   controller->host = host;
430   controller->cc = cc;
431   controller->cc_cls = cc_cls;
432   controller->event_mask = event_mask;
433   controller->cfg = GNUNET_CONFIGURATION_dup (cfg);
434   controller->client = GNUNET_CLIENT_connect ("testbed", controller->cfg);
435   if (NULL == controller->client)
436   {
437     GNUNET_TESTBED_controller_stop (controller);
438     return NULL;
439   }  
440   msg = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_InitMessage));
441   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_INIT);
442   msg->header.size = htons (sizeof (struct GNUNET_TESTBED_InitMessage));
443   msg->host_id = htonl (GNUNET_TESTBED_host_get_id_ (controller->host));
444   msg->event_mask = GNUNET_htonll (controller->event_mask);
445   queue_message (controller, (struct GNUNET_MessageHeader *) msg);
446   return controller;
447 }
448
449
450 /**
451  * Configure shared services at a controller.  Using this function,
452  * you can specify that certain services (such as "resolver")
453  * should not be run for each peer but instead be shared
454  * across N peers on the specified host.  This function
455  * must be called before any peers are created at the host.
456  * 
457  * @param controller controller to configure
458  * @param service_name name of the service to share
459  * @param num_peers number of peers that should share one instance
460  *        of the specified service (1 for no sharing is the default),
461  *        use 0 to disable the service
462  */
463 void
464 GNUNET_TESTBED_controller_configure_sharing (struct GNUNET_TESTBED_Controller *controller,
465                                              const char *service_name,
466                                              uint32_t num_peers)
467 {
468   struct GNUNET_TESTBED_ConfigureSharedServiceMessage *msg;
469   uint16_t service_name_size;
470   uint16_t msg_size;
471   
472   service_name_size = strlen (service_name) + 1;
473   msg_size = sizeof (struct GNUNET_TESTBED_ConfigureSharedServiceMessage)
474     + service_name_size;
475   msg = GNUNET_malloc (msg_size);
476   msg->header.size = htons (msg_size);
477   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_SERVICESHARE);
478   msg->host_id = htonl (GNUNET_TESTBED_host_get_id_ (controller->host));
479   msg->num_peers = htonl (num_peers);
480   memcpy (&msg[1], service_name, service_name_size);
481   queue_message (controller, (struct GNUNET_MessageHeader *) msg);
482 }
483
484
485 /**
486  * Stop the given controller (also will terminate all peers and
487  * controllers dependent on this controller).  This function 
488  * blocks until the testbed has been fully terminated (!).
489  *
490  * @param controller handle to controller to stop
491  */
492 void
493 GNUNET_TESTBED_controller_stop (struct GNUNET_TESTBED_Controller *controller)
494 {
495   struct MessageQueue *mq_entry;
496
497   if (NULL != controller->th)
498     GNUNET_CLIENT_notify_transmit_ready_cancel (controller->th);
499  /* Clear the message queue */
500   while (NULL != (mq_entry = controller->mq_head))
501   {
502     GNUNET_CONTAINER_DLL_remove (controller->mq_head,
503                                  controller->mq_tail,
504                                  mq_entry);
505     GNUNET_free (mq_entry->msg);
506     GNUNET_free (mq_entry);
507   }
508   if (NULL != controller->client)
509     GNUNET_CLIENT_disconnect (controller->client);
510   GNUNET_TESTBED_host_stop_ (controller->helper);
511   GNUNET_CONFIGURATION_destroy (controller->cfg);
512   GNUNET_free (controller);
513 }
514
515
516 /**
517  * Register a host with the controller
518  *
519  * @param controller the controller handle
520  * @param host the host to register
521  * @param cc the completion callback to call to inform the status of
522  *          registration. After calling this callback the registration handle
523  *          will be invalid. Cannot be NULL.
524  * @param cc_cls the closure for the cc
525  * @return handle to the host registration which can be used to cancel the
526  *           registration 
527  */
528 struct GNUNET_TESTBED_HostRegistrationHandle *
529 GNUNET_TESTBED_register_host (struct GNUNET_TESTBED_Controller *controller,
530                               struct GNUNET_TESTBED_Host *host,
531                               GNUNET_TESTBED_HostRegistrationCompletion cc,
532                               void *cc_cls)
533 {
534   struct GNUNET_TESTBED_HostRegistrationHandle *rh;
535   struct GNUNET_TESTBED_AddHostMessage *msg;
536   const char *username;
537   const char *hostname;
538   uint16_t msg_size;
539   uint16_t user_name_length;
540
541   if (NULL != controller->rh)
542     return NULL;
543   hostname = GNUNET_TESTBED_host_get_hostname_ (host);
544   if (GNUNET_YES == GNUNET_TESTBED_is_host_registered_ (host, controller))
545   {
546     LOG (GNUNET_ERROR_TYPE_WARNING,
547          "Host hostname: %s already registered\n",
548          (NULL == hostname) ? "localhost" : hostname);
549     return NULL;
550   }  
551   rh = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_HostRegistrationHandle));
552   rh->host = host;
553   rh->c = controller;
554   GNUNET_assert (NULL != cc);
555   rh->cc = cc;
556   rh->cc_cls = cc_cls;
557   controller->rh = rh;
558   username = GNUNET_TESTBED_host_get_username_ (host);
559   msg_size = (sizeof (struct GNUNET_TESTBED_AddHostMessage));
560   user_name_length = 0;
561   if (NULL != username)
562   {
563     user_name_length = strlen (username) + 1;
564     msg_size += user_name_length;
565   }
566   /* FIXME: what happens when hostname is NULL? localhost */
567   GNUNET_assert (NULL != hostname);
568   msg_size += strlen (hostname) + 1;
569   msg = GNUNET_malloc (msg_size);
570   msg->header.size = htons (msg_size);
571   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_ADDHOST);
572   msg->host_id = htonl (GNUNET_TESTBED_host_get_id_ (host));
573   msg->ssh_port = htons (GNUNET_TESTBED_host_get_ssh_port_ (host));
574   msg->user_name_length = htons (user_name_length);
575   if (NULL != username)
576     memcpy (&msg[1], username, user_name_length);
577   strcpy (((void *) msg) + user_name_length, hostname);
578   queue_message (controller, (struct GNUNET_MessageHeader *) msg);
579   return rh;
580 }
581
582
583 /**
584  * Cancel the pending registration. Note that if the registration message is
585  * already sent to the service the cancellation has only the effect that the
586  * registration completion callback for the registration is never called.
587  *
588  * @param handle the registration handle to cancel
589  */
590 void
591 GNUNET_TESTBED_cancel_registration (struct GNUNET_TESTBED_HostRegistrationHandle
592                                     *handle)
593 {
594   if (handle != handle->c->rh)
595   {
596     GNUNET_break (0);
597     return;
598   }
599   handle->c->rh = NULL;
600   GNUNET_free (handle);  
601 }
602
603
604 /**
605  * Create a link from a 'master' controller to a slave controller.
606  * Whenever the master controller is asked to start a peer at the
607  * given 'delegated_host', it will delegate the request to the
608  * specified slave controller.  Note that the slave controller runs at
609  * the 'slave_host', which may or may not be the same host as the
610  * 'delegated_host' (for hierarchical delegations).  The configuration
611  * of the slave controller is given and to be used to either create
612  * the slave controller or to connect to an existing slave controller
613  * process.  'is_subordinate' specifies if the given slave controller
614  * should be started and managed by the master controller, or if the
615  * slave already has a master and this is just a secondary master that
616  * is also allowed to use the existing slave.
617  *
618  * @param master handle to the master controller who creates the association
619  * @param delegated_host requests to which host should be delegated
620  * @param slave_host which host is used to run the slave controller 
621  * @param slave_cfg configuration to use for the slave controller
622  * @param is_subordinate GNUNET_YES if the slave should be started (and stopped)
623  *                       by the master controller; GNUNET_NO if we are just
624  *                       allowed to use the slave via TCP/IP
625  */
626 void
627 GNUNET_TESTBED_controller_link (struct GNUNET_TESTBED_Controller *master,
628                                 struct GNUNET_TESTBED_Host *delegated_host,
629                                 struct GNUNET_TESTBED_Host *slave_host,
630                                 const struct GNUNET_CONFIGURATION_Handle *slave_cfg,
631                                 int is_subordinate)
632 {
633   struct GNUNET_TESTBED_ControllerLinkMessage *msg;
634   char *config;
635   Bytef *cconfig;
636   uLongf cc_size;
637   size_t config_size;  
638   uint16_t msg_size;
639
640   GNUNET_assert (GNUNET_YES == 
641                  GNUNET_TESTBED_is_host_registered_ (delegated_host, master));
642   GNUNET_assert (GNUNET_YES == 
643                  GNUNET_TESTBED_is_host_registered_ (slave_host, master));
644   config = GNUNET_CONFIGURATION_serialize (slave_cfg, &config_size);
645   cc_size = compressBound ((uLong) config_size);
646   cconfig = GNUNET_malloc (cc_size);
647   GNUNET_assert (Z_OK ==
648                  compress2 (cconfig, &cc_size, 
649                             (Bytef *) config, config_size, Z_BEST_SPEED));
650   GNUNET_free (config);
651   GNUNET_assert ((UINT16_MAX -
652                   sizeof (struct GNUNET_TESTBED_ControllerLinkMessage))
653                   >= cc_size); /* Configuration doesn't fit in 1 message */
654   msg_size = cc_size + sizeof (struct GNUNET_TESTBED_ControllerLinkMessage);
655   msg = GNUNET_realloc (cconfig, msg_size);
656   memmove (msg + sizeof (struct GNUNET_TESTBED_ControllerLinkMessage),
657            msg, cc_size);
658   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_LCONTROLLERS);
659   msg->header.size = htons (msg_size);
660   msg->delegated_host_id = htonl (GNUNET_TESTBED_host_get_id_ (delegated_host));
661   msg->slave_host_id = htonl (GNUNET_TESTBED_host_get_id_ (slave_host));
662   msg->config_size = htons ((uint16_t) config_size);
663   msg->is_subordinate = (GNUNET_YES == is_subordinate) ? 1 : 0;
664   queue_message (master, (struct GNUNET_MessageHeader *) msg);
665 }
666
667
668 /**
669  * Ask the testbed controller to write the current overlay topology to
670  * a file.  Naturally, the file will only contain a snapshot as the
671  * topology may evolve all the time.
672  *
673  * @param controller overlay controller to inspect
674  * @param filename name of the file the topology should
675  *        be written to.
676  */
677 void
678 GNUNET_TESTBED_overlay_write_topology_to_file (struct GNUNET_TESTBED_Controller *controller,
679                                                const char *filename)
680 {
681   GNUNET_break (0);
682 }
683
684
685
686 /* end of testbed_api.c */