testbed api peer start
[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 GNUNET_MESSAGE_TYPE_TESTBED_PEERCREATESUCCESS message from
290  * controller (testbed service)
291  *
292  * @param c the controller handler
293  * @param msg message received
294  * @return GNUNET_YES if we can continue receiving from service; GNUNET_NO if
295  *           not
296  */
297 static int
298 handle_peer_create_success (struct GNUNET_TESTBED_Controller *c,
299                             const struct
300                             GNUNET_TESTBED_PeerCreateSuccessEventMessage *msg)
301 {
302   struct GNUNET_TESTBED_Operation *op;
303   struct GNUNET_TESTBED_Peer *peer;
304   uint64_t op_id;
305
306   GNUNET_assert (sizeof (struct GNUNET_TESTBED_PeerCreateSuccessEventMessage)
307                  == ntohs (msg->header.size));
308   op_id = GNUNET_ntohll (msg->operation_id);
309   for (op = c->op_head; NULL != op; op = op->next)
310   {
311     if (op->operation_id == op_id)
312       break;
313   }
314   GNUNET_assert (NULL != op);
315   peer = op->data;
316   GNUNET_assert (NULL != peer);
317   GNUNET_assert (peer->unique_id == ntohl (msg->peer_id));
318   if (0 != (c->event_mask & (1L << GNUNET_TESTBED_ET_PEER_START)))
319   {
320     struct GNUNET_TESTBED_EventInformation info;
321     
322     info.details.peer_start.host = peer->host;
323     info.details.peer_start.peer = peer;
324     if (NULL != c->cc)
325       c->cc (c->cc_cls, &info);
326   }
327   GNUNET_CONTAINER_DLL_remove (c->op_head, c->op_tail, op);
328   GNUNET_free (op);
329   return GNUNET_YES;
330 }
331
332
333 /**
334  * Handler for messages from controller (testbed service)
335  *
336  * @param cls the controller handler
337  * @param msg message received, NULL on timeout or fatal error
338  */
339 static void 
340 message_handler (void *cls, const struct GNUNET_MessageHeader *msg)
341 {
342   struct GNUNET_TESTBED_Controller *c = cls;  
343   int status;
344
345   c->in_receive = GNUNET_NO;
346   /* FIXME: Add checks for message integrity */
347   if (NULL == msg)
348   {
349     LOG_DEBUG ("Receive timed out or connection to service dropped\n");
350     return;
351   }
352   status = GNUNET_OK;
353   switch (ntohs (msg->type))
354   {
355   case GNUNET_MESSAGE_TYPE_TESTBED_ADDHOSTCONFIRM:
356     status =
357       handle_addhostconfirm (c, (const struct
358                                  GNUNET_TESTBED_HostConfirmedMessage *) msg);
359     break;
360   case GNUNET_MESSAGE_TYPE_TESTBED_GENERICOPSUCCESS:
361     status =
362       handle_opsuccess (c, (const struct
363                             GNUNET_TESTBED_GenericOperationSuccessEventMessage
364                             *) msg);
365     break;
366   case GNUNET_MESSAGE_TYPE_TESTBED_PEERCREATESUCCESS:
367     status =
368       handle_peer_create_success 
369       (c, (const struct GNUNET_TESTBED_PeerCreateSuccessEventMessage *)msg);
370     break;
371   default:
372     GNUNET_break (0);
373   }
374   if ((GNUNET_OK == status) && (GNUNET_NO == c->in_receive))
375   {
376     c->in_receive = GNUNET_YES;
377     GNUNET_CLIENT_receive (c->client, &message_handler, c,
378                            GNUNET_TIME_UNIT_FOREVER_REL);    
379   }
380 }
381
382
383 /**
384  * Function called to notify a client about the connection begin ready to queue
385  * more data.  "buf" will be NULL and "size" zero if the connection was closed
386  * for writing in the meantime.
387  *
388  * @param cls closure
389  * @param size number of bytes available in buf
390  * @param buf where the callee should write the message
391  * @return number of bytes written to buf
392  */
393 static size_t
394 transmit_ready_notify (void *cls, size_t size, void *buf)
395 {
396   struct GNUNET_TESTBED_Controller *c = cls;
397   struct MessageQueue *mq_entry;
398
399   c->th = NULL;
400   mq_entry = c->mq_head;
401   GNUNET_assert (NULL != mq_entry);
402   if ((0 == size) && (NULL == buf)) /* Timeout */
403   {
404     LOG_DEBUG ("Message sending timed out -- retrying\n");
405     c->th =
406       GNUNET_CLIENT_notify_transmit_ready (c->client,
407                                            ntohs (mq_entry->msg->size),
408                                            TIMEOUT_REL,
409                                            GNUNET_YES, &transmit_ready_notify,
410                                            c);
411     return 0;
412   }
413   GNUNET_assert (ntohs (mq_entry->msg->size) <= size);
414   size = ntohs (mq_entry->msg->size);  
415   memcpy (buf, mq_entry->msg, size);
416   LOG_DEBUG ("Message of type: %u and size: %u sent\n",
417              ntohs (mq_entry->msg->type), size);
418   GNUNET_free (mq_entry->msg);
419   GNUNET_CONTAINER_DLL_remove (c->mq_head, c->mq_tail, mq_entry);
420   GNUNET_free (mq_entry);
421   mq_entry = c->mq_head;
422   if (NULL != mq_entry)
423     c->th = 
424       GNUNET_CLIENT_notify_transmit_ready (c->client,
425                                            ntohs (mq_entry->msg->size),
426                                            TIMEOUT_REL,
427                                            GNUNET_YES, &transmit_ready_notify,
428                                            c);
429   if (GNUNET_NO == c->in_receive)
430   {
431     c->in_receive = GNUNET_YES;
432     GNUNET_CLIENT_receive (c->client, &message_handler, c,
433                            GNUNET_TIME_UNIT_FOREVER_REL);
434   }
435   return size;
436 }
437
438
439 /**
440  * Queues a message in send queue for sending to the service
441  *
442  * @param controller the handle to the controller
443  * @param msg the message to queue
444  */
445 void
446 GNUNET_TESTBED_queue_message_ (struct GNUNET_TESTBED_Controller *controller,
447                                struct GNUNET_MessageHeader *msg)
448 {
449   struct MessageQueue *mq_entry;
450   uint16_t type;
451   uint16_t size;
452
453   type = ntohs (msg->type);
454   size = ntohs (msg->size);
455   GNUNET_assert ((GNUNET_MESSAGE_TYPE_TESTBED_INIT <= type) &&
456                  (GNUNET_MESSAGE_TYPE_TESTBED_MAX > type));                 
457   mq_entry = GNUNET_malloc (sizeof (struct MessageQueue));
458   mq_entry->msg = msg;
459   LOG (GNUNET_ERROR_TYPE_DEBUG,
460        "Queueing message of type %u, size %u for sending\n", type,
461        ntohs (msg->size));
462   GNUNET_CONTAINER_DLL_insert_tail (controller->mq_head, controller->mq_tail,
463                                     mq_entry);
464   if (NULL == controller->th)
465     controller->th = 
466       GNUNET_CLIENT_notify_transmit_ready (controller->client, size,
467                                            TIMEOUT_REL,
468                                            GNUNET_YES, &transmit_ready_notify,
469                                            controller);
470 }
471
472
473 /**
474  * Handle for controller process
475  */
476 struct GNUNET_TESTBED_ControllerProc
477 {
478   /**
479    * The process handle
480    */
481   struct GNUNET_HELPER_Handle *helper;
482
483   /**
484    * The host where the helper is run
485    */
486   struct GNUNET_TESTBED_Host *host;
487
488   /**
489    * The controller error callback
490    */
491   GNUNET_TESTBED_ControllerStatusCallback cb;
492
493   /**
494    * The closure for the above callback
495    */
496   void *cls;
497
498   /**
499    * The send handle for the helper
500    */
501   struct GNUNET_HELPER_SendHandle *shandle;
502
503   /**
504    * The message corresponding to send handle
505    */
506   struct GNUNET_MessageHeader *msg;
507
508   /**
509    * The port number for ssh; used for helpers starting ssh
510    */
511   char *port;
512
513   /**
514    * The ssh destination string; used for helpers starting ssh
515    */
516   char *dst;
517
518   /**
519    * The configuration of the running testbed service
520    */
521   struct GNUNET_CONFIGURATION_Handle *cfg;
522
523 };
524
525
526 /**
527  * Functions with this signature are called whenever a
528  * complete message is received by the tokenizer.
529  *
530  * Do not call GNUNET_SERVER_mst_destroy in callback
531  *
532  * @param cls closure
533  * @param client identification of the client
534  * @param message the actual message
535  *
536  * @return GNUNET_OK on success, GNUNET_SYSERR to stop further processing
537  */
538 static int helper_mst (void *cls, void *client,
539                        const struct GNUNET_MessageHeader *message)
540 {
541   struct GNUNET_TESTBED_ControllerProc *cp = cls;
542   const struct GNUNET_TESTBED_HelperReply *msg;
543   const char *hostname;
544   char *config;
545   uLongf config_size;
546   uLongf xconfig_size;
547     
548   msg = (const struct GNUNET_TESTBED_HelperReply *) message;
549   GNUNET_assert (sizeof (struct GNUNET_TESTBED_HelperReply) 
550                  < ntohs (msg->header.size));
551   GNUNET_assert (GNUNET_MESSAGE_TYPE_TESTBED_HELPER_REPLY 
552                  == ntohs (msg->header.type));
553   config_size = (uLongf) ntohs (msg->config_size);
554   xconfig_size = (uLongf) (ntohs (msg->header.size)
555                            - sizeof (struct GNUNET_TESTBED_HelperReply));
556   config = GNUNET_malloc (config_size);
557   GNUNET_assert (Z_OK == uncompress ((Bytef *) config, &config_size,
558                                      (const Bytef *) &msg[1], xconfig_size));
559   GNUNET_assert (NULL == cp->cfg);
560   cp->cfg = GNUNET_CONFIGURATION_create ();
561   GNUNET_assert (GNUNET_CONFIGURATION_deserialize (cp->cfg, config, 
562                                                    config_size, GNUNET_NO));
563   GNUNET_free (config);
564   if ((NULL == cp->host) || 
565       (NULL == (hostname = GNUNET_TESTBED_host_get_hostname_ (cp->host))))
566     hostname = "localhost";
567   /* Change the hostname so that we can connect to it */
568   GNUNET_CONFIGURATION_set_value_string (cp->cfg, "testbed", "hostname", 
569                                          hostname);
570   cp->cb (cp->cls, cp->cfg, GNUNET_OK);
571   return GNUNET_OK;
572 }
573
574
575 /**
576  * Continuation function from GNUNET_HELPER_send()
577  * 
578  * @param cls closure
579  * @param result GNUNET_OK on success,
580  *               GNUNET_NO if helper process died
581  *               GNUNET_SYSERR during GNUNET_HELPER_stop
582  */
583 static void 
584 clear_msg (void *cls, int result)
585 {
586   struct GNUNET_TESTBED_ControllerProc *cp = cls;
587   
588   GNUNET_assert (NULL != cp->shandle);
589   cp->shandle = NULL;
590   GNUNET_free (cp->msg);
591 }
592
593
594 /**
595  * Callback that will be called when the helper process dies. This is not called
596  * when the helper process is stoped using GNUNET_HELPER_stop()
597  *
598  * @param cls the closure from GNUNET_HELPER_start()
599  */
600 static void 
601 helper_exp_cb (void *cls)
602 {
603   struct GNUNET_TESTBED_ControllerProc *cp = cls;
604   GNUNET_TESTBED_ControllerStatusCallback cb;
605   void *cb_cls;
606
607   cb = cp->cb;
608   cb_cls = cp->cls;
609   GNUNET_TESTBED_controller_stop (cp);
610   if (NULL != cb)
611     cb (cb_cls, NULL, GNUNET_SYSERR);
612 }
613
614
615 /**
616  * Starts a controller process at the host. FIXME: add controller start callback
617  * with the configuration with which the controller is started
618  *
619  * @param controller_ip the ip address of the controller. Will be set as TRUSTED
620  *          host when starting testbed controller at host
621  * @param host the host where the controller has to be started; NULL for
622  *          localhost
623  * @param cfg template configuration to use for the remote controller; the
624  *          remote controller will be started with a slightly modified
625  *          configuration (port numbers, unix domain sockets and service home
626  *          values are changed as per TESTING library on the remote host)
627  * @param cb function called when the controller is successfully started or
628  *          dies unexpectedly; GNUNET_TESTBED_controller_stop shouldn't be
629  *          called if cb is called with GNUNET_SYSERR as status. Will never be
630  *          called in the same task as 'GNUNET_TESTBED_controller_start'
631  *          (synchronous errors will be signalled by returning NULL). This
632  *          parameter cannot be NULL.
633  * @param cls closure for above callbacks
634  * @return the controller process handle, NULL on errors
635  */
636 struct GNUNET_TESTBED_ControllerProc *
637 GNUNET_TESTBED_controller_start (const char *controller_ip,
638                                  struct GNUNET_TESTBED_Host *host,
639                                  const struct GNUNET_CONFIGURATION_Handle *cfg,
640                                  GNUNET_TESTBED_ControllerStatusCallback cb,
641                                  void *cls)
642 {
643   struct GNUNET_TESTBED_ControllerProc *cp;
644   struct GNUNET_TESTBED_HelperInit *msg;
645   
646   cp = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_ControllerProc));
647   if ((NULL == host) || (0 == GNUNET_TESTBED_host_get_id_ (host)))
648   {
649     char * const binary_argv[] = {
650       "gnunet-testbed-helper", NULL
651     };
652
653     cp->helper = GNUNET_HELPER_start ("gnunet-testbed-helper", binary_argv, 
654                                       &helper_mst, &helper_exp_cb, cp);
655   }
656   else
657   {
658     char *remote_args[6 + 1];
659     unsigned int argp;
660     const char *username;
661     const char *hostname;
662
663     username = GNUNET_TESTBED_host_get_username_ (host);
664     hostname = GNUNET_TESTBED_host_get_hostname_ (host);
665     GNUNET_asprintf (&cp->port, "%u", GNUNET_TESTBED_host_get_ssh_port_ (host));
666     if (NULL == username)
667       GNUNET_asprintf (&cp->dst, "%s", hostname);
668     else 
669       GNUNET_asprintf (&cp->dst, "%s@%s", hostname, username);
670     argp = 0;
671     remote_args[argp++] = "ssh";
672     remote_args[argp++] = "-p";
673     remote_args[argp++] = cp->port;
674     remote_args[argp++] = "-q";
675     remote_args[argp++] = cp->dst;
676     remote_args[argp++] = "gnunet-testbed-helper";
677     remote_args[argp++] = NULL;
678     GNUNET_assert (argp == 6 + 1);
679     cp->helper = GNUNET_HELPER_start ("ssh", remote_args,
680                                       &helper_mst, &helper_exp_cb, cp);
681   }
682   if (NULL == cp->helper)
683   {
684     GNUNET_free_non_null (cp->port);
685     GNUNET_free_non_null (cp->dst);
686     GNUNET_free (cp);
687     return NULL;
688   }
689   cp->host = host;
690   cp->cb = cb;
691   cp->cls = cls;
692   msg = GNUNET_TESTBED_create_helper_init_msg_ (controller_ip, cfg);
693   cp->msg = &msg->header;
694   cp->shandle = GNUNET_HELPER_send (cp->helper, &msg->header, GNUNET_NO,
695                                     &clear_msg, cp);
696   if (NULL == cp->shandle)
697   {
698     GNUNET_free (msg);
699     GNUNET_TESTBED_controller_stop (cp);
700     return NULL;
701   }
702   return cp;
703 }
704
705
706 /**
707  * Stop the controller process (also will terminate all peers and controllers
708  * dependent on this controller).  This function blocks until the testbed has
709  * been fully terminated (!).
710  *
711  * @param cproc the controller process handle
712  */
713 void
714 GNUNET_TESTBED_controller_stop (struct GNUNET_TESTBED_ControllerProc *cp)
715 {
716   if (NULL != cp->shandle)
717     GNUNET_HELPER_send_cancel (cp->shandle);
718   GNUNET_HELPER_stop (cp->helper);
719   if (NULL != cp->cfg)
720     GNUNET_CONFIGURATION_destroy (cp->cfg);
721   GNUNET_free_non_null (cp->port);
722   GNUNET_free_non_null (cp->dst);
723   GNUNET_free (cp);
724 }
725
726
727 /**
728  * Start a controller process using the given configuration at the
729  * given host.
730  *
731  * @param cfg configuration to use
732  * @param host host to run the controller on; This should be the same host if
733  *          the controller was previously started with
734  *          GNUNET_TESTBED_controller_start; NULL for localhost
735  * @param event_mask bit mask with set of events to call 'cc' for;
736  *                   or-ed values of "1LL" shifted by the
737  *                   respective 'enum GNUNET_TESTBED_EventType'
738  *                   (i.e.  "(1LL << GNUNET_TESTBED_ET_CONNECT) | ...")
739  * @param cc controller callback to invoke on events
740  * @param cc_cls closure for cc
741  * @return handle to the controller
742  */
743 struct GNUNET_TESTBED_Controller *
744 GNUNET_TESTBED_controller_connect (const struct GNUNET_CONFIGURATION_Handle *cfg,
745                                    struct GNUNET_TESTBED_Host *host,
746                                    uint64_t event_mask,
747                                    GNUNET_TESTBED_ControllerCallback cc,
748                                    void *cc_cls)
749 {
750   struct GNUNET_TESTBED_Controller *controller;
751   struct GNUNET_TESTBED_InitMessage *msg;
752
753   controller = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_Controller));
754   controller->cc = cc;
755   controller->cc_cls = cc_cls;
756   controller->event_mask = event_mask;
757   controller->cfg = GNUNET_CONFIGURATION_dup (cfg);
758   controller->client = GNUNET_CLIENT_connect ("testbed", controller->cfg);  
759   if (NULL == controller->client)
760   {
761     GNUNET_TESTBED_controller_disconnect (controller);
762     return NULL;
763   }
764   if (NULL == host)
765   {
766     host = GNUNET_TESTBED_host_create_by_id_ (0);
767     if (NULL == host)
768     {
769       LOG (GNUNET_ERROR_TYPE_WARNING,
770            "Treating NULL host as localhost. Multiple references to localhost. "
771            " May break when localhost freed before calling disconnect \n");
772       host = GNUNET_TESTBED_host_lookup_by_id_ (0);
773     }
774     else
775     {
776       controller->aux_host = GNUNET_YES;
777     }
778   }
779   GNUNET_assert (NULL != host);
780   msg = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_InitMessage));
781   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_INIT);
782   msg->header.size = htons (sizeof (struct GNUNET_TESTBED_InitMessage));
783   msg->host_id = htonl (GNUNET_TESTBED_host_get_id_ (host));
784   msg->event_mask = GNUNET_htonll (controller->event_mask);
785   GNUNET_TESTBED_queue_message_ (controller, (struct GNUNET_MessageHeader *) msg);
786   return controller;
787 }
788
789
790 /**
791  * Configure shared services at a controller.  Using this function,
792  * you can specify that certain services (such as "resolver")
793  * should not be run for each peer but instead be shared
794  * across N peers on the specified host.  This function
795  * must be called before any peers are created at the host.
796  * 
797  * @param controller controller to configure
798  * @param service_name name of the service to share
799  * @param num_peers number of peers that should share one instance
800  *        of the specified service (1 for no sharing is the default),
801  *        use 0 to disable the service
802  */
803 void
804 GNUNET_TESTBED_controller_configure_sharing (struct GNUNET_TESTBED_Controller *controller,
805                                              const char *service_name,
806                                              uint32_t num_peers)
807 {
808   struct GNUNET_TESTBED_ConfigureSharedServiceMessage *msg;
809   uint16_t service_name_size;
810   uint16_t msg_size;
811   
812   service_name_size = strlen (service_name) + 1;
813   msg_size = sizeof (struct GNUNET_TESTBED_ConfigureSharedServiceMessage)
814     + service_name_size;
815   msg = GNUNET_malloc (msg_size);
816   msg->header.size = htons (msg_size);
817   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_SERVICESHARE);
818   msg->host_id = htonl (GNUNET_TESTBED_host_get_id_ (controller->host));
819   msg->num_peers = htonl (num_peers);
820   memcpy (&msg[1], service_name, service_name_size);
821   GNUNET_TESTBED_queue_message_ (controller, (struct GNUNET_MessageHeader *) msg);
822 }
823
824
825 /**
826  * disconnects from the controller.
827  *
828  * @param controller handle to controller to stop
829  */
830 void
831 GNUNET_TESTBED_controller_disconnect (struct GNUNET_TESTBED_Controller *controller)
832 {
833   struct MessageQueue *mq_entry;
834
835   if (NULL != controller->th)
836     GNUNET_CLIENT_notify_transmit_ready_cancel (controller->th);
837  /* Clear the message queue */
838   while (NULL != (mq_entry = controller->mq_head))
839   {
840     GNUNET_CONTAINER_DLL_remove (controller->mq_head,
841                                  controller->mq_tail,
842                                  mq_entry);
843     GNUNET_free (mq_entry->msg);
844     GNUNET_free (mq_entry);
845   }
846   if (NULL != controller->client)
847     GNUNET_CLIENT_disconnect (controller->client);
848   GNUNET_CONFIGURATION_destroy (controller->cfg);
849   if (GNUNET_YES == controller->aux_host)
850     GNUNET_TESTBED_host_destroy (controller->host);
851   GNUNET_free (controller);
852 }
853
854
855 /**
856  * Register a host with the controller
857  *
858  * @param controller the controller handle
859  * @param host the host to register
860  * @param cc the completion callback to call to inform the status of
861  *          registration. After calling this callback the registration handle
862  *          will be invalid. Cannot be NULL.
863  * @param cc_cls the closure for the cc
864  * @return handle to the host registration which can be used to cancel the
865  *           registration 
866  */
867 struct GNUNET_TESTBED_HostRegistrationHandle *
868 GNUNET_TESTBED_register_host (struct GNUNET_TESTBED_Controller *controller,
869                               struct GNUNET_TESTBED_Host *host,
870                               GNUNET_TESTBED_HostRegistrationCompletion cc,
871                               void *cc_cls)
872 {
873   struct GNUNET_TESTBED_HostRegistrationHandle *rh;
874   struct GNUNET_TESTBED_AddHostMessage *msg;
875   const char *username;
876   const char *hostname;
877   uint16_t msg_size;
878   uint16_t user_name_length;
879
880   if (NULL != controller->rh)
881     return NULL;
882   hostname = GNUNET_TESTBED_host_get_hostname_ (host);
883   if (GNUNET_YES == GNUNET_TESTBED_is_host_registered_ (host, controller))
884   {
885     LOG (GNUNET_ERROR_TYPE_WARNING,
886          "Host hostname: %s already registered\n",
887          (NULL == hostname) ? "localhost" : hostname);
888     return NULL;
889   }  
890   rh = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_HostRegistrationHandle));
891   rh->host = host;
892   rh->c = controller;
893   GNUNET_assert (NULL != cc);
894   rh->cc = cc;
895   rh->cc_cls = cc_cls;
896   controller->rh = rh;
897   username = GNUNET_TESTBED_host_get_username_ (host);
898   msg_size = (sizeof (struct GNUNET_TESTBED_AddHostMessage));
899   user_name_length = 0;
900   if (NULL != username)
901   {
902     user_name_length = strlen (username) + 1;
903     msg_size += user_name_length;
904   }
905   /* FIXME: what happens when hostname is NULL? localhost */
906   GNUNET_assert (NULL != hostname);
907   msg_size += strlen (hostname) + 1;
908   msg = GNUNET_malloc (msg_size);
909   msg->header.size = htons (msg_size);
910   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_ADDHOST);
911   msg->host_id = htonl (GNUNET_TESTBED_host_get_id_ (host));
912   msg->ssh_port = htons (GNUNET_TESTBED_host_get_ssh_port_ (host));
913   msg->user_name_length = htons (user_name_length);
914   if (NULL != username)
915     memcpy (&msg[1], username, user_name_length);
916   strcpy (((void *) &msg[1]) + user_name_length, hostname);
917   GNUNET_TESTBED_queue_message_ (controller, (struct GNUNET_MessageHeader *) msg);
918   return rh;
919 }
920
921
922 /**
923  * Cancel the pending registration. Note that if the registration message is
924  * already sent to the service the cancellation has only the effect that the
925  * registration completion callback for the registration is never called.
926  *
927  * @param handle the registration handle to cancel
928  */
929 void
930 GNUNET_TESTBED_cancel_registration (struct GNUNET_TESTBED_HostRegistrationHandle
931                                     *handle)
932 {
933   if (handle != handle->c->rh)
934   {
935     GNUNET_break (0);
936     return;
937   }
938   handle->c->rh = NULL;
939   GNUNET_free (handle);  
940 }
941
942
943 /**
944  * Same as the GNUNET_TESTBED_controller_link, however expects configuration in
945  * serialized and compressed
946  *
947  * @param master handle to the master controller who creates the association
948  * @param delegated_host requests to which host should be delegated; cannot be NULL
949  * @param slave_host which host is used to run the slave controller; use NULL to
950  *          make the master controller connect to the delegated host
951  * @param sxcfg serialized and compressed configuration
952  * @param sxcfg_size the size scfg
953  * @param scfg_size the size of uncompressed serialized configuration
954  * @param is_subordinate GNUNET_YES if the controller at delegated_host should
955  *          be started by the master controller; GNUNET_NO if we are just
956  *          allowed to use the slave via TCP/IP
957  */
958 void
959 GNUNET_TESTBED_controller_link_2 (struct GNUNET_TESTBED_Controller *master,
960                                   struct GNUNET_TESTBED_Host *delegated_host,
961                                   struct GNUNET_TESTBED_Host *slave_host,
962                                   const char *sxcfg,
963                                   size_t sxcfg_size,
964                                   size_t scfg_size,
965                                   int is_subordinate)
966 {
967   struct GNUNET_TESTBED_ControllerLinkMessage *msg;
968   uint16_t msg_size;
969
970   GNUNET_assert (GNUNET_YES == 
971                  GNUNET_TESTBED_is_host_registered_ (delegated_host, master));
972   if ((NULL != slave_host) && (0 != GNUNET_TESTBED_host_get_id_ (slave_host)))
973     GNUNET_assert (GNUNET_YES == 
974                    GNUNET_TESTBED_is_host_registered_ (slave_host, master));
975   msg_size = sxcfg_size + sizeof (struct GNUNET_TESTBED_ControllerLinkMessage);
976   msg = GNUNET_malloc (msg_size);
977   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_LCONTROLLERS);  
978   msg->header.size = htons (msg_size);
979   msg->delegated_host_id = htonl (GNUNET_TESTBED_host_get_id_ (delegated_host));
980   msg->slave_host_id = htonl (GNUNET_TESTBED_host_get_id_ 
981                               ((NULL != slave_host) ? slave_host : master->host));
982   msg->config_size = htons ((uint16_t) scfg_size);
983   msg->is_subordinate = (GNUNET_YES == is_subordinate) ? 1 : 0;
984   memcpy (&msg[1], sxcfg, sxcfg_size);
985   GNUNET_TESTBED_queue_message_ (master, (struct GNUNET_MessageHeader *) msg);
986 }
987
988
989 /**
990  * Compresses given configuration using zlib compress
991  *
992  * @param config the serialized configuration
993  * @param size the size of config
994  * @param xconfig will be set to the compressed configuration (memory is fresly
995  *          allocated) 
996  * @return the size of the xconfig
997  */
998 size_t
999 GNUNET_TESTBED_compress_config_ (const char *config, size_t size,
1000                                  char **xconfig)
1001 {
1002   size_t xsize;
1003   
1004   xsize = compressBound ((uLong) size);
1005   *xconfig = GNUNET_malloc (xsize);
1006   GNUNET_assert (Z_OK ==
1007                  compress2 ((Bytef *)* xconfig, (uLongf *) &xsize,
1008                             (const Bytef *) config, (uLongf) size, 
1009                             Z_BEST_SPEED));
1010   return xsize;
1011 }
1012                                 
1013
1014 /**
1015  * Create a link from slave controller to delegated controller. Whenever the
1016  * master controller is asked to start a peer at the delegated controller the
1017  * request will be routed towards slave controller (if a route exists). The
1018  * slave controller will then route it to the delegated controller. The
1019  * configuration of the slave controller is given and to be used to either
1020  * create the slave controller or to connect to an existing slave controller
1021  * process.  'is_subordinate' specifies if the given slave controller should be
1022  * started and managed by the master controller, or if the slave already has a
1023  * master and this is just a secondary master that is also allowed to use the
1024  * existing slave.
1025  *
1026  * @param master handle to the master controller who creates the association
1027  * @param delegated_host requests to which host should be delegated
1028  * @param slave_host which host is used to run the slave controller 
1029  * @param slave_cfg configuration to use for the slave controller
1030  * @param is_subordinate GNUNET_YES if the slave should be started (and stopped)
1031  *                       by the master controller; GNUNET_NO if we are just
1032  *                       allowed to use the slave via TCP/IP
1033  */
1034 void
1035 GNUNET_TESTBED_controller_link (struct GNUNET_TESTBED_Controller *master,
1036                                 struct GNUNET_TESTBED_Host *delegated_host,
1037                                 struct GNUNET_TESTBED_Host *slave_host,
1038                                 const struct GNUNET_CONFIGURATION_Handle *slave_cfg,
1039                                 int is_subordinate)
1040 {
1041   char *config;
1042   char *cconfig;
1043   size_t cc_size;
1044   size_t config_size;  
1045   
1046   GNUNET_assert (GNUNET_YES == 
1047                  GNUNET_TESTBED_is_host_registered_ (delegated_host, master));
1048   if ((NULL != slave_host) && (0 != GNUNET_TESTBED_host_get_id_ (slave_host)))
1049     GNUNET_assert (GNUNET_YES == 
1050                    GNUNET_TESTBED_is_host_registered_ (slave_host, master));
1051   config = GNUNET_CONFIGURATION_serialize (slave_cfg, &config_size);
1052   cc_size = GNUNET_TESTBED_compress_config_ (config, config_size, &cconfig);
1053   GNUNET_free (config);
1054   GNUNET_assert ((UINT16_MAX -
1055                   sizeof (struct GNUNET_TESTBED_ControllerLinkMessage))
1056                   >= cc_size); /* Configuration doesn't fit in 1 message */
1057   GNUNET_TESTBED_controller_link_2 (master, delegated_host, slave_host,
1058                                     (const char *) cconfig,
1059                                     cc_size, config_size, is_subordinate);
1060   GNUNET_free (cconfig);
1061 }
1062
1063
1064 /**
1065  * Ask the testbed controller to write the current overlay topology to
1066  * a file.  Naturally, the file will only contain a snapshot as the
1067  * topology may evolve all the time.
1068  *
1069  * @param controller overlay controller to inspect
1070  * @param filename name of the file the topology should
1071  *        be written to.
1072  */
1073 void
1074 GNUNET_TESTBED_overlay_write_topology_to_file (struct GNUNET_TESTBED_Controller *controller,
1075                                                const char *filename)
1076 {
1077   GNUNET_break (0);
1078 }
1079
1080
1081 /**
1082  * Creates a helper initialization message. Only for testing.
1083  *
1084  * @param cname the ip address of the controlling host
1085  * @param cfg the configuration that has to used to start the testbed service
1086  *          thru helper
1087  * @return the initialization message
1088  */
1089 struct GNUNET_TESTBED_HelperInit *
1090 GNUNET_TESTBED_create_helper_init_msg_ (const char *cname,
1091                                          const struct GNUNET_CONFIGURATION_Handle *cfg)
1092 {
1093   struct GNUNET_TESTBED_HelperInit *msg;
1094   char *config;
1095   char *xconfig;
1096   size_t config_size;
1097   size_t xconfig_size;
1098   uint16_t cname_len;
1099   uint16_t msg_size;
1100
1101   config = GNUNET_CONFIGURATION_serialize (cfg, &config_size);
1102   GNUNET_assert (NULL != config);
1103   xconfig_size =
1104     GNUNET_TESTBED_compress_config_ (config, config_size, &xconfig);
1105   GNUNET_free (config);
1106   cname_len = strlen (cname);
1107   msg_size = xconfig_size + cname_len + 1 + 
1108     sizeof (struct GNUNET_TESTBED_HelperInit);
1109   msg = GNUNET_realloc (xconfig, msg_size);
1110   (void) memmove ( ((void *) &msg[1]) + cname_len + 1, msg, xconfig_size);
1111   msg->header.size = htons (msg_size);
1112   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TESTBED_HELPER_INIT);
1113   msg->cname_size = htons (cname_len);
1114   msg->config_size = htons (config_size);
1115   (void) strcpy ((char *) &msg[1], cname);
1116   return msg;
1117 }
1118
1119
1120 /* end of testbed_api.c */