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