Merge commit 'ronnie/master'
[metze/ctdb/wip.git] / server / ctdb_daemon.c
1 /* 
2    ctdb daemon code
3
4    Copyright (C) Andrew Tridgell  2006
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3 of the License, or
9    (at your option) any later version.
10    
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15    
16    You should have received a copy of the GNU General Public License
17    along with this program; if not, see <http://www.gnu.org/licenses/>.
18 */
19
20 #include "includes.h"
21 #include "db_wrap.h"
22 #include "lib/tdb/include/tdb.h"
23 #include "lib/events/events.h"
24 #include "lib/util/dlinklist.h"
25 #include "system/network.h"
26 #include "system/filesys.h"
27 #include "system/wait.h"
28 #include "../include/ctdb.h"
29 #include "../include/ctdb_private.h"
30 #include <sys/socket.h>
31
32 static void daemon_incoming_packet(void *, struct ctdb_req_header *);
33
34
35 static void print_exit_message(void)
36 {
37         DEBUG(DEBUG_NOTICE,("CTDB daemon shutting down\n"));
38 }
39
40
41 /* called when the "startup" event script has finished */
42 static void ctdb_start_transport(struct ctdb_context *ctdb)
43 {
44         if (ctdb->methods == NULL) {
45                 DEBUG(DEBUG_ALERT,(__location__ " startup event finished but transport is DOWN.\n"));
46                 ctdb_fatal(ctdb, "transport is not initialized but startup completed");
47         }
48
49         /* start the transport running */
50         if (ctdb->methods->start(ctdb) != 0) {
51                 DEBUG(DEBUG_ALERT,("transport failed to start!\n"));
52                 ctdb_fatal(ctdb, "transport failed to start");
53         }
54
55         /* start the recovery daemon process */
56         if (ctdb_start_recoverd(ctdb) != 0) {
57                 DEBUG(DEBUG_ALERT,("Failed to start recovery daemon\n"));
58                 exit(11);
59         }
60
61         /* Make sure we log something when the daemon terminates */
62         atexit(print_exit_message);
63
64         /* start monitoring for connected/disconnected nodes */
65         ctdb_start_keepalive(ctdb);
66
67         /* start monitoring for node health */
68         ctdb_start_monitoring(ctdb);
69
70         /* start periodic update of tcp tickle lists */
71         ctdb_start_tcp_tickle_update(ctdb);
72
73         /* start listening for recovery daemon pings */
74         ctdb_control_recd_ping(ctdb);
75 }
76
77 static void block_signal(int signum)
78 {
79         struct sigaction act;
80
81         memset(&act, 0, sizeof(act));
82
83         act.sa_handler = SIG_IGN;
84         sigemptyset(&act.sa_mask);
85         sigaddset(&act.sa_mask, signum);
86         sigaction(signum, &act, NULL);
87 }
88
89
90 /*
91   send a packet to a client
92  */
93 static int daemon_queue_send(struct ctdb_client *client, struct ctdb_req_header *hdr)
94 {
95         client->ctdb->statistics.client_packets_sent++;
96         return ctdb_queue_send(client->queue, (uint8_t *)hdr, hdr->length);
97 }
98
99 /*
100   message handler for when we are in daemon mode. This redirects the message
101   to the right client
102  */
103 static void daemon_message_handler(struct ctdb_context *ctdb, uint64_t srvid, 
104                                     TDB_DATA data, void *private_data)
105 {
106         struct ctdb_client *client = talloc_get_type(private_data, struct ctdb_client);
107         struct ctdb_req_message *r;
108         int len;
109
110         /* construct a message to send to the client containing the data */
111         len = offsetof(struct ctdb_req_message, data) + data.dsize;
112         r = ctdbd_allocate_pkt(ctdb, ctdb, CTDB_REQ_MESSAGE, 
113                                len, struct ctdb_req_message);
114         CTDB_NO_MEMORY_VOID(ctdb, r);
115
116         talloc_set_name_const(r, "req_message packet");
117
118         r->srvid         = srvid;
119         r->datalen       = data.dsize;
120         memcpy(&r->data[0], data.dptr, data.dsize);
121
122         daemon_queue_send(client, &r->hdr);
123
124         talloc_free(r);
125 }
126                                            
127
128 /*
129   this is called when the ctdb daemon received a ctdb request to 
130   set the srvid from the client
131  */
132 int daemon_register_message_handler(struct ctdb_context *ctdb, uint32_t client_id, uint64_t srvid)
133 {
134         struct ctdb_client *client = ctdb_reqid_find(ctdb, client_id, struct ctdb_client);
135         int res;
136         if (client == NULL) {
137                 DEBUG(DEBUG_ERR,("Bad client_id in daemon_request_register_message_handler\n"));
138                 return -1;
139         }
140         res = ctdb_register_message_handler(ctdb, client, srvid, daemon_message_handler, client);
141         if (res != 0) {
142                 DEBUG(DEBUG_ERR,(__location__ " Failed to register handler %llu in daemon\n", 
143                          (unsigned long long)srvid));
144         } else {
145                 DEBUG(DEBUG_INFO,(__location__ " Registered message handler for srvid=%llu\n", 
146                          (unsigned long long)srvid));
147         }
148
149         /* this is a hack for Samba - we now know the pid of the Samba client */
150         if ((srvid & 0xFFFFFFFF) == srvid &&
151             kill(srvid, 0) == 0) {
152                 client->pid = srvid;
153                 DEBUG(DEBUG_INFO,(__location__ " Registered PID %u for client %u\n",
154                          (unsigned)client->pid, client_id));
155         }
156         return res;
157 }
158
159 /*
160   this is called when the ctdb daemon received a ctdb request to 
161   remove a srvid from the client
162  */
163 int daemon_deregister_message_handler(struct ctdb_context *ctdb, uint32_t client_id, uint64_t srvid)
164 {
165         struct ctdb_client *client = ctdb_reqid_find(ctdb, client_id, struct ctdb_client);
166         if (client == NULL) {
167                 DEBUG(DEBUG_ERR,("Bad client_id in daemon_request_deregister_message_handler\n"));
168                 return -1;
169         }
170         return ctdb_deregister_message_handler(ctdb, srvid, client);
171 }
172
173
174 /*
175   destroy a ctdb_client
176 */
177 static int ctdb_client_destructor(struct ctdb_client *client)
178 {
179         ctdb_takeover_client_destructor_hook(client);
180         ctdb_reqid_remove(client->ctdb, client->client_id);
181         client->ctdb->statistics.num_clients--;
182
183         if (client->num_persistent_updates != 0) {
184                 DEBUG(DEBUG_ERR,(__location__ " Client disconnecting with %u persistent updates in flight. Starting recovery\n", client->num_persistent_updates));
185                 client->ctdb->recovery_mode = CTDB_RECOVERY_ACTIVE;
186         }
187
188         return 0;
189 }
190
191
192 /*
193   this is called when the ctdb daemon received a ctdb request message
194   from a local client over the unix domain socket
195  */
196 static void daemon_request_message_from_client(struct ctdb_client *client, 
197                                                struct ctdb_req_message *c)
198 {
199         TDB_DATA data;
200         int res;
201
202         /* maybe the message is for another client on this node */
203         if (ctdb_get_pnn(client->ctdb)==c->hdr.destnode) {
204                 ctdb_request_message(client->ctdb, (struct ctdb_req_header *)c);
205                 return;
206         }
207
208         /* its for a remote node */
209         data.dptr = &c->data[0];
210         data.dsize = c->datalen;
211         res = ctdb_daemon_send_message(client->ctdb, c->hdr.destnode,
212                                        c->srvid, data);
213         if (res != 0) {
214                 DEBUG(DEBUG_ERR,(__location__ " Failed to send message to remote node %u\n",
215                          c->hdr.destnode));
216         }
217 }
218
219
220 struct daemon_call_state {
221         struct ctdb_client *client;
222         uint32_t reqid;
223         struct ctdb_call *call;
224         struct timeval start_time;
225 };
226
227 /* 
228    complete a call from a client 
229 */
230 static void daemon_call_from_client_callback(struct ctdb_call_state *state)
231 {
232         struct daemon_call_state *dstate = talloc_get_type(state->async.private_data, 
233                                                            struct daemon_call_state);
234         struct ctdb_reply_call *r;
235         int res;
236         uint32_t length;
237         struct ctdb_client *client = dstate->client;
238         struct ctdb_db_context *ctdb_db = state->ctdb_db;
239
240         talloc_steal(client, dstate);
241         talloc_steal(dstate, dstate->call);
242
243         res = ctdb_daemon_call_recv(state, dstate->call);
244         if (res != 0) {
245                 DEBUG(DEBUG_ERR, (__location__ " ctdbd_call_recv() returned error\n"));
246                 client->ctdb->statistics.pending_calls--;
247                 ctdb_latency(ctdb_db, "call_from_client_cb 1", &client->ctdb->statistics.max_call_latency, dstate->start_time);
248                 return;
249         }
250
251         length = offsetof(struct ctdb_reply_call, data) + dstate->call->reply_data.dsize;
252         r = ctdbd_allocate_pkt(client->ctdb, dstate, CTDB_REPLY_CALL, 
253                                length, struct ctdb_reply_call);
254         if (r == NULL) {
255                 DEBUG(DEBUG_ERR, (__location__ " Failed to allocate reply_call in ctdb daemon\n"));
256                 client->ctdb->statistics.pending_calls--;
257                 ctdb_latency(ctdb_db, "call_from_client_cb 2", &client->ctdb->statistics.max_call_latency, dstate->start_time);
258                 return;
259         }
260         r->hdr.reqid        = dstate->reqid;
261         r->datalen          = dstate->call->reply_data.dsize;
262         memcpy(&r->data[0], dstate->call->reply_data.dptr, r->datalen);
263
264         res = daemon_queue_send(client, &r->hdr);
265         if (res != 0) {
266                 DEBUG(DEBUG_ERR, (__location__ " Failed to queue packet from daemon to client\n"));
267         }
268         ctdb_latency(ctdb_db, "call_from_client_cb 3", &client->ctdb->statistics.max_call_latency, dstate->start_time);
269         talloc_free(dstate);
270         client->ctdb->statistics.pending_calls--;
271 }
272
273 struct ctdb_daemon_packet_wrap {
274         struct ctdb_context *ctdb;
275         uint32_t client_id;
276 };
277
278 /*
279   a wrapper to catch disconnected clients
280  */
281 static void daemon_incoming_packet_wrap(void *p, struct ctdb_req_header *hdr)
282 {
283         struct ctdb_client *client;
284         struct ctdb_daemon_packet_wrap *w = talloc_get_type(p, 
285                                                             struct ctdb_daemon_packet_wrap);
286         if (w == NULL) {
287                 DEBUG(DEBUG_CRIT,(__location__ " Bad packet type '%s'\n", talloc_get_name(p)));
288                 return;
289         }
290
291         client = ctdb_reqid_find(w->ctdb, w->client_id, struct ctdb_client);
292         if (client == NULL) {
293                 DEBUG(DEBUG_ERR,(__location__ " Packet for disconnected client %u\n",
294                          w->client_id));
295                 talloc_free(w);
296                 return;
297         }
298         talloc_free(w);
299
300         /* process it */
301         daemon_incoming_packet(client, hdr);    
302 }
303
304
305 /*
306   this is called when the ctdb daemon received a ctdb request call
307   from a local client over the unix domain socket
308  */
309 static void daemon_request_call_from_client(struct ctdb_client *client, 
310                                             struct ctdb_req_call *c)
311 {
312         struct ctdb_call_state *state;
313         struct ctdb_db_context *ctdb_db;
314         struct daemon_call_state *dstate;
315         struct ctdb_call *call;
316         struct ctdb_ltdb_header header;
317         TDB_DATA key, data;
318         int ret;
319         struct ctdb_context *ctdb = client->ctdb;
320         struct ctdb_daemon_packet_wrap *w;
321
322         ctdb->statistics.total_calls++;
323         ctdb->statistics.pending_calls++;
324
325         ctdb_db = find_ctdb_db(client->ctdb, c->db_id);
326         if (!ctdb_db) {
327                 DEBUG(DEBUG_ERR, (__location__ " Unknown database in request. db_id==0x%08x",
328                           c->db_id));
329                 ctdb->statistics.pending_calls--;
330                 return;
331         }
332
333         key.dptr = c->data;
334         key.dsize = c->keylen;
335
336         w = talloc(ctdb, struct ctdb_daemon_packet_wrap);
337         CTDB_NO_MEMORY_VOID(ctdb, w);   
338
339         w->ctdb = ctdb;
340         w->client_id = client->client_id;
341
342         ret = ctdb_ltdb_lock_fetch_requeue(ctdb_db, key, &header, 
343                                            (struct ctdb_req_header *)c, &data,
344                                            daemon_incoming_packet_wrap, w, True);
345         if (ret == -2) {
346                 /* will retry later */
347                 ctdb->statistics.pending_calls--;
348                 return;
349         }
350
351         talloc_free(w);
352
353         if (ret != 0) {
354                 DEBUG(DEBUG_ERR,(__location__ " Unable to fetch record\n"));
355                 ctdb->statistics.pending_calls--;
356                 return;
357         }
358
359         dstate = talloc(client, struct daemon_call_state);
360         if (dstate == NULL) {
361                 ctdb_ltdb_unlock(ctdb_db, key);
362                 DEBUG(DEBUG_ERR,(__location__ " Unable to allocate dstate\n"));
363                 ctdb->statistics.pending_calls--;
364                 return;
365         }
366         dstate->start_time = timeval_current();
367         dstate->client = client;
368         dstate->reqid  = c->hdr.reqid;
369         talloc_steal(dstate, data.dptr);
370
371         call = dstate->call = talloc_zero(dstate, struct ctdb_call);
372         if (call == NULL) {
373                 ctdb_ltdb_unlock(ctdb_db, key);
374                 DEBUG(DEBUG_ERR,(__location__ " Unable to allocate call\n"));
375                 ctdb->statistics.pending_calls--;
376                 ctdb_latency(ctdb_db, "call_from_client 1", &ctdb->statistics.max_call_latency, dstate->start_time);
377                 return;
378         }
379
380         call->call_id = c->callid;
381         call->key = key;
382         call->call_data.dptr = c->data + c->keylen;
383         call->call_data.dsize = c->calldatalen;
384         call->flags = c->flags;
385
386         if (header.dmaster == ctdb->pnn) {
387                 state = ctdb_call_local_send(ctdb_db, call, &header, &data);
388         } else {
389                 state = ctdb_daemon_call_send_remote(ctdb_db, call, &header);
390         }
391
392         ctdb_ltdb_unlock(ctdb_db, key);
393
394         if (state == NULL) {
395                 DEBUG(DEBUG_ERR,(__location__ " Unable to setup call send\n"));
396                 ctdb->statistics.pending_calls--;
397                 ctdb_latency(ctdb_db, "call_from_client 2", &ctdb->statistics.max_call_latency, dstate->start_time);
398                 return;
399         }
400         talloc_steal(state, dstate);
401         talloc_steal(client, state);
402
403         state->async.fn = daemon_call_from_client_callback;
404         state->async.private_data = dstate;
405 }
406
407
408 static void daemon_request_control_from_client(struct ctdb_client *client, 
409                                                struct ctdb_req_control *c);
410
411 /* data contains a packet from the client */
412 static void daemon_incoming_packet(void *p, struct ctdb_req_header *hdr)
413 {
414         struct ctdb_client *client = talloc_get_type(p, struct ctdb_client);
415         TALLOC_CTX *tmp_ctx;
416         struct ctdb_context *ctdb = client->ctdb;
417
418         /* place the packet as a child of a tmp_ctx. We then use
419            talloc_free() below to free it. If any of the calls want
420            to keep it, then they will steal it somewhere else, and the
421            talloc_free() will be a no-op */
422         tmp_ctx = talloc_new(client);
423         talloc_steal(tmp_ctx, hdr);
424
425         if (hdr->ctdb_magic != CTDB_MAGIC) {
426                 ctdb_set_error(client->ctdb, "Non CTDB packet rejected in daemon\n");
427                 goto done;
428         }
429
430         if (hdr->ctdb_version != CTDB_VERSION) {
431                 ctdb_set_error(client->ctdb, "Bad CTDB version 0x%x rejected in daemon\n", hdr->ctdb_version);
432                 goto done;
433         }
434
435         switch (hdr->operation) {
436         case CTDB_REQ_CALL:
437                 ctdb->statistics.client.req_call++;
438                 daemon_request_call_from_client(client, (struct ctdb_req_call *)hdr);
439                 break;
440
441         case CTDB_REQ_MESSAGE:
442                 ctdb->statistics.client.req_message++;
443                 daemon_request_message_from_client(client, (struct ctdb_req_message *)hdr);
444                 break;
445
446         case CTDB_REQ_CONTROL:
447                 ctdb->statistics.client.req_control++;
448                 daemon_request_control_from_client(client, (struct ctdb_req_control *)hdr);
449                 break;
450
451         default:
452                 DEBUG(DEBUG_CRIT,(__location__ " daemon: unrecognized operation %u\n",
453                          hdr->operation));
454         }
455
456 done:
457         talloc_free(tmp_ctx);
458 }
459
460 /*
461   called when the daemon gets a incoming packet
462  */
463 static void ctdb_daemon_read_cb(uint8_t *data, size_t cnt, void *args)
464 {
465         struct ctdb_client *client = talloc_get_type(args, struct ctdb_client);
466         struct ctdb_req_header *hdr;
467
468         if (cnt == 0) {
469                 talloc_free(client);
470                 return;
471         }
472
473         client->ctdb->statistics.client_packets_recv++;
474
475         if (cnt < sizeof(*hdr)) {
476                 ctdb_set_error(client->ctdb, "Bad packet length %u in daemon\n", 
477                                (unsigned)cnt);
478                 return;
479         }
480         hdr = (struct ctdb_req_header *)data;
481         if (cnt != hdr->length) {
482                 ctdb_set_error(client->ctdb, "Bad header length %u expected %u\n in daemon", 
483                                (unsigned)hdr->length, (unsigned)cnt);
484                 return;
485         }
486
487         if (hdr->ctdb_magic != CTDB_MAGIC) {
488                 ctdb_set_error(client->ctdb, "Non CTDB packet rejected\n");
489                 return;
490         }
491
492         if (hdr->ctdb_version != CTDB_VERSION) {
493                 ctdb_set_error(client->ctdb, "Bad CTDB version 0x%x rejected in daemon\n", hdr->ctdb_version);
494                 return;
495         }
496
497         DEBUG(DEBUG_DEBUG,(__location__ " client request %u of type %u length %u from "
498                  "node %u to %u\n", hdr->reqid, hdr->operation, hdr->length,
499                  hdr->srcnode, hdr->destnode));
500
501         /* it is the responsibility of the incoming packet function to free 'data' */
502         daemon_incoming_packet(client, hdr);
503 }
504
505 static void ctdb_accept_client(struct event_context *ev, struct fd_event *fde, 
506                          uint16_t flags, void *private_data)
507 {
508         struct sockaddr_un addr;
509         socklen_t len;
510         int fd;
511         struct ctdb_context *ctdb = talloc_get_type(private_data, struct ctdb_context);
512         struct ctdb_client *client;
513 #ifdef _AIX
514         struct peercred_struct cr;
515         socklen_t crl = sizeof(struct peercred_struct);
516 #else
517         struct ucred cr;
518         socklen_t crl = sizeof(struct ucred);
519 #endif
520
521         memset(&addr, 0, sizeof(addr));
522         len = sizeof(addr);
523         fd = accept(ctdb->daemon.sd, (struct sockaddr *)&addr, &len);
524         if (fd == -1) {
525                 return;
526         }
527
528         set_nonblocking(fd);
529         set_close_on_exec(fd);
530
531         client = talloc_zero(ctdb, struct ctdb_client);
532 #ifdef _AIX
533         if (getsockopt(fd, SOL_SOCKET, SO_PEERID, &cr, &crl) == 0) {
534 #else
535         if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &cr, &crl) == 0) {
536 #endif
537                 talloc_asprintf(client, "struct ctdb_client: pid:%u", (unsigned)cr.pid);
538         }
539
540         client->ctdb = ctdb;
541         client->fd = fd;
542         client->client_id = ctdb_reqid_new(ctdb, client);
543         ctdb->statistics.num_clients++;
544
545         client->queue = ctdb_queue_setup(ctdb, client, fd, CTDB_DS_ALIGNMENT, 
546                                          ctdb_daemon_read_cb, client);
547
548         talloc_set_destructor(client, ctdb_client_destructor);
549 }
550
551
552
553 /*
554   create a unix domain socket and bind it
555   return a file descriptor open on the socket 
556 */
557 static int ux_socket_bind(struct ctdb_context *ctdb)
558 {
559         struct sockaddr_un addr;
560
561         ctdb->daemon.sd = socket(AF_UNIX, SOCK_STREAM, 0);
562         if (ctdb->daemon.sd == -1) {
563                 return -1;
564         }
565
566         set_close_on_exec(ctdb->daemon.sd);
567         set_nonblocking(ctdb->daemon.sd);
568
569         memset(&addr, 0, sizeof(addr));
570         addr.sun_family = AF_UNIX;
571         strncpy(addr.sun_path, ctdb->daemon.name, sizeof(addr.sun_path));
572
573         if (bind(ctdb->daemon.sd, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
574                 DEBUG(DEBUG_CRIT,("Unable to bind on ctdb socket '%s'\n", ctdb->daemon.name));
575                 goto failed;
576         }       
577
578         if (chown(ctdb->daemon.name, geteuid(), getegid()) != 0 ||
579             chmod(ctdb->daemon.name, 0700) != 0) {
580                 DEBUG(DEBUG_CRIT,("Unable to secure ctdb socket '%s', ctdb->daemon.name\n", ctdb->daemon.name));
581                 goto failed;
582         } 
583
584
585         if (listen(ctdb->daemon.sd, 100) != 0) {
586                 DEBUG(DEBUG_CRIT,("Unable to listen on ctdb socket '%s'\n", ctdb->daemon.name));
587                 goto failed;
588         }
589
590         return 0;
591
592 failed:
593         close(ctdb->daemon.sd);
594         ctdb->daemon.sd = -1;
595         return -1;      
596 }
597
598 /*
599   delete the socket on exit - called on destruction of autofree context
600  */
601 static int unlink_destructor(const char *name)
602 {
603         unlink(name);
604         return 0;
605 }
606
607 static void sig_child_handler(struct event_context *ev,
608         struct signal_event *se, int signum, int count,
609         void *dont_care, 
610         void *private_data)
611 {
612 //      struct ctdb_context *ctdb = talloc_get_type(private_data, struct ctdb_context);
613         int status;
614         pid_t pid = -1;
615
616         while (pid != 0) {
617                 pid = waitpid(-1, &status, WNOHANG);
618                 if (pid == -1) {
619                         DEBUG(DEBUG_ERR, (__location__ " waitpid() returned error. errno:%d\n", errno));
620                         return;
621                 }
622                 if (pid > 0) {
623                         DEBUG(DEBUG_DEBUG, ("SIGCHLD from %d\n", (int)pid));
624                 }
625         }
626 }
627
628 /*
629   start the protocol going as a daemon
630 */
631 int ctdb_start_daemon(struct ctdb_context *ctdb, bool do_fork)
632 {
633         int res, ret = -1;
634         struct fd_event *fde;
635         const char *domain_socket_name;
636         struct signal_event *se;
637
638         /* get rid of any old sockets */
639         unlink(ctdb->daemon.name);
640
641         /* create a unix domain stream socket to listen to */
642         res = ux_socket_bind(ctdb);
643         if (res!=0) {
644                 DEBUG(DEBUG_ALERT,(__location__ " Failed to open CTDB unix domain socket\n"));
645                 exit(10);
646         }
647
648         if (do_fork && fork()) {
649                 return 0;
650         }
651
652         tdb_reopen_all(False);
653
654         if (do_fork) {
655                 setsid();
656                 close(0);
657                 if (open("/dev/null", O_RDONLY) != 0) {
658                         DEBUG(DEBUG_ALERT,(__location__ " Failed to setup stdin on /dev/null\n"));
659                         exit(11);
660                 }
661         }
662         block_signal(SIGPIPE);
663
664         if (ctdb->do_setsched) {
665                 /* try to set us up as realtime */
666                 ctdb_set_scheduler(ctdb);
667         }
668
669         /* ensure the socket is deleted on exit of the daemon */
670         domain_socket_name = talloc_strdup(talloc_autofree_context(), ctdb->daemon.name);
671         talloc_set_destructor(domain_socket_name, unlink_destructor);   
672
673         ctdb->ev = event_context_init(NULL);
674
675         ctdb_set_child_logging(ctdb);
676
677         /* force initial recovery for election */
678         ctdb->recovery_mode = CTDB_RECOVERY_ACTIVE;
679
680         if (strcmp(ctdb->transport, "tcp") == 0) {
681                 int ctdb_tcp_init(struct ctdb_context *);
682                 ret = ctdb_tcp_init(ctdb);
683         }
684 #ifdef USE_INFINIBAND
685         if (strcmp(ctdb->transport, "ib") == 0) {
686                 int ctdb_ibw_init(struct ctdb_context *);
687                 ret = ctdb_ibw_init(ctdb);
688         }
689 #endif
690         if (ret != 0) {
691                 DEBUG(DEBUG_ERR,("Failed to initialise transport '%s'\n", ctdb->transport));
692                 return -1;
693         }
694
695         if (ctdb->methods == NULL) {
696                 DEBUG(DEBUG_ALERT,(__location__ " Can not initialize transport. ctdb->methods is NULL\n"));
697                 ctdb_fatal(ctdb, "transport is unavailable. can not initialize.");
698         }
699
700         /* initialise the transport  */
701         if (ctdb->methods->initialise(ctdb) != 0) {
702                 ctdb_fatal(ctdb, "transport failed to initialise");
703         }
704
705         /* attach to any existing persistent databases */
706         if (ctdb_attach_persistent(ctdb) != 0) {
707                 ctdb_fatal(ctdb, "Failed to attach to persistent databases\n");         
708         }
709
710         /* start frozen, then let the first election sort things out */
711         if (!ctdb_blocking_freeze(ctdb)) {
712                 ctdb_fatal(ctdb, "Failed to get initial freeze\n");
713         }
714
715         /* now start accepting clients, only can do this once frozen */
716         fde = event_add_fd(ctdb->ev, ctdb, ctdb->daemon.sd, 
717                            EVENT_FD_READ|EVENT_FD_AUTOCLOSE, 
718                            ctdb_accept_client, ctdb);
719
720         /* tell all other nodes we've just started up */
721         ctdb_daemon_send_control(ctdb, CTDB_BROADCAST_ALL,
722                                  0, CTDB_CONTROL_STARTUP, 0,
723                                  CTDB_CTRL_FLAG_NOREPLY,
724                                  tdb_null, NULL, NULL);
725
726         /* release any IPs we hold from previous runs of the daemon */
727         ctdb_release_all_ips(ctdb);
728
729         /* start the transport going */
730         ctdb_start_transport(ctdb);
731
732         /* set up a handler to pick up sigchld */
733         se = event_add_signal(ctdb->ev, ctdb,
734                                      SIGCHLD, 0,
735                                      sig_child_handler,
736                                      ctdb);
737         if (se == NULL) {
738                 DEBUG(DEBUG_CRIT,("Failed to set up signal handler for SIGCHLD\n"));
739                 exit(1);
740         }
741           
742         /* go into a wait loop to allow other nodes to complete */
743         event_loop_wait(ctdb->ev);
744
745         DEBUG(DEBUG_CRIT,("event_loop_wait() returned. this should not happen\n"));
746         exit(1);
747 }
748
749 /*
750   allocate a packet for use in daemon<->daemon communication
751  */
752 struct ctdb_req_header *_ctdb_transport_allocate(struct ctdb_context *ctdb,
753                                                  TALLOC_CTX *mem_ctx, 
754                                                  enum ctdb_operation operation, 
755                                                  size_t length, size_t slength,
756                                                  const char *type)
757 {
758         int size;
759         struct ctdb_req_header *hdr;
760
761         length = MAX(length, slength);
762         size = (length+(CTDB_DS_ALIGNMENT-1)) & ~(CTDB_DS_ALIGNMENT-1);
763
764         if (ctdb->methods == NULL) {
765                 DEBUG(DEBUG_ERR,(__location__ " Unable to allocate transport packet for operation %u of length %u. Transport is DOWN.\n",
766                          operation, (unsigned)length));
767                 return NULL;
768         }
769
770         hdr = (struct ctdb_req_header *)ctdb->methods->allocate_pkt(mem_ctx, size);
771         if (hdr == NULL) {
772                 DEBUG(DEBUG_ERR,("Unable to allocate transport packet for operation %u of length %u\n",
773                          operation, (unsigned)length));
774                 return NULL;
775         }
776         talloc_set_name_const(hdr, type);
777         memset(hdr, 0, slength);
778         hdr->length       = length;
779         hdr->operation    = operation;
780         hdr->ctdb_magic   = CTDB_MAGIC;
781         hdr->ctdb_version = CTDB_VERSION;
782         hdr->generation   = ctdb->vnn_map->generation;
783         hdr->srcnode      = ctdb->pnn;
784
785         return hdr;     
786 }
787
788 struct daemon_control_state {
789         struct daemon_control_state *next, *prev;
790         struct ctdb_client *client;
791         struct ctdb_req_control *c;
792         uint32_t reqid;
793         struct ctdb_node *node;
794 };
795
796 /*
797   callback when a control reply comes in
798  */
799 static void daemon_control_callback(struct ctdb_context *ctdb,
800                                     int32_t status, TDB_DATA data, 
801                                     const char *errormsg,
802                                     void *private_data)
803 {
804         struct daemon_control_state *state = talloc_get_type(private_data, 
805                                                              struct daemon_control_state);
806         struct ctdb_client *client = state->client;
807         struct ctdb_reply_control *r;
808         size_t len;
809
810         /* construct a message to send to the client containing the data */
811         len = offsetof(struct ctdb_reply_control, data) + data.dsize;
812         if (errormsg) {
813                 len += strlen(errormsg);
814         }
815         r = ctdbd_allocate_pkt(ctdb, state, CTDB_REPLY_CONTROL, len, 
816                                struct ctdb_reply_control);
817         CTDB_NO_MEMORY_VOID(ctdb, r);
818
819         r->hdr.reqid     = state->reqid;
820         r->status        = status;
821         r->datalen       = data.dsize;
822         r->errorlen = 0;
823         memcpy(&r->data[0], data.dptr, data.dsize);
824         if (errormsg) {
825                 r->errorlen = strlen(errormsg);
826                 memcpy(&r->data[r->datalen], errormsg, r->errorlen);
827         }
828
829         daemon_queue_send(client, &r->hdr);
830
831         talloc_free(state);
832 }
833
834 /*
835   fail all pending controls to a disconnected node
836  */
837 void ctdb_daemon_cancel_controls(struct ctdb_context *ctdb, struct ctdb_node *node)
838 {
839         struct daemon_control_state *state;
840         while ((state = node->pending_controls)) {
841                 DLIST_REMOVE(node->pending_controls, state);
842                 daemon_control_callback(ctdb, (uint32_t)-1, tdb_null, 
843                                         "node is disconnected", state);
844         }
845 }
846
847 /*
848   destroy a daemon_control_state
849  */
850 static int daemon_control_destructor(struct daemon_control_state *state)
851 {
852         if (state->node) {
853                 DLIST_REMOVE(state->node->pending_controls, state);
854         }
855         return 0;
856 }
857
858 /*
859   this is called when the ctdb daemon received a ctdb request control
860   from a local client over the unix domain socket
861  */
862 static void daemon_request_control_from_client(struct ctdb_client *client, 
863                                                struct ctdb_req_control *c)
864 {
865         TDB_DATA data;
866         int res;
867         struct daemon_control_state *state;
868         TALLOC_CTX *tmp_ctx = talloc_new(client);
869
870         if (c->hdr.destnode == CTDB_CURRENT_NODE) {
871                 c->hdr.destnode = client->ctdb->pnn;
872         }
873
874         state = talloc(client, struct daemon_control_state);
875         CTDB_NO_MEMORY_VOID(client->ctdb, state);
876
877         state->client = client;
878         state->c = talloc_steal(state, c);
879         state->reqid = c->hdr.reqid;
880         if (ctdb_validate_pnn(client->ctdb, c->hdr.destnode)) {
881                 state->node = client->ctdb->nodes[c->hdr.destnode];
882                 DLIST_ADD(state->node->pending_controls, state);
883         } else {
884                 state->node = NULL;
885         }
886
887         talloc_set_destructor(state, daemon_control_destructor);
888
889         if (c->flags & CTDB_CTRL_FLAG_NOREPLY) {
890                 talloc_steal(tmp_ctx, state);
891         }
892         
893         data.dptr = &c->data[0];
894         data.dsize = c->datalen;
895         res = ctdb_daemon_send_control(client->ctdb, c->hdr.destnode,
896                                        c->srvid, c->opcode, client->client_id,
897                                        c->flags,
898                                        data, daemon_control_callback,
899                                        state);
900         if (res != 0) {
901                 DEBUG(DEBUG_ERR,(__location__ " Failed to send control to remote node %u\n",
902                          c->hdr.destnode));
903         }
904
905         talloc_free(tmp_ctx);
906 }
907
908 /*
909   register a call function
910 */
911 int ctdb_daemon_set_call(struct ctdb_context *ctdb, uint32_t db_id,
912                          ctdb_fn_t fn, int id)
913 {
914         struct ctdb_registered_call *call;
915         struct ctdb_db_context *ctdb_db;
916
917         ctdb_db = find_ctdb_db(ctdb, db_id);
918         if (ctdb_db == NULL) {
919                 return -1;
920         }
921
922         call = talloc(ctdb_db, struct ctdb_registered_call);
923         call->fn = fn;
924         call->id = id;
925
926         DLIST_ADD(ctdb_db->calls, call);        
927         return 0;
928 }
929
930
931
932 /*
933   this local messaging handler is ugly, but is needed to prevent
934   recursion in ctdb_send_message() when the destination node is the
935   same as the source node
936  */
937 struct ctdb_local_message {
938         struct ctdb_context *ctdb;
939         uint64_t srvid;
940         TDB_DATA data;
941 };
942
943 static void ctdb_local_message_trigger(struct event_context *ev, struct timed_event *te, 
944                                        struct timeval t, void *private_data)
945 {
946         struct ctdb_local_message *m = talloc_get_type(private_data, 
947                                                        struct ctdb_local_message);
948         int res;
949
950         res = ctdb_dispatch_message(m->ctdb, m->srvid, m->data);
951         if (res != 0) {
952                 DEBUG(DEBUG_ERR, (__location__ " Failed to dispatch message for srvid=%llu\n", 
953                           (unsigned long long)m->srvid));
954         }
955         talloc_free(m);
956 }
957
958 static int ctdb_local_message(struct ctdb_context *ctdb, uint64_t srvid, TDB_DATA data)
959 {
960         struct ctdb_local_message *m;
961         m = talloc(ctdb, struct ctdb_local_message);
962         CTDB_NO_MEMORY(ctdb, m);
963
964         m->ctdb = ctdb;
965         m->srvid = srvid;
966         m->data  = data;
967         m->data.dptr = talloc_memdup(m, m->data.dptr, m->data.dsize);
968         if (m->data.dptr == NULL) {
969                 talloc_free(m);
970                 return -1;
971         }
972
973         /* this needs to be done as an event to prevent recursion */
974         event_add_timed(ctdb->ev, m, timeval_zero(), ctdb_local_message_trigger, m);
975         return 0;
976 }
977
978 /*
979   send a ctdb message
980 */
981 int ctdb_daemon_send_message(struct ctdb_context *ctdb, uint32_t pnn,
982                              uint64_t srvid, TDB_DATA data)
983 {
984         struct ctdb_req_message *r;
985         int len;
986
987         /* see if this is a message to ourselves */
988         if (pnn == ctdb->pnn) {
989                 return ctdb_local_message(ctdb, srvid, data);
990         }
991
992         len = offsetof(struct ctdb_req_message, data) + data.dsize;
993         r = ctdb_transport_allocate(ctdb, ctdb, CTDB_REQ_MESSAGE, len,
994                                     struct ctdb_req_message);
995         CTDB_NO_MEMORY(ctdb, r);
996
997         r->hdr.destnode  = pnn;
998         r->srvid         = srvid;
999         r->datalen       = data.dsize;
1000         memcpy(&r->data[0], data.dptr, data.dsize);
1001
1002         ctdb_queue_packet(ctdb, &r->hdr);
1003
1004         talloc_free(r);
1005         return 0;
1006 }
1007