add missing checks on so far ignored return values
[sahlberg/ctdb.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         if (client->ctdb->statistics.num_clients) {
182                 client->ctdb->statistics.num_clients--;
183         }
184
185         if (client->num_persistent_updates != 0) {
186                 DEBUG(DEBUG_ERR,(__location__ " Client disconnecting with %u persistent updates in flight. Starting recovery\n", client->num_persistent_updates));
187                 client->ctdb->recovery_mode = CTDB_RECOVERY_ACTIVE;
188         }
189
190         return 0;
191 }
192
193
194 /*
195   this is called when the ctdb daemon received a ctdb request message
196   from a local client over the unix domain socket
197  */
198 static void daemon_request_message_from_client(struct ctdb_client *client, 
199                                                struct ctdb_req_message *c)
200 {
201         TDB_DATA data;
202         int res;
203
204         /* maybe the message is for another client on this node */
205         if (ctdb_get_pnn(client->ctdb)==c->hdr.destnode) {
206                 ctdb_request_message(client->ctdb, (struct ctdb_req_header *)c);
207                 return;
208         }
209
210         /* its for a remote node */
211         data.dptr = &c->data[0];
212         data.dsize = c->datalen;
213         res = ctdb_daemon_send_message(client->ctdb, c->hdr.destnode,
214                                        c->srvid, data);
215         if (res != 0) {
216                 DEBUG(DEBUG_ERR,(__location__ " Failed to send message to remote node %u\n",
217                          c->hdr.destnode));
218         }
219 }
220
221
222 struct daemon_call_state {
223         struct ctdb_client *client;
224         uint32_t reqid;
225         struct ctdb_call *call;
226         struct timeval start_time;
227 };
228
229 /* 
230    complete a call from a client 
231 */
232 static void daemon_call_from_client_callback(struct ctdb_call_state *state)
233 {
234         struct daemon_call_state *dstate = talloc_get_type(state->async.private_data, 
235                                                            struct daemon_call_state);
236         struct ctdb_reply_call *r;
237         int res;
238         uint32_t length;
239         struct ctdb_client *client = dstate->client;
240         struct ctdb_db_context *ctdb_db = state->ctdb_db;
241
242         talloc_steal(client, dstate);
243         talloc_steal(dstate, dstate->call);
244
245         res = ctdb_daemon_call_recv(state, dstate->call);
246         if (res != 0) {
247                 DEBUG(DEBUG_ERR, (__location__ " ctdbd_call_recv() returned error\n"));
248                 if (client->ctdb->statistics.pending_calls > 0) {
249                         client->ctdb->statistics.pending_calls--;
250                 }
251                 ctdb_latency(ctdb_db, "call_from_client_cb 1", &client->ctdb->statistics.max_call_latency, dstate->start_time);
252                 return;
253         }
254
255         length = offsetof(struct ctdb_reply_call, data) + dstate->call->reply_data.dsize;
256         r = ctdbd_allocate_pkt(client->ctdb, dstate, CTDB_REPLY_CALL, 
257                                length, struct ctdb_reply_call);
258         if (r == NULL) {
259                 DEBUG(DEBUG_ERR, (__location__ " Failed to allocate reply_call in ctdb daemon\n"));
260                 if (client->ctdb->statistics.pending_calls > 0) {
261                         client->ctdb->statistics.pending_calls--;
262                 }
263                 ctdb_latency(ctdb_db, "call_from_client_cb 2", &client->ctdb->statistics.max_call_latency, dstate->start_time);
264                 return;
265         }
266         r->hdr.reqid        = dstate->reqid;
267         r->datalen          = dstate->call->reply_data.dsize;
268         memcpy(&r->data[0], dstate->call->reply_data.dptr, r->datalen);
269
270         res = daemon_queue_send(client, &r->hdr);
271         if (res != 0) {
272                 DEBUG(DEBUG_ERR, (__location__ " Failed to queue packet from daemon to client\n"));
273         }
274         ctdb_latency(ctdb_db, "call_from_client_cb 3", &client->ctdb->statistics.max_call_latency, dstate->start_time);
275         talloc_free(dstate);
276         if (client->ctdb->statistics.pending_calls > 0) {
277                 client->ctdb->statistics.pending_calls--;
278         }
279 }
280
281 struct ctdb_daemon_packet_wrap {
282         struct ctdb_context *ctdb;
283         uint32_t client_id;
284 };
285
286 /*
287   a wrapper to catch disconnected clients
288  */
289 static void daemon_incoming_packet_wrap(void *p, struct ctdb_req_header *hdr)
290 {
291         struct ctdb_client *client;
292         struct ctdb_daemon_packet_wrap *w = talloc_get_type(p, 
293                                                             struct ctdb_daemon_packet_wrap);
294         if (w == NULL) {
295                 DEBUG(DEBUG_CRIT,(__location__ " Bad packet type '%s'\n", talloc_get_name(p)));
296                 return;
297         }
298
299         client = ctdb_reqid_find(w->ctdb, w->client_id, struct ctdb_client);
300         if (client == NULL) {
301                 DEBUG(DEBUG_ERR,(__location__ " Packet for disconnected client %u\n",
302                          w->client_id));
303                 talloc_free(w);
304                 return;
305         }
306         talloc_free(w);
307
308         /* process it */
309         daemon_incoming_packet(client, hdr);    
310 }
311
312
313 /*
314   this is called when the ctdb daemon received a ctdb request call
315   from a local client over the unix domain socket
316  */
317 static void daemon_request_call_from_client(struct ctdb_client *client, 
318                                             struct ctdb_req_call *c)
319 {
320         struct ctdb_call_state *state;
321         struct ctdb_db_context *ctdb_db;
322         struct daemon_call_state *dstate;
323         struct ctdb_call *call;
324         struct ctdb_ltdb_header header;
325         TDB_DATA key, data;
326         int ret;
327         struct ctdb_context *ctdb = client->ctdb;
328         struct ctdb_daemon_packet_wrap *w;
329
330         ctdb->statistics.total_calls++;
331         if (client->ctdb->statistics.pending_calls > 0) {
332                 ctdb->statistics.pending_calls++;
333         }
334
335         ctdb_db = find_ctdb_db(client->ctdb, c->db_id);
336         if (!ctdb_db) {
337                 DEBUG(DEBUG_ERR, (__location__ " Unknown database in request. db_id==0x%08x",
338                           c->db_id));
339                 if (client->ctdb->statistics.pending_calls > 0) {
340                         ctdb->statistics.pending_calls--;
341                 }
342                 return;
343         }
344
345         key.dptr = c->data;
346         key.dsize = c->keylen;
347
348         w = talloc(ctdb, struct ctdb_daemon_packet_wrap);
349         CTDB_NO_MEMORY_VOID(ctdb, w);   
350
351         w->ctdb = ctdb;
352         w->client_id = client->client_id;
353
354         ret = ctdb_ltdb_lock_fetch_requeue(ctdb_db, key, &header, 
355                                            (struct ctdb_req_header *)c, &data,
356                                            daemon_incoming_packet_wrap, w, True);
357         if (ret == -2) {
358                 /* will retry later */
359                 if (client->ctdb->statistics.pending_calls > 0) {
360                         ctdb->statistics.pending_calls--;
361                 }
362                 return;
363         }
364
365         talloc_free(w);
366
367         if (ret != 0) {
368                 DEBUG(DEBUG_ERR,(__location__ " Unable to fetch record\n"));
369                 if (client->ctdb->statistics.pending_calls > 0) {
370                         ctdb->statistics.pending_calls--;
371                 }
372                 return;
373         }
374
375         dstate = talloc(client, struct daemon_call_state);
376         if (dstate == NULL) {
377                 ctdb_ltdb_unlock(ctdb_db, key);
378                 DEBUG(DEBUG_ERR,(__location__ " Unable to allocate dstate\n"));
379                 if (client->ctdb->statistics.pending_calls > 0) {
380                         ctdb->statistics.pending_calls--;
381                 }
382                 return;
383         }
384         dstate->start_time = timeval_current();
385         dstate->client = client;
386         dstate->reqid  = c->hdr.reqid;
387         talloc_steal(dstate, data.dptr);
388
389         call = dstate->call = talloc_zero(dstate, struct ctdb_call);
390         if (call == NULL) {
391                 ctdb_ltdb_unlock(ctdb_db, key);
392                 DEBUG(DEBUG_ERR,(__location__ " Unable to allocate call\n"));
393                 if (client->ctdb->statistics.pending_calls > 0) {
394                         ctdb->statistics.pending_calls--;
395                 }
396                 ctdb_latency(ctdb_db, "call_from_client 1", &ctdb->statistics.max_call_latency, dstate->start_time);
397                 return;
398         }
399
400         call->call_id = c->callid;
401         call->key = key;
402         call->call_data.dptr = c->data + c->keylen;
403         call->call_data.dsize = c->calldatalen;
404         call->flags = c->flags;
405
406         if (header.dmaster == ctdb->pnn) {
407                 state = ctdb_call_local_send(ctdb_db, call, &header, &data);
408         } else {
409                 state = ctdb_daemon_call_send_remote(ctdb_db, call, &header);
410         }
411
412         ctdb_ltdb_unlock(ctdb_db, key);
413
414         if (state == NULL) {
415                 DEBUG(DEBUG_ERR,(__location__ " Unable to setup call send\n"));
416                 if (client->ctdb->statistics.pending_calls > 0) {
417                         ctdb->statistics.pending_calls--;
418                 }
419                 ctdb_latency(ctdb_db, "call_from_client 2", &ctdb->statistics.max_call_latency, dstate->start_time);
420                 return;
421         }
422         talloc_steal(state, dstate);
423         talloc_steal(client, state);
424
425         state->async.fn = daemon_call_from_client_callback;
426         state->async.private_data = dstate;
427 }
428
429
430 static void daemon_request_control_from_client(struct ctdb_client *client, 
431                                                struct ctdb_req_control *c);
432
433 /* data contains a packet from the client */
434 static void daemon_incoming_packet(void *p, struct ctdb_req_header *hdr)
435 {
436         struct ctdb_client *client = talloc_get_type(p, struct ctdb_client);
437         TALLOC_CTX *tmp_ctx;
438         struct ctdb_context *ctdb = client->ctdb;
439
440         /* place the packet as a child of a tmp_ctx. We then use
441            talloc_free() below to free it. If any of the calls want
442            to keep it, then they will steal it somewhere else, and the
443            talloc_free() will be a no-op */
444         tmp_ctx = talloc_new(client);
445         talloc_steal(tmp_ctx, hdr);
446
447         if (hdr->ctdb_magic != CTDB_MAGIC) {
448                 ctdb_set_error(client->ctdb, "Non CTDB packet rejected in daemon\n");
449                 goto done;
450         }
451
452         if (hdr->ctdb_version != CTDB_VERSION) {
453                 ctdb_set_error(client->ctdb, "Bad CTDB version 0x%x rejected in daemon\n", hdr->ctdb_version);
454                 goto done;
455         }
456
457         switch (hdr->operation) {
458         case CTDB_REQ_CALL:
459                 ctdb->statistics.client.req_call++;
460                 daemon_request_call_from_client(client, (struct ctdb_req_call *)hdr);
461                 break;
462
463         case CTDB_REQ_MESSAGE:
464                 ctdb->statistics.client.req_message++;
465                 daemon_request_message_from_client(client, (struct ctdb_req_message *)hdr);
466                 break;
467
468         case CTDB_REQ_CONTROL:
469                 ctdb->statistics.client.req_control++;
470                 daemon_request_control_from_client(client, (struct ctdb_req_control *)hdr);
471                 break;
472
473         default:
474                 DEBUG(DEBUG_CRIT,(__location__ " daemon: unrecognized operation %u\n",
475                          hdr->operation));
476         }
477
478 done:
479         talloc_free(tmp_ctx);
480 }
481
482 /*
483   called when the daemon gets a incoming packet
484  */
485 static void ctdb_daemon_read_cb(uint8_t *data, size_t cnt, void *args)
486 {
487         struct ctdb_client *client = talloc_get_type(args, struct ctdb_client);
488         struct ctdb_req_header *hdr;
489
490         if (cnt == 0) {
491                 talloc_free(client);
492                 return;
493         }
494
495         client->ctdb->statistics.client_packets_recv++;
496
497         if (cnt < sizeof(*hdr)) {
498                 ctdb_set_error(client->ctdb, "Bad packet length %u in daemon\n", 
499                                (unsigned)cnt);
500                 return;
501         }
502         hdr = (struct ctdb_req_header *)data;
503         if (cnt != hdr->length) {
504                 ctdb_set_error(client->ctdb, "Bad header length %u expected %u\n in daemon", 
505                                (unsigned)hdr->length, (unsigned)cnt);
506                 return;
507         }
508
509         if (hdr->ctdb_magic != CTDB_MAGIC) {
510                 ctdb_set_error(client->ctdb, "Non CTDB packet rejected\n");
511                 return;
512         }
513
514         if (hdr->ctdb_version != CTDB_VERSION) {
515                 ctdb_set_error(client->ctdb, "Bad CTDB version 0x%x rejected in daemon\n", hdr->ctdb_version);
516                 return;
517         }
518
519         DEBUG(DEBUG_DEBUG,(__location__ " client request %u of type %u length %u from "
520                  "node %u to %u\n", hdr->reqid, hdr->operation, hdr->length,
521                  hdr->srcnode, hdr->destnode));
522
523         /* it is the responsibility of the incoming packet function to free 'data' */
524         daemon_incoming_packet(client, hdr);
525 }
526
527 static void ctdb_accept_client(struct event_context *ev, struct fd_event *fde, 
528                          uint16_t flags, void *private_data)
529 {
530         struct sockaddr_un addr;
531         socklen_t len;
532         int fd;
533         struct ctdb_context *ctdb = talloc_get_type(private_data, struct ctdb_context);
534         struct ctdb_client *client;
535 #ifdef _AIX
536         struct peercred_struct cr;
537         socklen_t crl = sizeof(struct peercred_struct);
538 #else
539         struct ucred cr;
540         socklen_t crl = sizeof(struct ucred);
541 #endif
542
543         memset(&addr, 0, sizeof(addr));
544         len = sizeof(addr);
545         fd = accept(ctdb->daemon.sd, (struct sockaddr *)&addr, &len);
546         if (fd == -1) {
547                 return;
548         }
549
550         set_nonblocking(fd);
551         set_close_on_exec(fd);
552
553         client = talloc_zero(ctdb, struct ctdb_client);
554 #ifdef _AIX
555         if (getsockopt(fd, SOL_SOCKET, SO_PEERID, &cr, &crl) == 0) {
556 #else
557         if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &cr, &crl) == 0) {
558 #endif
559                 talloc_asprintf(client, "struct ctdb_client: pid:%u", (unsigned)cr.pid);
560         }
561
562         client->ctdb = ctdb;
563         client->fd = fd;
564         client->client_id = ctdb_reqid_new(ctdb, client);
565         ctdb->statistics.num_clients++;
566
567         client->queue = ctdb_queue_setup(ctdb, client, fd, CTDB_DS_ALIGNMENT, 
568                                          ctdb_daemon_read_cb, client);
569
570         talloc_set_destructor(client, ctdb_client_destructor);
571 }
572
573
574
575 /*
576   create a unix domain socket and bind it
577   return a file descriptor open on the socket 
578 */
579 static int ux_socket_bind(struct ctdb_context *ctdb)
580 {
581         struct sockaddr_un addr;
582
583         ctdb->daemon.sd = socket(AF_UNIX, SOCK_STREAM, 0);
584         if (ctdb->daemon.sd == -1) {
585                 return -1;
586         }
587
588         set_close_on_exec(ctdb->daemon.sd);
589         set_nonblocking(ctdb->daemon.sd);
590
591         memset(&addr, 0, sizeof(addr));
592         addr.sun_family = AF_UNIX;
593         strncpy(addr.sun_path, ctdb->daemon.name, sizeof(addr.sun_path));
594
595         if (bind(ctdb->daemon.sd, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
596                 DEBUG(DEBUG_CRIT,("Unable to bind on ctdb socket '%s'\n", ctdb->daemon.name));
597                 goto failed;
598         }       
599
600         if (chown(ctdb->daemon.name, geteuid(), getegid()) != 0 ||
601             chmod(ctdb->daemon.name, 0700) != 0) {
602                 DEBUG(DEBUG_CRIT,("Unable to secure ctdb socket '%s', ctdb->daemon.name\n", ctdb->daemon.name));
603                 goto failed;
604         } 
605
606
607         if (listen(ctdb->daemon.sd, 100) != 0) {
608                 DEBUG(DEBUG_CRIT,("Unable to listen on ctdb socket '%s'\n", ctdb->daemon.name));
609                 goto failed;
610         }
611
612         return 0;
613
614 failed:
615         close(ctdb->daemon.sd);
616         ctdb->daemon.sd = -1;
617         return -1;      
618 }
619
620 /*
621   delete the socket on exit - called on destruction of autofree context
622  */
623 static int unlink_destructor(const char *name)
624 {
625         unlink(name);
626         return 0;
627 }
628
629 static void sig_child_handler(struct event_context *ev,
630         struct signal_event *se, int signum, int count,
631         void *dont_care, 
632         void *private_data)
633 {
634 //      struct ctdb_context *ctdb = talloc_get_type(private_data, struct ctdb_context);
635         int status;
636         pid_t pid = -1;
637
638         while (pid != 0) {
639                 pid = waitpid(-1, &status, WNOHANG);
640                 if (pid == -1) {
641                         DEBUG(DEBUG_ERR, (__location__ " waitpid() returned error. errno:%d\n", errno));
642                         return;
643                 }
644                 if (pid > 0) {
645                         DEBUG(DEBUG_DEBUG, ("SIGCHLD from %d\n", (int)pid));
646                 }
647         }
648 }
649
650 /*
651   start the protocol going as a daemon
652 */
653 int ctdb_start_daemon(struct ctdb_context *ctdb, bool do_fork)
654 {
655         int res, ret = -1;
656         struct fd_event *fde;
657         const char *domain_socket_name;
658         struct signal_event *se;
659
660         /* get rid of any old sockets */
661         unlink(ctdb->daemon.name);
662
663         /* create a unix domain stream socket to listen to */
664         res = ux_socket_bind(ctdb);
665         if (res!=0) {
666                 DEBUG(DEBUG_ALERT,(__location__ " Failed to open CTDB unix domain socket\n"));
667                 exit(10);
668         }
669
670         if (do_fork && fork()) {
671                 return 0;
672         }
673
674         tdb_reopen_all(False);
675
676         if (do_fork) {
677                 setsid();
678                 close(0);
679                 if (open("/dev/null", O_RDONLY) != 0) {
680                         DEBUG(DEBUG_ALERT,(__location__ " Failed to setup stdin on /dev/null\n"));
681                         exit(11);
682                 }
683         }
684         block_signal(SIGPIPE);
685
686         if (ctdb->do_setsched) {
687                 /* try to set us up as realtime */
688                 ctdb_set_scheduler(ctdb);
689         }
690
691         /* ensure the socket is deleted on exit of the daemon */
692         domain_socket_name = talloc_strdup(talloc_autofree_context(), ctdb->daemon.name);
693         if (domain_socket_name == NULL) {
694                 DEBUG(DEBUG_ALERT,(__location__ " talloc_strdup failed.\n"));
695                 exit(12);
696         }
697         talloc_set_destructor(domain_socket_name, unlink_destructor);   
698
699         ctdb->ev = event_context_init(NULL);
700
701         ctdb_set_child_logging(ctdb);
702
703         /* force initial recovery for election */
704         ctdb->recovery_mode = CTDB_RECOVERY_ACTIVE;
705
706         if (strcmp(ctdb->transport, "tcp") == 0) {
707                 int ctdb_tcp_init(struct ctdb_context *);
708                 ret = ctdb_tcp_init(ctdb);
709         }
710 #ifdef USE_INFINIBAND
711         if (strcmp(ctdb->transport, "ib") == 0) {
712                 int ctdb_ibw_init(struct ctdb_context *);
713                 ret = ctdb_ibw_init(ctdb);
714         }
715 #endif
716         if (ret != 0) {
717                 DEBUG(DEBUG_ERR,("Failed to initialise transport '%s'\n", ctdb->transport));
718                 return -1;
719         }
720
721         if (ctdb->methods == NULL) {
722                 DEBUG(DEBUG_ALERT,(__location__ " Can not initialize transport. ctdb->methods is NULL\n"));
723                 ctdb_fatal(ctdb, "transport is unavailable. can not initialize.");
724         }
725
726         /* initialise the transport  */
727         if (ctdb->methods->initialise(ctdb) != 0) {
728                 ctdb_fatal(ctdb, "transport failed to initialise");
729         }
730
731         /* attach to any existing persistent databases */
732         if (ctdb_attach_persistent(ctdb) != 0) {
733                 ctdb_fatal(ctdb, "Failed to attach to persistent databases\n");         
734         }
735
736         /* start frozen, then let the first election sort things out */
737         if (!ctdb_blocking_freeze(ctdb)) {
738                 ctdb_fatal(ctdb, "Failed to get initial freeze\n");
739         }
740
741         /* now start accepting clients, only can do this once frozen */
742         fde = event_add_fd(ctdb->ev, ctdb, ctdb->daemon.sd, 
743                            EVENT_FD_READ|EVENT_FD_AUTOCLOSE, 
744                            ctdb_accept_client, ctdb);
745
746         /* tell all other nodes we've just started up */
747         ctdb_daemon_send_control(ctdb, CTDB_BROADCAST_ALL,
748                                  0, CTDB_CONTROL_STARTUP, 0,
749                                  CTDB_CTRL_FLAG_NOREPLY,
750                                  tdb_null, NULL, NULL);
751
752         /* release any IPs we hold from previous runs of the daemon */
753         ctdb_release_all_ips(ctdb);
754
755         /* start the transport going */
756         ctdb_start_transport(ctdb);
757
758         /* set up a handler to pick up sigchld */
759         se = event_add_signal(ctdb->ev, ctdb,
760                                      SIGCHLD, 0,
761                                      sig_child_handler,
762                                      ctdb);
763         if (se == NULL) {
764                 DEBUG(DEBUG_CRIT,("Failed to set up signal handler for SIGCHLD\n"));
765                 exit(1);
766         }
767           
768         /* go into a wait loop to allow other nodes to complete */
769         event_loop_wait(ctdb->ev);
770
771         DEBUG(DEBUG_CRIT,("event_loop_wait() returned. this should not happen\n"));
772         exit(1);
773 }
774
775 /*
776   allocate a packet for use in daemon<->daemon communication
777  */
778 struct ctdb_req_header *_ctdb_transport_allocate(struct ctdb_context *ctdb,
779                                                  TALLOC_CTX *mem_ctx, 
780                                                  enum ctdb_operation operation, 
781                                                  size_t length, size_t slength,
782                                                  const char *type)
783 {
784         int size;
785         struct ctdb_req_header *hdr;
786
787         length = MAX(length, slength);
788         size = (length+(CTDB_DS_ALIGNMENT-1)) & ~(CTDB_DS_ALIGNMENT-1);
789
790         if (ctdb->methods == NULL) {
791                 DEBUG(DEBUG_ERR,(__location__ " Unable to allocate transport packet for operation %u of length %u. Transport is DOWN.\n",
792                          operation, (unsigned)length));
793                 return NULL;
794         }
795
796         hdr = (struct ctdb_req_header *)ctdb->methods->allocate_pkt(mem_ctx, size);
797         if (hdr == NULL) {
798                 DEBUG(DEBUG_ERR,("Unable to allocate transport packet for operation %u of length %u\n",
799                          operation, (unsigned)length));
800                 return NULL;
801         }
802         talloc_set_name_const(hdr, type);
803         memset(hdr, 0, slength);
804         hdr->length       = length;
805         hdr->operation    = operation;
806         hdr->ctdb_magic   = CTDB_MAGIC;
807         hdr->ctdb_version = CTDB_VERSION;
808         hdr->generation   = ctdb->vnn_map->generation;
809         hdr->srcnode      = ctdb->pnn;
810
811         return hdr;     
812 }
813
814 struct daemon_control_state {
815         struct daemon_control_state *next, *prev;
816         struct ctdb_client *client;
817         struct ctdb_req_control *c;
818         uint32_t reqid;
819         struct ctdb_node *node;
820 };
821
822 /*
823   callback when a control reply comes in
824  */
825 static void daemon_control_callback(struct ctdb_context *ctdb,
826                                     int32_t status, TDB_DATA data, 
827                                     const char *errormsg,
828                                     void *private_data)
829 {
830         struct daemon_control_state *state = talloc_get_type(private_data, 
831                                                              struct daemon_control_state);
832         struct ctdb_client *client = state->client;
833         struct ctdb_reply_control *r;
834         size_t len;
835
836         /* construct a message to send to the client containing the data */
837         len = offsetof(struct ctdb_reply_control, data) + data.dsize;
838         if (errormsg) {
839                 len += strlen(errormsg);
840         }
841         r = ctdbd_allocate_pkt(ctdb, state, CTDB_REPLY_CONTROL, len, 
842                                struct ctdb_reply_control);
843         CTDB_NO_MEMORY_VOID(ctdb, r);
844
845         r->hdr.reqid     = state->reqid;
846         r->status        = status;
847         r->datalen       = data.dsize;
848         r->errorlen = 0;
849         memcpy(&r->data[0], data.dptr, data.dsize);
850         if (errormsg) {
851                 r->errorlen = strlen(errormsg);
852                 memcpy(&r->data[r->datalen], errormsg, r->errorlen);
853         }
854
855         daemon_queue_send(client, &r->hdr);
856
857         talloc_free(state);
858 }
859
860 /*
861   fail all pending controls to a disconnected node
862  */
863 void ctdb_daemon_cancel_controls(struct ctdb_context *ctdb, struct ctdb_node *node)
864 {
865         struct daemon_control_state *state;
866         while ((state = node->pending_controls)) {
867                 DLIST_REMOVE(node->pending_controls, state);
868                 daemon_control_callback(ctdb, (uint32_t)-1, tdb_null, 
869                                         "node is disconnected", state);
870         }
871 }
872
873 /*
874   destroy a daemon_control_state
875  */
876 static int daemon_control_destructor(struct daemon_control_state *state)
877 {
878         if (state->node) {
879                 DLIST_REMOVE(state->node->pending_controls, state);
880         }
881         return 0;
882 }
883
884 /*
885   this is called when the ctdb daemon received a ctdb request control
886   from a local client over the unix domain socket
887  */
888 static void daemon_request_control_from_client(struct ctdb_client *client, 
889                                                struct ctdb_req_control *c)
890 {
891         TDB_DATA data;
892         int res;
893         struct daemon_control_state *state;
894         TALLOC_CTX *tmp_ctx = talloc_new(client);
895
896         if (c->hdr.destnode == CTDB_CURRENT_NODE) {
897                 c->hdr.destnode = client->ctdb->pnn;
898         }
899
900         state = talloc(client, struct daemon_control_state);
901         CTDB_NO_MEMORY_VOID(client->ctdb, state);
902
903         state->client = client;
904         state->c = talloc_steal(state, c);
905         state->reqid = c->hdr.reqid;
906         if (ctdb_validate_pnn(client->ctdb, c->hdr.destnode)) {
907                 state->node = client->ctdb->nodes[c->hdr.destnode];
908                 DLIST_ADD(state->node->pending_controls, state);
909         } else {
910                 state->node = NULL;
911         }
912
913         talloc_set_destructor(state, daemon_control_destructor);
914
915         if (c->flags & CTDB_CTRL_FLAG_NOREPLY) {
916                 talloc_steal(tmp_ctx, state);
917         }
918         
919         data.dptr = &c->data[0];
920         data.dsize = c->datalen;
921         res = ctdb_daemon_send_control(client->ctdb, c->hdr.destnode,
922                                        c->srvid, c->opcode, client->client_id,
923                                        c->flags,
924                                        data, daemon_control_callback,
925                                        state);
926         if (res != 0) {
927                 DEBUG(DEBUG_ERR,(__location__ " Failed to send control to remote node %u\n",
928                          c->hdr.destnode));
929         }
930
931         talloc_free(tmp_ctx);
932 }
933
934 /*
935   register a call function
936 */
937 int ctdb_daemon_set_call(struct ctdb_context *ctdb, uint32_t db_id,
938                          ctdb_fn_t fn, int id)
939 {
940         struct ctdb_registered_call *call;
941         struct ctdb_db_context *ctdb_db;
942
943         ctdb_db = find_ctdb_db(ctdb, db_id);
944         if (ctdb_db == NULL) {
945                 return -1;
946         }
947
948         call = talloc(ctdb_db, struct ctdb_registered_call);
949         call->fn = fn;
950         call->id = id;
951
952         DLIST_ADD(ctdb_db->calls, call);        
953         return 0;
954 }
955
956
957
958 /*
959   this local messaging handler is ugly, but is needed to prevent
960   recursion in ctdb_send_message() when the destination node is the
961   same as the source node
962  */
963 struct ctdb_local_message {
964         struct ctdb_context *ctdb;
965         uint64_t srvid;
966         TDB_DATA data;
967 };
968
969 static void ctdb_local_message_trigger(struct event_context *ev, struct timed_event *te, 
970                                        struct timeval t, void *private_data)
971 {
972         struct ctdb_local_message *m = talloc_get_type(private_data, 
973                                                        struct ctdb_local_message);
974         int res;
975
976         res = ctdb_dispatch_message(m->ctdb, m->srvid, m->data);
977         if (res != 0) {
978                 DEBUG(DEBUG_ERR, (__location__ " Failed to dispatch message for srvid=%llu\n", 
979                           (unsigned long long)m->srvid));
980         }
981         talloc_free(m);
982 }
983
984 static int ctdb_local_message(struct ctdb_context *ctdb, uint64_t srvid, TDB_DATA data)
985 {
986         struct ctdb_local_message *m;
987         m = talloc(ctdb, struct ctdb_local_message);
988         CTDB_NO_MEMORY(ctdb, m);
989
990         m->ctdb = ctdb;
991         m->srvid = srvid;
992         m->data  = data;
993         m->data.dptr = talloc_memdup(m, m->data.dptr, m->data.dsize);
994         if (m->data.dptr == NULL) {
995                 talloc_free(m);
996                 return -1;
997         }
998
999         /* this needs to be done as an event to prevent recursion */
1000         event_add_timed(ctdb->ev, m, timeval_zero(), ctdb_local_message_trigger, m);
1001         return 0;
1002 }
1003
1004 /*
1005   send a ctdb message
1006 */
1007 int ctdb_daemon_send_message(struct ctdb_context *ctdb, uint32_t pnn,
1008                              uint64_t srvid, TDB_DATA data)
1009 {
1010         struct ctdb_req_message *r;
1011         int len;
1012
1013         /* see if this is a message to ourselves */
1014         if (pnn == ctdb->pnn) {
1015                 return ctdb_local_message(ctdb, srvid, data);
1016         }
1017
1018         len = offsetof(struct ctdb_req_message, data) + data.dsize;
1019         r = ctdb_transport_allocate(ctdb, ctdb, CTDB_REQ_MESSAGE, len,
1020                                     struct ctdb_req_message);
1021         CTDB_NO_MEMORY(ctdb, r);
1022
1023         r->hdr.destnode  = pnn;
1024         r->srvid         = srvid;
1025         r->datalen       = data.dsize;
1026         memcpy(&r->data[0], data.dptr, data.dsize);
1027
1028         ctdb_queue_packet(ctdb, &r->hdr);
1029
1030         talloc_free(r);
1031         return 0;
1032 }
1033