implemented controller error callback
[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  * @author Sree Harsha Totakura
28  */
29
30
31 #include "platform.h"
32 #include "gnunet_testbed_service.h"
33 #include "gnunet_core_service.h"
34 #include "gnunet_constants.h"
35 #include "gnunet_transport_service.h"
36 #include "gnunet_hello_lib.h"
37 #include <zlib.h>
38
39 #include "testbed.h"
40 #include "testbed_api.h"
41 #include "testbed_api_hosts.h"
42 #include "testbed_api_peers.h"
43
44 /**
45  * Generic logging shorthand
46  */
47 #define LOG(kind, ...)                          \
48   GNUNET_log_from (kind, "testbed-api", __VA_ARGS__);
49
50 /**
51  * Debug logging
52  */
53 #define LOG_DEBUG(...)                          \
54   LOG (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__);
55
56 /**
57  * Relative time seconds shorthand
58  */
59 #define TIME_REL_SECS(sec) \
60   GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, sec)
61
62
63 /**
64  * Default server message sending retry timeout
65  */
66 #define TIMEOUT_REL TIME_REL_SECS(1)
67
68
69 /**
70  * The message queue for sending messages to the controller service
71  */
72 struct MessageQueue
73 {
74   /**
75    * The message to be sent
76    */
77   struct GNUNET_MessageHeader *msg;
78
79   /**
80    * next pointer for DLL
81    */
82   struct MessageQueue *next;
83   
84   /**
85    * prev pointer for DLL
86    */
87   struct MessageQueue *prev;
88 };
89
90
91 /**
92  * Structure for a controller link
93  */
94 struct ControllerLink
95 {
96   /**
97    * The next ptr for DLL
98    */
99   struct ControllerLink *next;
100
101   /**
102    * The prev ptr for DLL
103    */
104   struct ControllerLink *prev;
105
106   /**
107    * The host which will be referred in the peer start request. This is the
108    * host where the peer should be started
109    */
110   struct GNUNET_TESTBED_Host *delegated_host;
111
112   /**
113    * The host which will contacted to delegate the peer start request
114    */
115   struct GNUNET_TESTBED_Host *slave_host;
116
117   /**
118    * The configuration to be used to connect to slave host
119    */
120   const struct GNUNET_CONFIGURATION_Handle *slave_cfg;
121
122   /**
123    * GNUNET_YES if the slave should be started (and stopped) by us; GNUNET_NO
124    * if we are just allowed to use the slave via TCP/IP
125    */
126   int is_subordinate;
127 };
128
129
130 /**
131  * handle for host registration
132  */
133 struct GNUNET_TESTBED_HostRegistrationHandle
134 {
135   /**
136    * The host being registered
137    */
138   struct GNUNET_TESTBED_Host *host;
139
140   /**
141    * The controller at which this host is being registered
142    */
143   struct GNUNET_TESTBED_Controller *c;
144
145   /**
146    * The Registartion completion callback
147    */
148   GNUNET_TESTBED_HostRegistrationCompletion cc;
149
150   /**
151    * The closure for above callback
152    */
153   void *cc_cls;
154 };
155
156
157 /**
158  * Handler for GNUNET_MESSAGE_TYPE_TESTBED_ADDHOSTCONFIRM message from
159  * controller (testbed service)
160  *
161  * @param c the controller handler
162  * @param msg message received
163  * @return GNUNET_YES if we can continue receiving from service; GNUNET_NO if
164  *           not
165  */
166 static int
167 handle_addhostconfirm (struct GNUNET_TESTBED_Controller *c,
168                        const struct GNUNET_TESTBED_HostConfirmedMessage *msg)
169 {
170   struct GNUNET_TESTBED_HostRegistrationHandle *rh;
171   char *emsg;
172   uint16_t msg_size;
173
174   rh = c->rh;
175   if (NULL == rh)
176   {  
177     return GNUNET_OK;    
178   }
179   if (GNUNET_TESTBED_host_get_id_ (rh->host) != ntohl (msg->host_id))
180   {
181     LOG_DEBUG ("Mismatch in host id's %u, %u of host confirm msg\n",
182                GNUNET_TESTBED_host_get_id_ (rh->host), ntohl (msg->host_id));
183     return GNUNET_OK;
184   }
185   c->rh = NULL;
186   msg_size = ntohs (msg->header.size);
187   if (sizeof (struct GNUNET_TESTBED_HostConfirmedMessage) == msg_size)
188   {
189     LOG_DEBUG ("Host %u successfully registered\n", ntohl (msg->host_id));
190     GNUNET_TESTBED_mark_host_registered_at_  (rh->host, c);
191     rh->cc (rh->cc_cls, NULL);
192     GNUNET_free (rh);
193     return GNUNET_OK;
194   } 
195   /* We have an error message */
196   emsg = (char *) &msg[1];
197   if ('\0' != emsg[msg_size - 
198                    sizeof (struct GNUNET_TESTBED_HostConfirmedMessage)])
199   {
200     GNUNET_break (0);
201     GNUNET_free (rh);
202     return GNUNET_NO;
203   }  
204   LOG (GNUNET_ERROR_TYPE_ERROR, _("Adding host %u failed with error: %s\n"),
205        ntohl (msg->host_id), emsg);
206   rh->cc (rh->cc_cls, emsg);
207   GNUNET_free (rh);
208   return GNUNET_OK;
209 }
210
211
212 /**
213  * Handler for GNUNET_MESSAGE_TYPE_TESTBED_ADDHOSTCONFIRM message from
214  * controller (testbed service)
215  *
216  * @param c the controller handler
217  * @param msg message received
218  * @return GNUNET_YES if we can continue receiving from service; GNUNET_NO if
219  *           not
220  */
221 static int
222 handle_opsuccess (struct GNUNET_TESTBED_Controller *c,
223                   const struct
224                   GNUNET_TESTBED_GenericOperationSuccessEventMessage *msg)
225 {
226   struct GNUNET_TESTBED_Operation *op;
227   struct GNUNET_TESTBED_EventInformation *event;
228   uint64_t op_id;
229   
230   op_id = GNUNET_ntohll (msg->operation_id);
231   LOG_DEBUG ("Operation %ul successful\n", op_id);
232   for (op = c->op_head; NULL != op; op = op->next)
233   {
234     if (op->operation_id == op_id)
235       break;
236   }
237   if (NULL == op)
238   {
239     LOG_DEBUG ("Operation not found\n");
240     return GNUNET_YES;
241   }
242   event = NULL;
243   if (0 != (c->event_mask & (1L << GNUNET_TESTBED_ET_OPERATION_FINISHED)))
244     event = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_EventInformation));
245   if (NULL != event)
246     event->type = GNUNET_TESTBED_ET_OPERATION_FINISHED; 
247   switch (op->type)
248   {
249   case OP_PEER_DESTROY:
250     {
251       struct PeerDestroyData *data;
252       
253       if (NULL != event)
254       {
255         event->details.operation_finished.operation = op;
256         event->details.operation_finished.op_cls = NULL;
257         event->details.operation_finished.emsg = NULL;
258         event->details.operation_finished.pit = GNUNET_TESTBED_PIT_GENERIC;
259         event->details.operation_finished.op_result.generic = NULL;
260       }
261       data = (struct PeerDestroyData *) op->data;
262       if (NULL != data->peer->details)
263       {
264         if (NULL != data->peer->details->cfg)
265           GNUNET_CONFIGURATION_destroy (data->peer->details->cfg);
266         //PEER_DETAILS
267       }
268       GNUNET_free (data->peer);
269       GNUNET_free (data);
270       //PEERDESTROYDATA
271     }
272     break;
273   default:
274     GNUNET_break (0);
275   }
276   if (NULL != event)
277   {
278     if (NULL != c->cc)
279       c->cc (c->cc_cls, event);
280     GNUNET_free (event);
281   }
282   GNUNET_CONTAINER_DLL_remove (c->op_head, c->op_tail, op);
283   GNUNET_free (op);
284   return GNUNET_YES;  
285 }
286
287
288 /**
289  * Handler for messages from controller (testbed service)
290  *
291  * @param cls the controller handler
292  * @param msg message received, NULL on timeout or fatal error
293  */
294 static void 
295 message_handler (void *cls, const struct GNUNET_MessageHeader *msg)
296 {
297   struct GNUNET_TESTBED_Controller *c = cls;  
298   int status;
299
300   c->in_receive = GNUNET_NO;
301   /* FIXME: Add checks for message integrity */
302   if (NULL == msg)
303   {
304     LOG_DEBUG ("Receive timed out or connection to service dropped\n");
305     return;
306   }
307   status = GNUNET_OK;
308   switch (ntohs (msg->type))
309   {
310   case GNUNET_MESSAGE_TYPE_TESTBED_ADDHOSTCONFIRM:
311     status =
312       handle_addhostconfirm (c, (const struct
313                                  GNUNET_TESTBED_HostConfirmedMessage *) msg);
314     break;
315   case GNUNET_MESSAGE_TYPE_TESTBED_GENERICOPSUCCESS:
316     status =
317       handle_opsuccess (c, (const struct
318                             GNUNET_TESTBED_GenericOperationSuccessEventMessage
319                             *) msg);
320     break;
321   default:
322     GNUNET_break (0);
323   }
324   if ((GNUNET_OK == status) && (GNUNET_NO == c->in_receive))
325   {
326     c->in_receive = GNUNET_YES;
327     GNUNET_CLIENT_receive (c->client, &message_handler, c,
328                            GNUNET_TIME_UNIT_FOREVER_REL);    
329   }
330 }
331
332
333 /**
334  * Function called to notify a client about the connection begin ready to queue
335  * more data.  "buf" will be NULL and "size" zero if the connection was closed
336  * for writing in the meantime.
337  *
338  * @param cls closure
339  * @param size number of bytes available in buf
340  * @param buf where the callee should write the message
341  * @return number of bytes written to buf
342  */
343 static size_t
344 transmit_ready_notify (void *cls, size_t size, void *buf)
345 {
346   struct GNUNET_TESTBED_Controller *c = cls;
347   struct MessageQueue *mq_entry;
348
349   c->th = NULL;
350   mq_entry = c->mq_head;
351   GNUNET_assert (NULL != mq_entry);
352   if ((0 == size) && (NULL == buf)) /* Timeout */
353   {
354     LOG_DEBUG ("Message sending timed out -- retrying\n");
355     c->th =
356       GNUNET_CLIENT_notify_transmit_ready (c->client,
357                                            ntohs (mq_entry->msg->size),
358                                            TIMEOUT_REL,
359                                            GNUNET_YES, &transmit_ready_notify,
360                                            c);
361     return 0;
362   }
363   GNUNET_assert (ntohs (mq_entry->msg->size) <= size);
364   size = ntohs (mq_entry->msg->size);  
365   memcpy (buf, mq_entry->msg, size);
366   LOG_DEBUG ("Message of type: %u and size: %u sent\n",
367              ntohs (mq_entry->msg->type), size);
368   GNUNET_free (mq_entry->msg);
369   GNUNET_CONTAINER_DLL_remove (c->mq_head, c->mq_tail, mq_entry);
370   GNUNET_free (mq_entry);
371   mq_entry = c->mq_head;
372   if (NULL != mq_entry)
373     c->th = 
374       GNUNET_CLIENT_notify_transmit_ready (c->client,
375                                            ntohs (mq_entry->msg->size),
376                                            TIMEOUT_REL,
377                                            GNUNET_YES, &transmit_ready_notify,
378                                            c);
379   if (GNUNET_NO == c->in_receive)
380   {
381     c->in_receive = GNUNET_YES;
382     GNUNET_CLIENT_receive (c->client, &message_handler, c,
383                            GNUNET_TIME_UNIT_FOREVER_REL);
384   }
385   return size;
386 }
387
388
389 /**
390  * Queues a message in send queue for sending to the service
391  *
392  * @param controller the handle to the controller
393  * @param msg the message to queue
394  */
395 void
396 GNUNET_TESTBED_queue_message (struct GNUNET_TESTBED_Controller *controller,
397                               struct GNUNET_MessageHeader *msg)
398 {
399   struct MessageQueue *mq_entry;
400   uint16_t type;
401   uint16_t size;
402
403   type = ntohs (msg->type);
404   size = ntohs (msg->size);
405   GNUNET_assert ((GNUNET_MESSAGE_TYPE_TESTBED_INIT <= type) &&
406                  (GNUNET_MESSAGE_TYPE_TESTBED_MAX > type));                 
407   mq_entry = GNUNET_malloc (sizeof (struct MessageQueue));
408   mq_entry->msg = msg;
409   LOG (GNUNET_ERROR_TYPE_DEBUG,
410        "Queueing message of type %u, size %u for sending\n", type,
411        ntohs (msg->size));
412   GNUNET_CONTAINER_DLL_insert_tail (controller->mq_head, controller->mq_tail,
413                                     mq_entry);
414   if (NULL == controller->th)
415     controller->th = 
416       GNUNET_CLIENT_notify_transmit_ready (controller->client, size,
417                                            TIMEOUT_REL,
418                                            GNUNET_YES, &transmit_ready_notify,
419                                            controller);
420 }
421
422
423 /**
424  * Handle for controller process
425  */
426 struct GNUNET_TESTBED_ControllerProc
427 {
428   /**
429    * The helper handle
430    */
431   struct GNUNET_TESTBED_HelperHandle *helper;
432
433   /**
434    * The controller error callback
435    */
436   GNUNET_TESTBED_ControllerErrorCallback cec;
437
438   /**
439    * The closure for the above callback
440    */
441   void *cec_cls;
442
443   /**
444    * The task id of the task that will be called when controller dies
445    */
446   GNUNET_SCHEDULER_TaskIdentifier controller_dead_task_id;
447 };
448
449
450 /**
451  * The task which is run when a controller dies (its stdout is closed)
452  *
453  * @param cls the ControllerProc struct
454  * @param tc the context
455  */
456 static void
457 controller_dead_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
458 {
459   struct GNUNET_TESTBED_ControllerProc *cproc = cls;
460
461   cproc->controller_dead_task_id = GNUNET_SCHEDULER_NO_TASK;
462   if (NULL != cproc->cec)
463     cproc->cec (cproc->cec_cls, NULL); /* FIXME: How to get the error message? */
464 }
465
466
467 /**
468  * Starts a controller process at the host
469  *
470  * @param system used for reserving ports if host is NULL and to determine
471  *               which 'host' to set as TRUSTED ('controller') when starting testbed remotely
472  * @param host the host where the controller has to be started; NULL for localhost
473  * @param cfg template configuration to use for the remote controller; will
474  *            be modified to contain the actual host/port/unixpath used for
475  *            the testbed service
476  * @param cec function called if the contoller dies unexpectedly; will not be 
477  *            invoked after GNUNET_TESTBED_controller_stop, if 'cec' was called,
478  *            GNUNET_TESTBED_controller_stop must no longer be called; will
479  *            never be called in the same task as 'GNUNET_TESTBED_controller_start'
480  *            (synchronous errors will be signalled by returning NULL)
481  * @param cec_cls closure for 'cec'
482  * @return the controller process handle, NULL on errors
483  */
484 struct GNUNET_TESTBED_ControllerProc *
485 GNUNET_TESTBED_controller_start (struct GNUNET_TESTING_System *system,
486                                  struct GNUNET_TESTBED_Host *host,
487                                  struct GNUNET_CONFIGURATION_Handle *cfg,
488                                  GNUNET_TESTBED_ControllerErrorCallback cec,
489                                  void *cec_cls)
490 {
491   struct GNUNET_TESTBED_ControllerProc *cproc;
492   const struct GNUNET_DISK_FileHandle *read_fh;
493   char *cfg_filename;
494
495   if ((NULL == host) || (0 == GNUNET_TESTBED_host_get_id_ (host)))
496   {
497     if (GNUNET_OK != GNUNET_TESTING_configuration_create (system, cfg))
498       return NULL;
499     GNUNET_assert 
500       (GNUNET_OK == 
501        GNUNET_CONFIGURATION_get_value_string (cfg, "PATHS", "DEFAULTCONFIG",
502                                               &cfg_filename));
503     if (GNUNET_OK != GNUNET_CONFIGURATION_write (cfg, cfg_filename))
504     {
505       GNUNET_break (0);
506       return NULL;
507     }
508     char * const binary_argv[] = {
509       "gnunet-service-testbed",
510       "-c", cfg_filename,
511       NULL
512     };
513     cproc = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_ControllerProc));
514     cproc->helper = GNUNET_TESTBED_host_run_ (host, binary_argv);
515     GNUNET_free (cfg_filename);
516     if (NULL == cproc->helper)
517     {
518       GNUNET_free (cproc);
519       return NULL;
520     }
521   }
522   else
523   {
524     GNUNET_break (0); /* FIXME: start controller remotely */
525     return NULL;
526   }
527   read_fh = GNUNET_DISK_pipe_handle (cproc->helper->cpipe_out,
528                                      GNUNET_DISK_PIPE_END_READ);
529   if (NULL == read_fh)
530   {
531     GNUNET_break (0); // we can't catch the process 
532   }
533   cproc->cec = cec;
534   cproc->cec_cls = cec_cls;
535   cproc->controller_dead_task_id =
536     GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL, read_fh,
537                                     &controller_dead_task, cproc);
538   return cproc;
539 }
540
541
542 /**
543  * Stop the controller process (also will terminate all peers and controllers
544  * dependent on this controller).  This function blocks until the testbed has
545  * been fully terminated (!).
546  *
547  * @param cproc the controller process handle
548  */
549 void
550 GNUNET_TESTBED_controller_stop (struct GNUNET_TESTBED_ControllerProc *cproc)
551 {
552   if (GNUNET_SCHEDULER_NO_TASK != cproc->controller_dead_task_id)
553   {
554     GNUNET_SCHEDULER_cancel (cproc->controller_dead_task_id);
555     cproc->controller_dead_task_id = GNUNET_SCHEDULER_NO_TASK;
556   }
557   GNUNET_TESTBED_host_stop_ (cproc->helper);
558   GNUNET_free (cproc);
559 }
560
561
562 /**
563  * Start a controller process using the given configuration at the
564  * given host.
565  *
566  * @param cfg configuration to use
567  * @param host host to run the controller on; This should be the same host if
568  *          the controller was previously started with
569  *          GNUNET_TESTBED_controller_start; NULL for localhost
570  * @param event_mask bit mask with set of events to call 'cc' for;
571  *                   or-ed values of "1LL" shifted by the
572  *                   respective 'enum GNUNET_TESTBED_EventType'
573  *                   (i.e.  "(1LL << GNUNET_TESTBED_ET_CONNECT) | ...")
574  * @param cc controller callback to invoke on events
575  * @param cc_cls closure for cc
576  * @return handle to the controller
577  */
578 struct GNUNET_TESTBED_Controller *
579 GNUNET_TESTBED_controller_connect (const struct GNUNET_CONFIGURATION_Handle *cfg,
580                                    struct GNUNET_TESTBED_Host *host,
581                                    uint64_t event_mask,
582                                    GNUNET_TESTBED_ControllerCallback cc,
583                                    void *cc_cls)
584 {
585   struct GNUNET_TESTBED_Controller *controller;
586   struct GNUNET_TESTBED_InitMessage *msg;
587
588   controller = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_Controller));
589   controller->cc = cc;
590   controller->cc_cls = cc_cls;
591   controller->event_mask = event_mask;
592   controller->cfg = GNUNET_CONFIGURATION_dup (cfg);
593   controller->client = GNUNET_CLIENT_connect ("testbed", controller->cfg);  
594   if (NULL == controller->client)
595   {
596     GNUNET_TESTBED_controller_disconnect (controller);
597     return NULL;
598   }
599   if (NULL == host)
600   {
601     host = GNUNET_TESTBED_host_create_by_id_ (0);
602     if (NULL == host)
603     {
604       LOG (GNUNET_ERROR_TYPE_WARNING,
605            "Treating NULL host as localhost. Multiple references to localhost. "
606            " May break when localhost freed before calling disconnect \n");
607       host = GNUNET_TESTBED_host_lookup_by_id_ (0);
608     }
609     else
610     {
611       controller->aux_host = GNUNET_YES;
612     }
613   }
614   GNUNET_assert (NULL != host);
615   msg = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_InitMessage));
616   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_INIT);
617   msg->header.size = htons (sizeof (struct GNUNET_TESTBED_InitMessage));
618   msg->host_id = htonl (GNUNET_TESTBED_host_get_id_ (host));
619   msg->event_mask = GNUNET_htonll (controller->event_mask);
620   GNUNET_TESTBED_queue_message (controller, (struct GNUNET_MessageHeader *) msg);
621   return controller;
622 }
623
624
625 /**
626  * Configure shared services at a controller.  Using this function,
627  * you can specify that certain services (such as "resolver")
628  * should not be run for each peer but instead be shared
629  * across N peers on the specified host.  This function
630  * must be called before any peers are created at the host.
631  * 
632  * @param controller controller to configure
633  * @param service_name name of the service to share
634  * @param num_peers number of peers that should share one instance
635  *        of the specified service (1 for no sharing is the default),
636  *        use 0 to disable the service
637  */
638 void
639 GNUNET_TESTBED_controller_configure_sharing (struct GNUNET_TESTBED_Controller *controller,
640                                              const char *service_name,
641                                              uint32_t num_peers)
642 {
643   struct GNUNET_TESTBED_ConfigureSharedServiceMessage *msg;
644   uint16_t service_name_size;
645   uint16_t msg_size;
646   
647   service_name_size = strlen (service_name) + 1;
648   msg_size = sizeof (struct GNUNET_TESTBED_ConfigureSharedServiceMessage)
649     + service_name_size;
650   msg = GNUNET_malloc (msg_size);
651   msg->header.size = htons (msg_size);
652   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_SERVICESHARE);
653   msg->host_id = htonl (GNUNET_TESTBED_host_get_id_ (controller->host));
654   msg->num_peers = htonl (num_peers);
655   memcpy (&msg[1], service_name, service_name_size);
656   GNUNET_TESTBED_queue_message (controller, (struct GNUNET_MessageHeader *) msg);
657 }
658
659
660 /**
661  * disconnects from the controller.
662  *
663  * @param controller handle to controller to stop
664  */
665 void
666 GNUNET_TESTBED_controller_disconnect (struct GNUNET_TESTBED_Controller *controller)
667 {
668   struct MessageQueue *mq_entry;
669
670   if (NULL != controller->th)
671     GNUNET_CLIENT_notify_transmit_ready_cancel (controller->th);
672  /* Clear the message queue */
673   while (NULL != (mq_entry = controller->mq_head))
674   {
675     GNUNET_CONTAINER_DLL_remove (controller->mq_head,
676                                  controller->mq_tail,
677                                  mq_entry);
678     GNUNET_free (mq_entry->msg);
679     GNUNET_free (mq_entry);
680   }
681   if (NULL != controller->client)
682     GNUNET_CLIENT_disconnect (controller->client);
683   GNUNET_CONFIGURATION_destroy (controller->cfg);
684   if (GNUNET_YES == controller->aux_host)
685     GNUNET_TESTBED_host_destroy (controller->host);
686   GNUNET_free (controller);
687 }
688
689
690 /**
691  * Register a host with the controller
692  *
693  * @param controller the controller handle
694  * @param host the host to register
695  * @param cc the completion callback to call to inform the status of
696  *          registration. After calling this callback the registration handle
697  *          will be invalid. Cannot be NULL.
698  * @param cc_cls the closure for the cc
699  * @return handle to the host registration which can be used to cancel the
700  *           registration 
701  */
702 struct GNUNET_TESTBED_HostRegistrationHandle *
703 GNUNET_TESTBED_register_host (struct GNUNET_TESTBED_Controller *controller,
704                               struct GNUNET_TESTBED_Host *host,
705                               GNUNET_TESTBED_HostRegistrationCompletion cc,
706                               void *cc_cls)
707 {
708   struct GNUNET_TESTBED_HostRegistrationHandle *rh;
709   struct GNUNET_TESTBED_AddHostMessage *msg;
710   const char *username;
711   const char *hostname;
712   uint16_t msg_size;
713   uint16_t user_name_length;
714
715   if (NULL != controller->rh)
716     return NULL;
717   hostname = GNUNET_TESTBED_host_get_hostname_ (host);
718   if (GNUNET_YES == GNUNET_TESTBED_is_host_registered_ (host, controller))
719   {
720     LOG (GNUNET_ERROR_TYPE_WARNING,
721          "Host hostname: %s already registered\n",
722          (NULL == hostname) ? "localhost" : hostname);
723     return NULL;
724   }  
725   rh = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_HostRegistrationHandle));
726   rh->host = host;
727   rh->c = controller;
728   GNUNET_assert (NULL != cc);
729   rh->cc = cc;
730   rh->cc_cls = cc_cls;
731   controller->rh = rh;
732   username = GNUNET_TESTBED_host_get_username_ (host);
733   msg_size = (sizeof (struct GNUNET_TESTBED_AddHostMessage));
734   user_name_length = 0;
735   if (NULL != username)
736   {
737     user_name_length = strlen (username) + 1;
738     msg_size += user_name_length;
739   }
740   /* FIXME: what happens when hostname is NULL? localhost */
741   GNUNET_assert (NULL != hostname);
742   msg_size += strlen (hostname) + 1;
743   msg = GNUNET_malloc (msg_size);
744   msg->header.size = htons (msg_size);
745   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_ADDHOST);
746   msg->host_id = htonl (GNUNET_TESTBED_host_get_id_ (host));
747   msg->ssh_port = htons (GNUNET_TESTBED_host_get_ssh_port_ (host));
748   msg->user_name_length = htons (user_name_length);
749   if (NULL != username)
750     memcpy (&msg[1], username, user_name_length);
751   strcpy (((void *) &msg[1]) + user_name_length, hostname);
752   GNUNET_TESTBED_queue_message (controller, (struct GNUNET_MessageHeader *) msg);
753   return rh;
754 }
755
756
757 /**
758  * Cancel the pending registration. Note that if the registration message is
759  * already sent to the service the cancellation has only the effect that the
760  * registration completion callback for the registration is never called.
761  *
762  * @param handle the registration handle to cancel
763  */
764 void
765 GNUNET_TESTBED_cancel_registration (struct GNUNET_TESTBED_HostRegistrationHandle
766                                     *handle)
767 {
768   if (handle != handle->c->rh)
769   {
770     GNUNET_break (0);
771     return;
772   }
773   handle->c->rh = NULL;
774   GNUNET_free (handle);  
775 }
776
777
778 /**
779  * Same as the GNUNET_TESTBED_controller_link, however expects configuration in
780  * serialized and compressed
781  *
782  * @param master handle to the master controller who creates the association
783  * @param delegated_host requests to which host should be delegated; cannot be NULL
784  * @param slave_host which host is used to run the slave controller; use NULL to
785  *          make the master controller connect to the delegated host
786  * @param sxcfg serialized and compressed configuration
787  * @param sxcfg_size the size scfg
788  * @param scfg_size the size of uncompressed serialized configuration
789  * @param is_subordinate GNUNET_YES if the controller at delegated_host should
790  *          be started by the master controller; GNUNET_NO if we are just
791  *          allowed to use the slave via TCP/IP
792  */
793 void
794 GNUNET_TESTBED_controller_link_2 (struct GNUNET_TESTBED_Controller *master,
795                                   struct GNUNET_TESTBED_Host *delegated_host,
796                                   struct GNUNET_TESTBED_Host *slave_host,
797                                   const char *sxcfg,
798                                   size_t sxcfg_size,
799                                   size_t scfg_size,
800                                   int is_subordinate)
801 {
802   struct GNUNET_TESTBED_ControllerLinkMessage *msg;
803   uint16_t msg_size;
804
805   GNUNET_assert (GNUNET_YES == 
806                  GNUNET_TESTBED_is_host_registered_ (delegated_host, master));
807   if ((NULL != slave_host) && (0 != GNUNET_TESTBED_host_get_id_ (slave_host)))
808     GNUNET_assert (GNUNET_YES == 
809                    GNUNET_TESTBED_is_host_registered_ (slave_host, master));
810   msg_size = sxcfg_size + sizeof (struct GNUNET_TESTBED_ControllerLinkMessage);
811   msg = GNUNET_malloc (msg_size);
812   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_LCONTROLLERS);  
813   msg->header.size = htons (msg_size);
814   msg->delegated_host_id = htonl (GNUNET_TESTBED_host_get_id_ (delegated_host));
815   msg->slave_host_id = htonl (GNUNET_TESTBED_host_get_id_ 
816                               ((NULL != slave_host) ? slave_host : master->host));
817   msg->config_size = htons ((uint16_t) scfg_size);
818   msg->is_subordinate = (GNUNET_YES == is_subordinate) ? 1 : 0;
819   memcpy (&msg[1], sxcfg, sxcfg_size);
820   GNUNET_TESTBED_queue_message (master, (struct GNUNET_MessageHeader *) msg);
821 }
822
823
824 /**
825  * Compresses given configuration using zlib compress
826  *
827  * @param config the serialized configuration
828  * @param size the size of config
829  * @param xconfig will be set to the compressed configuration (memory is fresly
830  *          allocated) 
831  * @return the size of the xconfig
832  */
833 size_t
834 GNUNET_TESTBED_compress_config (const char *config, size_t size,
835                                 char **xconfig)
836 {
837   size_t xsize;
838   
839   xsize = compressBound ((uLong) size);
840   *xconfig = GNUNET_malloc (xsize);
841   GNUNET_assert (Z_OK ==
842                  compress2 ((Bytef *)* xconfig, (uLongf *) &xsize,
843                             (const Bytef *) config, (uLongf) size, 
844                             Z_BEST_SPEED));
845   return xsize;
846 }
847                                 
848
849 /**
850  * Create a link from slave controller to delegated controller. Whenever the
851  * master controller is asked to start a peer at the delegated controller the
852  * request will be routed towards slave controller (if a route exists). The
853  * slave controller will then route it to the delegated controller. The
854  * configuration of the slave controller is given and to be used to either
855  * create the slave controller or to connect to an existing slave controller
856  * process.  'is_subordinate' specifies if the given slave controller should be
857  * started and managed by the master controller, or if the slave already has a
858  * master and this is just a secondary master that is also allowed to use the
859  * existing slave.
860  *
861  * @param master handle to the master controller who creates the association
862  * @param delegated_host requests to which host should be delegated
863  * @param slave_host which host is used to run the slave controller 
864  * @param slave_cfg configuration to use for the slave controller
865  * @param is_subordinate GNUNET_YES if the slave should be started (and stopped)
866  *                       by the master controller; GNUNET_NO if we are just
867  *                       allowed to use the slave via TCP/IP
868  */
869 void
870 GNUNET_TESTBED_controller_link (struct GNUNET_TESTBED_Controller *master,
871                                 struct GNUNET_TESTBED_Host *delegated_host,
872                                 struct GNUNET_TESTBED_Host *slave_host,
873                                 const struct GNUNET_CONFIGURATION_Handle *slave_cfg,
874                                 int is_subordinate)
875 {
876   char *config;
877   char *cconfig;
878   size_t cc_size;
879   size_t config_size;  
880   
881   GNUNET_assert (GNUNET_YES == 
882                  GNUNET_TESTBED_is_host_registered_ (delegated_host, master));
883   if ((NULL != slave_host) && (0 != GNUNET_TESTBED_host_get_id_ (slave_host)))
884     GNUNET_assert (GNUNET_YES == 
885                    GNUNET_TESTBED_is_host_registered_ (slave_host, master));
886   config = GNUNET_CONFIGURATION_serialize (slave_cfg, &config_size);
887   cc_size = GNUNET_TESTBED_compress_config (config, config_size, &cconfig);
888   GNUNET_free (config);
889   GNUNET_assert ((UINT16_MAX -
890                   sizeof (struct GNUNET_TESTBED_ControllerLinkMessage))
891                   >= cc_size); /* Configuration doesn't fit in 1 message */
892   GNUNET_TESTBED_controller_link_2 (master, delegated_host, slave_host,
893                                     (const char *) cconfig,
894                                     cc_size, config_size, is_subordinate);
895   GNUNET_free (cconfig);
896 }
897
898
899 /**
900  * Ask the testbed controller to write the current overlay topology to
901  * a file.  Naturally, the file will only contain a snapshot as the
902  * topology may evolve all the time.
903  *
904  * @param controller overlay controller to inspect
905  * @param filename name of the file the topology should
906  *        be written to.
907  */
908 void
909 GNUNET_TESTBED_overlay_write_topology_to_file (struct GNUNET_TESTBED_Controller *controller,
910                                                const char *filename)
911 {
912   GNUNET_break (0);
913 }
914
915
916
917 /* end of testbed_api.c */