r23410: Merge the core of the cluster code.
[kai/samba.git] / source / lib / ctdbd_conn.c
1 /* 
2    Unix SMB/CIFS implementation.
3    Samba internal messaging functions
4    Copyright (C) 2007 by Volker Lendecke
5    Copyright (C) 2007 by Andrew Tridgell
6    
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11    
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16    
17    You should have received a copy of the GNU General Public License
18    along with this program; if not, write to the Free Software
19    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 */
21
22 #include "includes.h"
23
24 #ifdef CLUSTER_SUPPORT
25
26 #include "librpc/gen_ndr/messaging.h"
27 #include "librpc/gen_ndr/ndr_messaging.h"
28
29 /* paths to these include files come from --with-ctdb= in configure */
30 #include "ctdb.h"
31 #include "ctdb_private.h"
32
33 struct ctdbd_connection {
34         struct messaging_context *msg_ctx;
35         uint32 reqid;
36         uint32 our_vnn;
37         uint64 rand_srvid;
38         struct packet_context *pkt;
39         struct fd_event *fde;
40         
41         void (*release_ip_handler)(const char *ip_addr, void *private_data);
42         void *release_ip_priv;
43 };
44
45 static NTSTATUS ctdbd_control(struct ctdbd_connection *conn,
46                               uint32_t vnn, uint32 opcode, 
47                               uint64_t srvid, TDB_DATA data, 
48                               TALLOC_CTX *mem_ctx, TDB_DATA *outdata,
49                               int *cstatus);
50
51 /*
52  * exit on fatal communications errors with the ctdbd daemon
53  */
54 static void cluster_fatal(const char *why)
55 {
56         DEBUG(0,("cluster fatal event: %s - exiting immediately\n", why));
57         /* we don't use smb_panic() as we don't want to delay to write
58            a core file. We need to release this process id immediately
59            so that someone else can take over without getting sharing
60            violations */
61         _exit(0);
62 }
63
64 /*
65  * Register a srvid with ctdbd
66  */
67 static NTSTATUS register_with_ctdbd(struct ctdbd_connection *conn,
68                                     uint64_t srvid)
69 {
70
71         int cstatus;
72         return ctdbd_control(conn, CTDB_CURRENT_NODE,
73                              CTDB_CONTROL_REGISTER_SRVID, srvid,
74                              tdb_null, NULL, NULL, &cstatus);
75 }
76
77 /*
78  * get our vnn from the cluster
79  */
80 static NTSTATUS get_cluster_vnn(struct ctdbd_connection *conn, uint32 *vnn)
81 {
82         int32_t cstatus=-1;
83         NTSTATUS status;
84         status = ctdbd_control(conn,
85                                CTDB_CURRENT_NODE, CTDB_CONTROL_GET_VNN, 0,
86                                tdb_null, NULL, NULL, &cstatus);
87         if (!NT_STATUS_IS_OK(status)) {
88                 cluster_fatal("ctdbd_control failed\n");
89         }
90         *vnn = (uint32_t)cstatus;
91         return status;
92 }
93
94 uint32 ctdbd_vnn(const struct ctdbd_connection *conn)
95 {
96         return conn->our_vnn;
97 }
98
99 /*
100  * Get us a ctdb connection
101  */
102
103 static NTSTATUS ctdbd_connect(TALLOC_CTX *mem_ctx,
104                               struct packet_context **presult)
105 {
106         struct packet_context *result;
107         const char *sockname = lp_ctdbd_socket();
108         struct sockaddr_un addr;
109         int fd;
110
111         if (!sockname || !*sockname) {
112                 sockname = CTDB_PATH;
113         }
114
115         fd = socket(AF_UNIX, SOCK_STREAM, 0);
116         if (fd == -1) {
117                 DEBUG(3, ("Could not create socket: %s\n", strerror(errno)));
118                 return map_nt_error_from_unix(errno);
119         }
120
121         ZERO_STRUCT(addr);
122         addr.sun_family = AF_UNIX;
123         strncpy(addr.sun_path, sockname, sizeof(addr.sun_path));
124
125         if (connect(fd, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
126                 DEBUG(0, ("connect(%s) failed: %s\n", sockname,
127                           strerror(errno)));
128                 close(fd);
129                 return map_nt_error_from_unix(errno);
130         }
131
132         if (!(result = packet_init(mem_ctx, fd))) {
133                 close(fd);
134                 return NT_STATUS_NO_MEMORY;
135         }
136
137         *presult = result;
138         return NT_STATUS_OK;
139 }
140
141 /*
142  * Do we have a complete ctdb packet in the queue?
143  */
144
145 static BOOL ctdb_req_complete(const struct data_blob *data,
146                               size_t *length,
147                               void *private_data)
148 {
149         uint32 msglen;
150
151         if (data->length < sizeof(msglen)) {
152                 return False;
153         }
154
155         msglen = *((uint32 *)data->data);
156
157         DEBUG(10, ("msglen = %d\n", msglen));
158
159         if (msglen < sizeof(struct ctdb_req_header)) {
160                 DEBUG(0, ("Got invalid msglen: %d, expected at least %d for "
161                           "the req_header\n", msglen,
162                           sizeof(struct ctdb_req_header)));
163                 cluster_fatal("ctdbd protocol error\n");
164         }
165
166         if (data->length >= msglen) {
167                 *length = msglen;
168                 return True;
169         }
170
171         return False;
172 }
173
174 /*
175  * State necessary to defer an incoming message while we are waiting for a
176  * ctdb reply.
177  */
178
179 struct deferred_msg_state {
180         struct messaging_context *msg_ctx;
181         struct messaging_rec *rec;
182 };
183
184 /*
185  * Timed event handler for the deferred message
186  */
187
188 static void deferred_message_dispatch(struct event_context *event_ctx,
189                                       struct timed_event *te,
190                                       const struct timeval *now,
191                                       void *private_data)
192 {
193         struct deferred_msg_state *state = talloc_get_type_abort(
194                 private_data, struct deferred_msg_state);
195
196         messaging_dispatch_rec(state->msg_ctx, state->rec);
197         TALLOC_FREE(state);
198         TALLOC_FREE(te);
199 }
200
201 struct req_pull_state {
202         TALLOC_CTX *mem_ctx;
203         DATA_BLOB req;
204 };
205
206 /*
207  * Pull a ctdb request out of the incoming packet queue
208  */
209
210 static NTSTATUS ctdb_req_pull(const struct data_blob *data,
211                               void *private_data)
212 {
213         struct req_pull_state *state = (struct req_pull_state *)private_data;
214
215         state->req = data_blob_talloc(state->mem_ctx, data->data,
216                                       data->length);
217         if (state->req.data == NULL) {
218                 return NT_STATUS_NO_MEMORY;
219         }
220         return NT_STATUS_OK;
221 }
222
223 /*
224  * Fetch a messaging_rec from an incoming ctdb style message
225  */
226
227 static struct messaging_rec *ctdb_pull_messaging_rec(TALLOC_CTX *mem_ctx,
228                                                      size_t overall_length,
229                                                      struct ctdb_req_message *msg)
230 {
231         struct messaging_rec *result;
232         DATA_BLOB blob;
233         NTSTATUS status;
234
235         if ((overall_length < offsetof(struct ctdb_req_message, data))
236             || (overall_length
237                 < offsetof(struct ctdb_req_message, data) + msg->datalen)) {
238
239                 cluster_fatal("got invalid msg length");
240         }
241
242         if (!(result = TALLOC_P(mem_ctx, struct messaging_rec))) {
243                 DEBUG(0, ("talloc failed\n"));
244                 return NULL;
245         }
246
247         blob = data_blob_const(msg->data, msg->datalen);
248
249         status = ndr_pull_struct_blob(
250                 &blob, result, result,
251                 (ndr_pull_flags_fn_t)ndr_pull_messaging_rec);
252
253         if (!NT_STATUS_IS_OK(status)) {
254                 DEBUG(0, ("ndr_pull_struct_blob failed: %s\n",
255                           nt_errstr(status)));
256                 TALLOC_FREE(result);
257                 return NULL;
258         }
259
260         return result;
261 }
262
263 /*
264  * Read a full ctdbd request. If we have a messaging context, defer incoming
265  * messages that might come in between.
266  */
267
268 static NTSTATUS ctdb_read_req(struct ctdbd_connection *conn, uint32 reqid,
269                               TALLOC_CTX *mem_ctx, void *result)
270 {
271         struct ctdb_req_header *hdr;
272         struct req_pull_state state;
273         NTSTATUS status;
274
275  again:
276
277         status = packet_fd_read_sync(conn->pkt);
278
279         if (NT_STATUS_EQUAL(status, NT_STATUS_NETWORK_BUSY)) {
280                 /* EAGAIN */
281                 goto again;
282         }
283
284         if (!NT_STATUS_IS_OK(status)) {
285                 DEBUG(3, ("packet_fd_read failed: %s\n", nt_errstr(status)));
286                 cluster_fatal("ctdbd died\n");
287         }
288
289         ZERO_STRUCT(state);
290         state.mem_ctx = mem_ctx;
291
292         if (!packet_handler(conn->pkt, ctdb_req_complete, ctdb_req_pull,
293                             &state, &status)) {
294                 /*
295                  * Not enough data
296                  */
297                 goto again;
298         }
299
300         if (!NT_STATUS_IS_OK(status)) {
301                 DEBUG(3, ("Could not read packet: %s\n", nt_errstr(status)));
302                 cluster_fatal("ctdbd died\n");
303         }
304
305         hdr = (struct ctdb_req_header *)state.req.data;
306
307         if (hdr->operation == CTDB_REQ_MESSAGE) {
308                 struct timed_event *evt;
309                 struct deferred_msg_state *msg_state;
310                 struct ctdb_req_message *msg = (struct ctdb_req_message *)hdr;
311
312                 if (conn->msg_ctx == NULL) {
313                         DEBUG(1, ("Got a message without having a msg ctx, "
314                                   "dropping msg %llu\n", msg->srvid));
315                         goto again;
316                 }
317                 
318                 if ((conn->release_ip_handler != NULL)
319                     && (msg->srvid == CTDB_SRVID_RELEASE_IP)) {
320                         /* must be dispatched immediately */
321                         DEBUG(10, ("received CTDB_SRVID_RELEASE_IP\n"));
322                         conn->release_ip_handler((const char *)msg->data,
323                                                  conn->release_ip_priv);
324                         TALLOC_FREE(hdr);
325                         goto again;
326                 }
327
328                 if (!(msg_state = TALLOC_P(NULL, struct deferred_msg_state))) {
329                         DEBUG(0, ("talloc failed\n"));
330                         TALLOC_FREE(hdr);
331                         goto again;
332                 }
333
334                 if (!(msg_state->rec = ctdb_pull_messaging_rec(
335                               msg_state, state.req.length, msg))) {
336                         DEBUG(0, ("ctdbd_pull_messaging_rec failed\n"));
337                         TALLOC_FREE(msg_state);
338                         TALLOC_FREE(hdr);
339                         goto again;
340                 }
341
342                 TALLOC_FREE(hdr);
343
344                 msg_state->msg_ctx = conn->msg_ctx;
345                 
346                 /*
347                  * We're waiting for a call reply, but an async message has
348                  * crossed. Defer dispatching to the toplevel event loop.
349                  */
350                 evt = event_add_timed(conn->msg_ctx->event_ctx,
351                                       conn->msg_ctx->event_ctx,
352                                       timeval_zero(),
353                                       "deferred_message_dispatch",
354                                       deferred_message_dispatch,
355                                       msg_state);
356                 if (evt == NULL) {
357                         DEBUG(0, ("event_add_timed failed\n"));
358                         TALLOC_FREE(msg_state);
359                         TALLOC_FREE(hdr);
360                         goto again;
361                 }
362                 
363                 goto again;
364         }
365
366         if (hdr->reqid != reqid) {
367                 /* we got the wrong reply */
368                 DEBUG(0,("Discarding mismatched ctdb reqid %u should have "
369                          "been %u\n", hdr->reqid, reqid));
370                 TALLOC_FREE(hdr);
371                 goto again;
372         }
373
374         *((void **)result) = talloc_move(mem_ctx, &hdr);
375
376         return NT_STATUS_OK;
377 }
378
379 /*
380  * Get us a ctdbd connection
381  */
382
383 NTSTATUS ctdbd_init_connection(TALLOC_CTX *mem_ctx,
384                                struct ctdbd_connection **pconn)
385 {
386         struct ctdbd_connection *conn;
387         NTSTATUS status;
388
389         if (!(conn = TALLOC_ZERO_P(mem_ctx, struct ctdbd_connection))) {
390                 DEBUG(0, ("talloc failed\n"));
391                 return NT_STATUS_NO_MEMORY;
392         }
393
394         status = ctdbd_connect(conn, &conn->pkt);
395
396         if (!NT_STATUS_IS_OK(status)) {
397                 DEBUG(10, ("ctdbd_connect failed: %s\n", nt_errstr(status)));
398                 goto fail;
399         }
400
401         status = get_cluster_vnn(conn, &conn->our_vnn);
402
403         if (!NT_STATUS_IS_OK(status)) {
404                 DEBUG(10, ("get_cluster_vnn failed: %s\n", nt_errstr(status)));
405                 goto fail;
406         }
407
408         generate_random_buffer((unsigned char *)&conn->rand_srvid,
409                                sizeof(conn->rand_srvid));
410
411         status = register_with_ctdbd(conn, conn->rand_srvid);
412
413         if (!NT_STATUS_IS_OK(status)) {
414                 DEBUG(5, ("Could not register random srvid: %s\n",
415                           nt_errstr(status)));
416                 goto fail;
417         }
418
419         *pconn = conn;
420         return NT_STATUS_OK;
421
422  fail:
423         TALLOC_FREE(conn);
424         return status;
425 }
426
427 /*
428  * Get us a ctdbd connection and register us as a process
429  */
430
431 NTSTATUS ctdbd_messaging_connection(TALLOC_CTX *mem_ctx,
432                                     struct ctdbd_connection **pconn)
433 {
434         struct ctdbd_connection *conn;
435         NTSTATUS status;
436
437         status = ctdbd_init_connection(mem_ctx, &conn);
438
439         if (!NT_STATUS_IS_OK(status)) {
440                 return status;
441         }
442
443         status = register_with_ctdbd(conn, (uint64_t)sys_getpid());
444         if (!NT_STATUS_IS_OK(status)) {
445                 goto fail;
446         }
447
448         status = register_with_ctdbd(conn, MSG_SRVID_SAMBA);
449         if (!NT_STATUS_IS_OK(status)) {
450                 goto fail;
451         }
452
453         *pconn = conn;
454         return NT_STATUS_OK;
455
456  fail:
457         TALLOC_FREE(conn);
458         return status;
459 }
460
461 /*
462  * Packet handler to receive and handle a ctdb message
463  */
464 static NTSTATUS ctdb_handle_message(const struct data_blob *data,
465                                     void *private_data)
466 {
467         struct ctdbd_connection *conn = talloc_get_type_abort(
468                 private_data, struct ctdbd_connection);
469         struct ctdb_req_message *msg;
470         struct messaging_rec *msg_rec;
471
472         msg = (struct ctdb_req_message *)data->data;
473
474         if (msg->hdr.operation != CTDB_REQ_MESSAGE) {
475                 DEBUG(0, ("Received async msg of type %u, discarding\n",
476                           msg->hdr.operation));
477                 return NT_STATUS_INVALID_PARAMETER;
478         }
479
480         if ((conn->release_ip_handler != NULL)
481             && (msg->srvid == CTDB_SRVID_RELEASE_IP)) {
482                 /* must be dispatched immediately */
483                 DEBUG(10, ("received CTDB_SRVID_RELEASE_IP\n"));
484                 conn->release_ip_handler((const char *)msg->data,
485                                          conn->release_ip_priv);
486                 return NT_STATUS_OK;
487         }
488
489         SMB_ASSERT(conn->msg_ctx != NULL);
490
491         if (msg->srvid == CTDB_SRVID_RECONFIGURE) {
492                 DEBUG(0,("Got cluster reconfigure message\n"));
493                 /*
494                  * when the cluster is reconfigured, we need to clean the brl
495                  * database
496                  */
497                 messaging_send(conn->msg_ctx, procid_self(),
498                                MSG_SMB_BRL_VALIDATE, &data_blob_null);
499
500                 /*
501                  * it's possible that we have just rejoined the cluster after
502                  * an outage. In that case our pending locks could have been
503                  * removed from the lockdb, so retry them once more
504                  */
505                 message_send_all(conn->msg_ctx, MSG_SMB_UNLOCK, NULL, 0, NULL);
506
507                 return NT_STATUS_OK;
508                 
509         }
510
511         /* only messages to our pid or the broadcast are valid here */
512         if (msg->srvid != sys_getpid() && msg->srvid != MSG_SRVID_SAMBA) {
513                 DEBUG(0,("Got unexpected message with srvid=%llu\n", 
514                          (unsigned long long)msg->srvid));
515                 return NT_STATUS_OK;
516         }
517
518         if (!(msg_rec = ctdb_pull_messaging_rec(NULL, data->length, msg))) {
519                 DEBUG(10, ("ctdb_pull_messaging_rec failed\n"));
520                 return NT_STATUS_NO_MEMORY;
521         }
522
523         messaging_dispatch_rec(conn->msg_ctx, msg_rec);
524
525         TALLOC_FREE(msg_rec);
526         return NT_STATUS_OK;
527 }
528
529 /*
530  * The ctdbd socket is readable asynchronuously
531  */
532
533 static void ctdbd_socket_handler(struct event_context *event_ctx,
534                                  struct fd_event *event,
535                                  uint16 flags,
536                                  void *private_data)
537 {
538         struct ctdbd_connection *conn = talloc_get_type_abort(
539                 private_data, struct ctdbd_connection);
540
541         NTSTATUS status;
542
543         status = packet_fd_read(conn->pkt);
544
545         if (!NT_STATUS_IS_OK(status)) {
546                 DEBUG(0, ("packet_fd_read failed: %s\n", nt_errstr(status)));
547                 cluster_fatal("ctdbd died\n");
548         }
549
550         while (packet_handler(conn->pkt, ctdb_req_complete,
551                               ctdb_handle_message, conn, &status)) {
552                 if (!NT_STATUS_IS_OK(status)) {
553                         DEBUG(10, ("could not handle incoming message: %s\n",
554                                    nt_errstr(status)));
555                 }
556         }
557 }
558
559 /*
560  * Prepare a ctdbd connection to receive messages
561  */
562
563 NTSTATUS ctdbd_register_msg_ctx(struct ctdbd_connection *conn,
564                                 struct messaging_context *msg_ctx)
565 {
566         SMB_ASSERT(conn->msg_ctx == NULL);
567         SMB_ASSERT(conn->fde == NULL);
568
569         if (!(conn->fde = event_add_fd(msg_ctx->event_ctx, conn,
570                                        packet_get_fd(conn->pkt),
571                                        EVENT_FD_READ,
572                                        ctdbd_socket_handler,
573                                        conn))) {
574                 DEBUG(0, ("event_add_fd failed\n"));
575                 return NT_STATUS_NO_MEMORY;
576         }
577
578         conn->msg_ctx = msg_ctx;
579
580         return NT_STATUS_OK;
581 }
582
583 /*
584  * Send a messaging message across a ctdbd
585  */
586
587 NTSTATUS ctdbd_messaging_send(struct ctdbd_connection *conn,
588                               uint32 dst_vnn, uint64 dst_srvid,
589                               struct messaging_rec *msg)
590 {
591         struct ctdb_req_message r;
592         TALLOC_CTX *mem_ctx;
593         DATA_BLOB blob;
594         NTSTATUS status;
595
596         if (!(mem_ctx = talloc_init("ctdbd_messaging_send"))) {
597                 DEBUG(0, ("talloc failed\n"));
598                 return NT_STATUS_NO_MEMORY;
599         }
600
601         status = ndr_push_struct_blob(
602                 &blob, mem_ctx, msg,
603                 (ndr_push_flags_fn_t)ndr_push_messaging_rec);
604
605         if (!NT_STATUS_IS_OK(status)) {
606                 DEBUG(0, ("ndr_push_struct_blob failed: %s\n",
607                           nt_errstr(status)));
608                 goto fail;
609         }
610
611         r.hdr.length = offsetof(struct ctdb_req_message, data) + blob.length;
612         r.hdr.ctdb_magic = CTDB_MAGIC;
613         r.hdr.ctdb_version = CTDB_VERSION;
614         r.hdr.generation = 1;
615         r.hdr.operation  = CTDB_REQ_MESSAGE;
616         r.hdr.destnode   = dst_vnn;
617         r.hdr.srcnode    = conn->our_vnn;
618         r.hdr.reqid      = 0;
619         r.srvid          = dst_srvid;
620         r.datalen        = blob.length;
621
622         status = packet_send(
623                 conn->pkt, 2,
624                 data_blob_const(&r, offsetof(struct ctdb_req_message, data)),
625                 blob);
626
627         if (!NT_STATUS_IS_OK(status)) {
628                 DEBUG(0, ("packet_send failed: %s\n", nt_errstr(status)));
629                 goto fail;
630         }
631
632         status = packet_flush(conn->pkt);
633
634         if (!NT_STATUS_IS_OK(status)) {
635                 DEBUG(3, ("write to ctdbd failed: %s\n", nt_errstr(status)));
636                 cluster_fatal("cluster dispatch daemon msg write error\n");
637         }
638
639         status = NT_STATUS_OK;
640  fail:
641         TALLOC_FREE(mem_ctx);
642         return status;
643 }
644
645 /*
646  * send/recv a generic ctdb control message
647  */
648 static NTSTATUS ctdbd_control(struct ctdbd_connection *conn,
649                               uint32_t vnn, uint32 opcode, 
650                               uint64_t srvid, TDB_DATA data, 
651                               TALLOC_CTX *mem_ctx, TDB_DATA *outdata,
652                               int *cstatus)
653 {
654         struct ctdb_req_control req;
655         struct ctdb_reply_control *reply = NULL;
656         struct ctdbd_connection *new_conn = NULL;
657         NTSTATUS status;
658
659         if (conn == NULL) {
660                 status = ctdbd_init_connection(NULL, &new_conn);
661
662                 if (!NT_STATUS_IS_OK(status)) {
663                         DEBUG(10, ("Could not init temp connection: %s\n",
664                                    nt_errstr(status)));
665                         goto fail;
666                 }
667
668                 conn = new_conn;
669         }
670
671         ZERO_STRUCT(req);
672         req.hdr.length = offsetof(struct ctdb_req_control, data) + data.dsize;
673         req.hdr.ctdb_magic   = CTDB_MAGIC;
674         req.hdr.ctdb_version = CTDB_VERSION;
675         req.hdr.operation    = CTDB_REQ_CONTROL;
676         req.hdr.reqid        = ++conn->reqid;
677         req.hdr.destnode     = vnn;
678         req.opcode           = opcode;
679         req.srvid            = srvid;
680         req.datalen          = data.dsize;
681
682         status = packet_send(
683                 conn->pkt, 2,
684                 data_blob_const(&req, offsetof(struct ctdb_req_control, data)),
685                 data);
686
687         if (!NT_STATUS_IS_OK(status)) {
688                 DEBUG(3, ("packet_send failed: %s\n", nt_errstr(status)));
689                 goto fail;
690         }
691
692         status = packet_flush(conn->pkt);
693
694         if (!NT_STATUS_IS_OK(status)) {
695                 DEBUG(3, ("write to ctdbd failed: %s\n", nt_errstr(status)));
696                 cluster_fatal("cluster dispatch daemon control write error\n");
697         }
698
699         status = ctdb_read_req(conn, req.hdr.reqid, NULL, (void *)&reply);
700
701         if (!NT_STATUS_IS_OK(status)) {
702                 DEBUG(10, ("ctdb_read_req failed: %s\n", nt_errstr(status)));
703                 goto fail;
704         }
705
706         if (reply->hdr.operation != CTDB_REPLY_CONTROL) {
707                 DEBUG(0, ("received invalid reply\n"));
708                 goto fail;
709         }
710
711         if (outdata) {
712                 if (!(outdata->dptr = (uint8 *)talloc_memdup(
713                               mem_ctx, reply->data, reply->datalen))) {
714                         TALLOC_FREE(reply);
715                         return NT_STATUS_NO_MEMORY;
716                 }
717                 outdata->dsize = reply->datalen;
718         }
719         if (cstatus) {
720                 (*cstatus) = reply->status;
721         }
722
723         status = NT_STATUS_OK;
724
725  fail:
726         TALLOC_FREE(new_conn);
727         TALLOC_FREE(reply);
728         return status;
729 }
730
731 /*
732  * see if a remote process exists
733  */
734 BOOL ctdbd_process_exists(struct ctdbd_connection *conn, uint32 vnn, pid_t pid)
735 {
736         NTSTATUS status;
737         TDB_DATA data;
738         int32_t cstatus;
739
740         data.dptr = (uint8_t*)&pid;
741         data.dsize = sizeof(pid);
742
743         status = ctdbd_control(conn, vnn, CTDB_CONTROL_PROCESS_EXISTS, 0,
744                                data, NULL, NULL, &cstatus);
745         if (!NT_STATUS_IS_OK(status)) {
746                 DEBUG(0, (__location__ " ctdb_control for process_exists "
747                           "failed\n"));
748                 return False;
749         }
750
751         return cstatus == 0;
752 }
753
754 /*
755  * Get a db path
756  */
757 char *ctdbd_dbpath(struct ctdbd_connection *conn,
758                    TALLOC_CTX *mem_ctx, uint32_t db_id)
759 {
760         NTSTATUS status;
761         TDB_DATA data;
762         int32_t cstatus;
763
764         data.dptr = (uint8_t*)&db_id;
765         data.dsize = sizeof(db_id);
766
767         status = ctdbd_control(conn, CTDB_CURRENT_NODE,
768                                CTDB_CONTROL_GETDBPATH, 0, data, 
769                                mem_ctx, &data, &cstatus);
770         if (!NT_STATUS_IS_OK(status) || cstatus != 0) {
771                 DEBUG(0,(__location__ " ctdb_control for getdbpath failed\n"));
772                 return NULL;
773         }
774
775         return (char *)data.dptr;
776 }
777
778 /*
779  * attach to a ctdb database
780  */
781 NTSTATUS ctdbd_db_attach(struct ctdbd_connection *conn,
782                          const char *name, uint32_t *db_id, int tdb_flags)
783 {
784         NTSTATUS status;
785         TDB_DATA data;
786         int32_t cstatus;
787
788         data.dptr = (uint8_t*)name;
789         data.dsize = strlen(name)+1;
790
791         status = ctdbd_control(conn, CTDB_CURRENT_NODE,
792                                CTDB_CONTROL_DB_ATTACH, 0, data, 
793                                NULL, &data, &cstatus);
794         if (!NT_STATUS_IS_OK(status)) {
795                 DEBUG(0, (__location__ " ctdb_control for db_attach "
796                           "failed: %s\n", nt_errstr(status)));
797                 return status;
798         }
799
800         if (cstatus != 0 || data.dsize != sizeof(uint32_t)) {
801                 DEBUG(0,(__location__ " ctdb_control for db_attach failed\n"));
802                 return NT_STATUS_INTERNAL_ERROR;
803         }
804
805         *db_id = *(uint32_t *)data.dptr;
806         talloc_free(data.dptr);
807
808         if (!(tdb_flags & TDB_SEQNUM)) {
809                 return NT_STATUS_OK;
810         }
811
812         data.dptr = (uint8_t *)db_id;
813         data.dsize = sizeof(*db_id);
814
815         status = ctdbd_control(conn, CTDB_CURRENT_NODE,
816                                CTDB_CONTROL_ENABLE_SEQNUM, 0, data, 
817                                NULL, NULL, &cstatus);
818         if (!NT_STATUS_IS_OK(status) || cstatus != 0) {
819                 DEBUG(0,(__location__ " ctdb_control for enable seqnum "
820                          "failed\n"));
821                 return NT_STATUS_IS_OK(status) ? NT_STATUS_INTERNAL_ERROR :
822                         status;
823         }
824
825         return NT_STATUS_OK;
826 }
827
828 /*
829  * force the migration of a record to this node
830  */
831 NTSTATUS ctdbd_migrate(struct ctdbd_connection *conn, uint32 db_id,
832                        TDB_DATA key)
833 {
834         struct ctdb_req_call req;
835         struct ctdb_reply_call *reply;
836         NTSTATUS status;
837
838         ZERO_STRUCT(req);
839         
840         req.hdr.length = offsetof(struct ctdb_req_call, data) + key.dsize;
841         req.hdr.ctdb_magic   = CTDB_MAGIC;
842         req.hdr.ctdb_version = CTDB_VERSION;
843         req.hdr.operation    = CTDB_REQ_CALL;
844         req.hdr.reqid        = ++conn->reqid;
845         req.flags            = CTDB_IMMEDIATE_MIGRATION;
846         req.callid           = CTDB_NULL_FUNC;
847         req.db_id            = db_id;
848         req.keylen           = key.dsize;
849
850         status = packet_send(
851                 conn->pkt, 2,
852                 data_blob_const(&req, offsetof(struct ctdb_req_call, data)),
853                 key);
854
855         if (!NT_STATUS_IS_OK(status)) {
856                 DEBUG(3, ("packet_send failed: %s\n", nt_errstr(status)));
857                 return status;
858         }
859
860         status = packet_flush(conn->pkt);
861
862         if (!NT_STATUS_IS_OK(status)) {
863                 DEBUG(3, ("write to ctdbd failed: %s\n", nt_errstr(status)));
864                 cluster_fatal("cluster dispatch daemon control write error\n");
865         }
866
867         status = ctdb_read_req(conn, req.hdr.reqid, NULL, (void *)&reply);
868
869         if (!NT_STATUS_IS_OK(status)) {
870                 DEBUG(0, ("ctdb_read_req failed: %s\n", nt_errstr(status)));
871                 goto fail;
872         }
873
874         if (reply->hdr.operation != CTDB_REPLY_CALL) {
875                 DEBUG(0, ("received invalid reply\n"));
876                 status = NT_STATUS_INTERNAL_ERROR;
877                 goto fail;
878         }
879
880         status = NT_STATUS_OK;
881  fail:
882
883         TALLOC_FREE(reply);
884         return status;
885 }
886
887 /*
888  * remotely fetch a record without locking it or forcing a migration
889  */
890 NTSTATUS ctdbd_fetch(struct ctdbd_connection *conn, uint32 db_id,
891                      TDB_DATA key, TALLOC_CTX *mem_ctx, TDB_DATA *data)
892 {
893         struct ctdb_req_call req;
894         struct ctdb_reply_call *reply;
895         NTSTATUS status;
896
897         ZERO_STRUCT(req);
898         
899         req.hdr.length = offsetof(struct ctdb_req_call, data) + key.dsize;
900         req.hdr.ctdb_magic   = CTDB_MAGIC;
901         req.hdr.ctdb_version = CTDB_VERSION;
902         req.hdr.operation    = CTDB_REQ_CALL;
903         req.hdr.reqid        = ++conn->reqid;
904         req.flags            = 0;
905         req.callid           = CTDB_FETCH_FUNC;
906         req.db_id            = db_id;
907         req.keylen           = key.dsize;
908
909         status = packet_send(
910                 conn->pkt, 2,
911                 data_blob_const(&req, offsetof(struct ctdb_req_call, data)),
912                 key);
913
914         if (!NT_STATUS_IS_OK(status)) {
915                 DEBUG(3, ("packet_send failed: %s\n", nt_errstr(status)));
916                 return status;
917         }
918
919         status = packet_flush(conn->pkt);
920
921         if (!NT_STATUS_IS_OK(status)) {
922                 DEBUG(3, ("write to ctdbd failed: %s\n", nt_errstr(status)));
923                 cluster_fatal("cluster dispatch daemon control write error\n");
924         }
925
926         status = ctdb_read_req(conn, req.hdr.reqid, NULL, (void *)&reply);
927
928         if (!NT_STATUS_IS_OK(status)) {
929                 DEBUG(0, ("ctdb_read_req failed: %s\n", nt_errstr(status)));
930                 goto fail;
931         }
932
933         if (reply->hdr.operation != CTDB_REPLY_CALL) {
934                 DEBUG(0, ("received invalid reply\n"));
935                 status = NT_STATUS_INTERNAL_ERROR;
936                 goto fail;
937         }
938
939         data->dsize = reply->datalen;
940         if (data->dsize == 0) {
941                 data->dptr = NULL;
942                 goto done;
943         }
944
945         data->dptr = (uint8 *)talloc_memdup(mem_ctx, &reply->data[0],
946                                             reply->datalen);
947         if (data->dptr == NULL) {
948                 DEBUG(0, ("talloc failed\n"));
949                 status = NT_STATUS_NO_MEMORY;
950                 goto fail;
951         }
952
953  done:
954         status = NT_STATUS_OK;
955  fail:
956         TALLOC_FREE(reply);
957         return status;
958 }
959
960 struct ctdbd_traverse_state {
961         void (*fn)(TDB_DATA key, TDB_DATA data, void *private_data);
962         void *private_data;
963 };
964
965 /*
966  * Handle a traverse record coming in on the ctdbd connection
967  */
968
969 static NTSTATUS ctdb_traverse_handler(const struct data_blob *blob,
970                                       void *private_data)
971 {
972         struct ctdbd_traverse_state *state =
973                 (struct ctdbd_traverse_state *)private_data;
974
975         struct ctdb_req_message *m;
976         struct ctdb_rec_data *d;
977         TDB_DATA key, data;
978
979         m = (struct ctdb_req_message *)blob->data;
980
981         if (blob->length < sizeof(*m) || m->hdr.length != blob->length) {
982                 DEBUG(0, ("Got invalid message of length %d\n",
983                           (int)blob->length));
984                 return NT_STATUS_UNEXPECTED_IO_ERROR;
985         }
986
987         d = (struct ctdb_rec_data *)&m->data[0];
988         if (m->datalen < sizeof(uint32_t) || m->datalen != d->length) {
989                 DEBUG(0, ("Got invalid traverse data of length %d\n",
990                           (int)m->datalen));
991                 return NT_STATUS_UNEXPECTED_IO_ERROR;
992         }
993
994         key.dsize = d->keylen;
995         key.dptr  = &d->data[0];
996         data.dsize = d->datalen;
997         data.dptr = &d->data[d->keylen];                
998
999         if (key.dsize == 0 && data.dsize == 0) {
1000                 /* end of traverse */
1001                 return NT_STATUS_END_OF_FILE;
1002         }
1003
1004         if (data.dsize < sizeof(struct ctdb_ltdb_header)) {
1005                 DEBUG(0, ("Got invalid ltdb header length %d\n",
1006                           (int)data.dsize));
1007                 return NT_STATUS_UNEXPECTED_IO_ERROR;
1008         }
1009         data.dsize -= sizeof(struct ctdb_ltdb_header);
1010         data.dptr += sizeof(struct ctdb_ltdb_header);
1011
1012         if (state->fn) {
1013                 state->fn(key, data, state->private_data);
1014         }
1015
1016         return NT_STATUS_OK;
1017 }
1018
1019 /*
1020   Traverse a ctdb database. This uses a kind-of hackish way to open a second
1021   connection to ctdbd to avoid the hairy recursive and async problems with
1022   everything in-line.
1023 */
1024
1025 NTSTATUS ctdbd_traverse(uint32 db_id,
1026                         void (*fn)(TDB_DATA key, TDB_DATA data,
1027                                    void *private_data),
1028                         void *private_data)
1029 {
1030         struct ctdbd_connection *conn;
1031         NTSTATUS status;
1032
1033         TDB_DATA data;
1034         struct ctdb_traverse_start t;
1035         int cstatus;
1036         struct ctdbd_traverse_state state;
1037
1038         status = ctdbd_init_connection(NULL, &conn);
1039
1040         t.db_id = db_id;
1041         t.srvid = conn->rand_srvid;
1042         t.reqid = ++conn->reqid;
1043
1044         data.dptr = (uint8_t *)&t;
1045         data.dsize = sizeof(t);
1046
1047         status = ctdbd_control(conn, CTDB_CURRENT_NODE,
1048                                CTDB_CONTROL_TRAVERSE_START, conn->rand_srvid,
1049                                data, NULL, NULL, &cstatus);
1050
1051         if (!NT_STATUS_IS_OK(status) || (cstatus != 0)) {
1052
1053                 DEBUG(0,("ctdbd_control failed: %s, %d\n", nt_errstr(status),
1054                          cstatus));
1055
1056                 if (NT_STATUS_IS_OK(status)) {
1057                         /*
1058                          * We need a mapping here
1059                          */
1060                         status = NT_STATUS_UNSUCCESSFUL;
1061                 }
1062                 goto done;
1063         }
1064
1065         state.fn = fn;
1066         state.private_data = private_data;
1067
1068         while (True) {
1069
1070                 status = NT_STATUS_OK;
1071
1072                 if (packet_handler(conn->pkt, ctdb_req_complete,
1073                                    ctdb_traverse_handler, &state, &status)) {
1074
1075                         if (NT_STATUS_EQUAL(status, NT_STATUS_END_OF_FILE)) {
1076                                 status = NT_STATUS_OK;
1077                                 break;
1078                         }
1079
1080                         /*
1081                          * There might be more in the queue
1082                          */
1083                         continue;
1084                 }
1085
1086                 if (!NT_STATUS_IS_OK(status)) {
1087                         break;
1088                 }
1089
1090                 status = packet_fd_read_sync(conn->pkt);
1091
1092                 if (NT_STATUS_EQUAL(status, NT_STATUS_END_OF_FILE)) {
1093                         status = NT_STATUS_OK;
1094                 }
1095
1096                 if (!NT_STATUS_IS_OK(status)) {
1097                         cluster_fatal("ctdbd died\n");
1098                 }
1099         }
1100
1101  done:
1102         TALLOC_FREE(conn);
1103         return status;
1104 }
1105
1106 /*
1107  * Register us as a server for a particular tcp connection
1108  */
1109
1110 NTSTATUS ctdbd_register_ips(struct ctdbd_connection *conn,
1111                             const struct sockaddr_in *server,
1112                             const struct sockaddr_in *client,
1113                             void (*release_ip_handler)(const char *ip_addr,
1114                                                        void *private_data),
1115                             void *private_data)
1116 {
1117         struct ctdb_control_tcp p;
1118         TDB_DATA data;
1119         NTSTATUS status;
1120
1121         /*
1122          * Only one connection so far
1123          */
1124         SMB_ASSERT(conn->release_ip_handler == NULL);
1125
1126         /*
1127          * We want to be told about IP releases
1128          */
1129
1130         status = register_with_ctdbd(conn, CTDB_SRVID_RELEASE_IP);
1131         if (!NT_STATUS_IS_OK(status)) {
1132                 return status;
1133         }
1134
1135         p.dest = *server;
1136         p.src = *client;
1137
1138         /*
1139          * inform ctdb of our tcp connection, so if IP takeover happens ctdb
1140          * can send an extra ack to trigger a reset for our client, so it
1141          * immediately reconnects
1142          */
1143         data.dptr = (uint8_t *)&p;
1144         data.dsize = sizeof(p);
1145
1146         return ctdbd_control(conn, CTDB_CURRENT_NODE, 
1147                              CTDB_CONTROL_TCP_CLIENT, 
1148                              CTDB_CTRL_FLAG_NOREPLY, data, NULL, NULL, NULL);
1149 }
1150
1151 /*
1152  * We want to handle reconfigure events
1153  */
1154 NTSTATUS ctdbd_register_reconfigure(struct ctdbd_connection *conn)
1155 {
1156         return register_with_ctdbd(conn, CTDB_SRVID_RECONFIGURE);
1157 }
1158
1159 #else
1160
1161 NTSTATUS ctdbd_init_connection(TALLOC_CTX *mem_ctx,
1162                                struct ctdbd_connection **pconn)
1163 {
1164         return NT_STATUS_NOT_IMPLEMENTED;
1165 }
1166
1167 #endif