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