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