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