ctdb-daemon: Stop using tevent compatibility definitions
[vlendec/samba-autobuild/.git] / ctdb / server / ctdb_call.c
1 /* 
2    ctdb_call protocol 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   see http://wiki.samba.org/index.php/Samba_%26_Clustering for
21   protocol design and packet details
22 */
23 #include "includes.h"
24 #include "tdb.h"
25 #include "lib/util/dlinklist.h"
26 #include "system/network.h"
27 #include "system/filesys.h"
28 #include "../include/ctdb_private.h"
29 #include "../common/rb_tree.h"
30 #include "common/reqid.h"
31 #include "common/system.h"
32
33 struct ctdb_sticky_record {
34         struct ctdb_context *ctdb;
35         struct ctdb_db_context *ctdb_db;
36         TDB_CONTEXT *pindown;
37 };
38
39 /*
40   find the ctdb_db from a db index
41  */
42  struct ctdb_db_context *find_ctdb_db(struct ctdb_context *ctdb, uint32_t id)
43 {
44         struct ctdb_db_context *ctdb_db;
45
46         for (ctdb_db=ctdb->db_list; ctdb_db; ctdb_db=ctdb_db->next) {
47                 if (ctdb_db->db_id == id) {
48                         break;
49                 }
50         }
51         return ctdb_db;
52 }
53
54 /*
55   a varient of input packet that can be used in lock requeue
56 */
57 static void ctdb_call_input_pkt(void *p, struct ctdb_req_header *hdr)
58 {
59         struct ctdb_context *ctdb = talloc_get_type(p, struct ctdb_context);
60         ctdb_input_pkt(ctdb, hdr);
61 }
62
63
64 /*
65   send an error reply
66 */
67 static void ctdb_send_error(struct ctdb_context *ctdb, 
68                             struct ctdb_req_header *hdr, uint32_t status,
69                             const char *fmt, ...) PRINTF_ATTRIBUTE(4,5);
70 static void ctdb_send_error(struct ctdb_context *ctdb, 
71                             struct ctdb_req_header *hdr, uint32_t status,
72                             const char *fmt, ...)
73 {
74         va_list ap;
75         struct ctdb_reply_error *r;
76         char *msg;
77         int msglen, len;
78
79         if (ctdb->methods == NULL) {
80                 DEBUG(DEBUG_INFO,(__location__ " Failed to send error. Transport is DOWN\n"));
81                 return;
82         }
83
84         va_start(ap, fmt);
85         msg = talloc_vasprintf(ctdb, fmt, ap);
86         if (msg == NULL) {
87                 ctdb_fatal(ctdb, "Unable to allocate error in ctdb_send_error\n");
88         }
89         va_end(ap);
90
91         msglen = strlen(msg)+1;
92         len = offsetof(struct ctdb_reply_error, msg);
93         r = ctdb_transport_allocate(ctdb, msg, CTDB_REPLY_ERROR, len + msglen, 
94                                     struct ctdb_reply_error);
95         CTDB_NO_MEMORY_FATAL(ctdb, r);
96
97         r->hdr.destnode  = hdr->srcnode;
98         r->hdr.reqid     = hdr->reqid;
99         r->status        = status;
100         r->msglen        = msglen;
101         memcpy(&r->msg[0], msg, msglen);
102
103         ctdb_queue_packet(ctdb, &r->hdr);
104
105         talloc_free(msg);
106 }
107
108
109 /**
110  * send a redirect reply
111  *
112  * The logic behind this function is this:
113  *
114  * A client wants to grab a record and sends a CTDB_REQ_CALL packet
115  * to its local ctdb (ctdb_request_call). If the node is not itself
116  * the record's DMASTER, it first redirects the packet to  the
117  * record's LMASTER. The LMASTER then redirects the call packet to
118  * the current DMASTER. Note that this works because of this: When
119  * a record is migrated off a node, then the new DMASTER is stored
120  * in the record's copy on the former DMASTER.
121  */
122 static void ctdb_call_send_redirect(struct ctdb_context *ctdb,
123                                     struct ctdb_db_context *ctdb_db,
124                                     TDB_DATA key,
125                                     struct ctdb_req_call *c, 
126                                     struct ctdb_ltdb_header *header)
127 {
128         uint32_t lmaster = ctdb_lmaster(ctdb, &key);
129
130         c->hdr.destnode = lmaster;
131         if (ctdb->pnn == lmaster) {
132                 c->hdr.destnode = header->dmaster;
133         }
134         c->hopcount++;
135
136         if (c->hopcount%100 > 95) {
137                 DEBUG(DEBUG_WARNING,("High hopcount %d dbid:%s "
138                         "key:0x%08x reqid=%08x pnn:%d src:%d lmaster:%d "
139                         "header->dmaster:%d dst:%d\n",
140                         c->hopcount, ctdb_db->db_name, ctdb_hash(&key),
141                         c->hdr.reqid, ctdb->pnn, c->hdr.srcnode, lmaster,
142                         header->dmaster, c->hdr.destnode));
143         }
144
145         ctdb_queue_packet(ctdb, &c->hdr);
146 }
147
148
149 /*
150   send a dmaster reply
151
152   caller must have the chainlock before calling this routine. Caller must be
153   the lmaster
154 */
155 static void ctdb_send_dmaster_reply(struct ctdb_db_context *ctdb_db,
156                                     struct ctdb_ltdb_header *header,
157                                     TDB_DATA key, TDB_DATA data,
158                                     uint32_t new_dmaster,
159                                     uint32_t reqid)
160 {
161         struct ctdb_context *ctdb = ctdb_db->ctdb;
162         struct ctdb_reply_dmaster *r;
163         int ret, len;
164         TALLOC_CTX *tmp_ctx;
165
166         if (ctdb->pnn != ctdb_lmaster(ctdb, &key)) {
167                 DEBUG(DEBUG_ALERT,(__location__ " Caller is not lmaster!\n"));
168                 return;
169         }
170
171         header->dmaster = new_dmaster;
172         ret = ctdb_ltdb_store(ctdb_db, key, header, data);
173         if (ret != 0) {
174                 ctdb_fatal(ctdb, "ctdb_send_dmaster_reply unable to update dmaster");
175                 return;
176         }
177
178         if (ctdb->methods == NULL) {
179                 ctdb_fatal(ctdb, "ctdb_send_dmaster_reply cant update dmaster since transport is down");
180                 return;
181         }
182
183         /* put the packet on a temporary context, allowing us to safely free
184            it below even if ctdb_reply_dmaster() has freed it already */
185         tmp_ctx = talloc_new(ctdb);
186
187         /* send the CTDB_REPLY_DMASTER */
188         len = offsetof(struct ctdb_reply_dmaster, data) + key.dsize + data.dsize + sizeof(uint32_t);
189         r = ctdb_transport_allocate(ctdb, tmp_ctx, CTDB_REPLY_DMASTER, len,
190                                     struct ctdb_reply_dmaster);
191         CTDB_NO_MEMORY_FATAL(ctdb, r);
192
193         r->hdr.destnode  = new_dmaster;
194         r->hdr.reqid     = reqid;
195         r->hdr.generation = ctdb_db->generation;
196         r->rsn           = header->rsn;
197         r->keylen        = key.dsize;
198         r->datalen       = data.dsize;
199         r->db_id         = ctdb_db->db_id;
200         memcpy(&r->data[0], key.dptr, key.dsize);
201         memcpy(&r->data[key.dsize], data.dptr, data.dsize);
202         memcpy(&r->data[key.dsize+data.dsize], &header->flags, sizeof(uint32_t));
203
204         ctdb_queue_packet(ctdb, &r->hdr);
205
206         talloc_free(tmp_ctx);
207 }
208
209 /*
210   send a dmaster request (give another node the dmaster for a record)
211
212   This is always sent to the lmaster, which ensures that the lmaster
213   always knows who the dmaster is. The lmaster will then send a
214   CTDB_REPLY_DMASTER to the new dmaster
215 */
216 static void ctdb_call_send_dmaster(struct ctdb_db_context *ctdb_db, 
217                                    struct ctdb_req_call *c, 
218                                    struct ctdb_ltdb_header *header,
219                                    TDB_DATA *key, TDB_DATA *data)
220 {
221         struct ctdb_req_dmaster *r;
222         struct ctdb_context *ctdb = ctdb_db->ctdb;
223         int len;
224         uint32_t lmaster = ctdb_lmaster(ctdb, key);
225
226         if (ctdb->methods == NULL) {
227                 ctdb_fatal(ctdb, "Failed ctdb_call_send_dmaster since transport is down");
228                 return;
229         }
230
231         if (data->dsize != 0) {
232                 header->flags |= CTDB_REC_FLAG_MIGRATED_WITH_DATA;
233         }
234
235         if (lmaster == ctdb->pnn) {
236                 ctdb_send_dmaster_reply(ctdb_db, header, *key, *data, 
237                                         c->hdr.srcnode, c->hdr.reqid);
238                 return;
239         }
240         
241         len = offsetof(struct ctdb_req_dmaster, data) + key->dsize + data->dsize
242                         + sizeof(uint32_t);
243         r = ctdb_transport_allocate(ctdb, ctdb, CTDB_REQ_DMASTER, len, 
244                                     struct ctdb_req_dmaster);
245         CTDB_NO_MEMORY_FATAL(ctdb, r);
246         r->hdr.destnode  = lmaster;
247         r->hdr.reqid     = c->hdr.reqid;
248         r->hdr.generation = ctdb_db->generation;
249         r->db_id         = c->db_id;
250         r->rsn           = header->rsn;
251         r->dmaster       = c->hdr.srcnode;
252         r->keylen        = key->dsize;
253         r->datalen       = data->dsize;
254         memcpy(&r->data[0], key->dptr, key->dsize);
255         memcpy(&r->data[key->dsize], data->dptr, data->dsize);
256         memcpy(&r->data[key->dsize + data->dsize], &header->flags, sizeof(uint32_t));
257
258         header->dmaster = c->hdr.srcnode;
259         if (ctdb_ltdb_store(ctdb_db, *key, header, *data) != 0) {
260                 ctdb_fatal(ctdb, "Failed to store record in ctdb_call_send_dmaster");
261         }
262         
263         ctdb_queue_packet(ctdb, &r->hdr);
264
265         talloc_free(r);
266 }
267
268 static void ctdb_sticky_pindown_timeout(struct tevent_context *ev,
269                                         struct tevent_timer *te,
270                                         struct timeval t, void *private_data)
271 {
272         struct ctdb_sticky_record *sr = talloc_get_type(private_data, 
273                                                        struct ctdb_sticky_record);
274
275         DEBUG(DEBUG_ERR,("Pindown timeout db:%s  unstick record\n", sr->ctdb_db->db_name));
276         if (sr->pindown != NULL) {
277                 talloc_free(sr->pindown);
278                 sr->pindown = NULL;
279         }
280 }
281
282 static int
283 ctdb_set_sticky_pindown(struct ctdb_context *ctdb, struct ctdb_db_context *ctdb_db, TDB_DATA key)
284 {
285         TALLOC_CTX *tmp_ctx = talloc_new(NULL);
286         uint32_t *k;
287         struct ctdb_sticky_record *sr;
288
289         k = ctdb_key_to_idkey(tmp_ctx, key);
290         if (k == NULL) {
291                 DEBUG(DEBUG_ERR,("Failed to allocate key for sticky record\n"));
292                 talloc_free(tmp_ctx);
293                 return -1;
294         }
295
296         sr = trbt_lookuparray32(ctdb_db->sticky_records, k[0], &k[0]);
297         if (sr == NULL) {
298                 talloc_free(tmp_ctx);
299                 return 0;
300         }
301
302         talloc_free(tmp_ctx);
303
304         if (sr->pindown == NULL) {
305                 DEBUG(DEBUG_ERR,("Pinning down record in %s for %d ms\n", ctdb_db->db_name, ctdb->tunable.sticky_pindown));
306                 sr->pindown = talloc_new(sr);
307                 if (sr->pindown == NULL) {
308                         DEBUG(DEBUG_ERR,("Failed to allocate pindown context for sticky record\n"));
309                         return -1;
310                 }
311                 tevent_add_timer(ctdb->ev, sr->pindown,
312                                  timeval_current_ofs(ctdb->tunable.sticky_pindown / 1000,
313                                                      (ctdb->tunable.sticky_pindown * 1000) % 1000000),
314                                  ctdb_sticky_pindown_timeout, sr);
315         }
316
317         return 0;
318 }
319
320 /*
321   called when a CTDB_REPLY_DMASTER packet comes in, or when the lmaster
322   gets a CTDB_REQUEST_DMASTER for itself. We become the dmaster.
323
324   must be called with the chainlock held. This function releases the chainlock
325 */
326 static void ctdb_become_dmaster(struct ctdb_db_context *ctdb_db,
327                                 struct ctdb_req_header *hdr,
328                                 TDB_DATA key, TDB_DATA data,
329                                 uint64_t rsn, uint32_t record_flags)
330 {
331         struct ctdb_call_state *state;
332         struct ctdb_context *ctdb = ctdb_db->ctdb;
333         struct ctdb_ltdb_header header;
334         int ret;
335
336         DEBUG(DEBUG_DEBUG,("pnn %u dmaster response %08x\n", ctdb->pnn, ctdb_hash(&key)));
337
338         ZERO_STRUCT(header);
339         header.rsn = rsn;
340         header.dmaster = ctdb->pnn;
341         header.flags = record_flags;
342
343         state = reqid_find(ctdb->idr, hdr->reqid, struct ctdb_call_state);
344
345         if (state) {
346                 if (state->call->flags & CTDB_CALL_FLAG_VACUUM_MIGRATION) {
347                         /*
348                          * We temporarily add the VACUUM_MIGRATED flag to
349                          * the record flags, so that ctdb_ltdb_store can
350                          * decide whether the record should be stored or
351                          * deleted.
352                          */
353                         header.flags |= CTDB_REC_FLAG_VACUUM_MIGRATED;
354                 }
355         }
356
357         if (ctdb_ltdb_store(ctdb_db, key, &header, data) != 0) {
358                 ctdb_fatal(ctdb, "ctdb_reply_dmaster store failed\n");
359
360                 ret = ctdb_ltdb_unlock(ctdb_db, key);
361                 if (ret != 0) {
362                         DEBUG(DEBUG_ERR,(__location__ " ctdb_ltdb_unlock() failed with error %d\n", ret));
363                 }
364                 return;
365         }
366
367         /* we just became DMASTER and this database is "sticky",
368            see if the record is flagged as "hot" and set up a pin-down
369            context to stop migrations for a little while if so
370         */
371         if (ctdb_db->sticky) {
372                 ctdb_set_sticky_pindown(ctdb, ctdb_db, key);
373         }
374
375         if (state == NULL) {
376                 DEBUG(DEBUG_ERR,("pnn %u Invalid reqid %u in ctdb_become_dmaster from node %u\n",
377                          ctdb->pnn, hdr->reqid, hdr->srcnode));
378
379                 ret = ctdb_ltdb_unlock(ctdb_db, key);
380                 if (ret != 0) {
381                         DEBUG(DEBUG_ERR,(__location__ " ctdb_ltdb_unlock() failed with error %d\n", ret));
382                 }
383                 return;
384         }
385
386         if (key.dsize != state->call->key.dsize || memcmp(key.dptr, state->call->key.dptr, key.dsize)) {
387                 DEBUG(DEBUG_ERR, ("Got bogus DMASTER packet reqid:%u from node %u. Key does not match key held in matching idr.\n", hdr->reqid, hdr->srcnode));
388
389                 ret = ctdb_ltdb_unlock(ctdb_db, key);
390                 if (ret != 0) {
391                         DEBUG(DEBUG_ERR,(__location__ " ctdb_ltdb_unlock() failed with error %d\n", ret));
392                 }
393                 return;
394         }
395
396         if (hdr->reqid != state->reqid) {
397                 /* we found a record  but it was the wrong one */
398                 DEBUG(DEBUG_ERR, ("Dropped orphan in ctdb_become_dmaster with reqid:%u\n from node %u", hdr->reqid, hdr->srcnode));
399
400                 ret = ctdb_ltdb_unlock(ctdb_db, key);
401                 if (ret != 0) {
402                         DEBUG(DEBUG_ERR,(__location__ " ctdb_ltdb_unlock() failed with error %d\n", ret));
403                 }
404                 return;
405         }
406
407         ctdb_call_local(ctdb_db, state->call, &header, state, &data, true);
408
409         ret = ctdb_ltdb_unlock(ctdb_db, state->call->key);
410         if (ret != 0) {
411                 DEBUG(DEBUG_ERR,(__location__ " ctdb_ltdb_unlock() failed with error %d\n", ret));
412         }
413
414         state->state = CTDB_CALL_DONE;
415         if (state->async.fn) {
416                 state->async.fn(state);
417         }
418 }
419
420 struct dmaster_defer_call {
421         struct dmaster_defer_call *next, *prev;
422         struct ctdb_context *ctdb;
423         struct ctdb_req_header *hdr;
424 };
425
426 struct dmaster_defer_queue {
427         struct ctdb_db_context *ctdb_db;
428         uint32_t generation;
429         struct dmaster_defer_call *deferred_calls;
430 };
431
432 static void dmaster_defer_reprocess(struct tevent_context *ev,
433                                     struct tevent_timer *te,
434                                     struct timeval t,
435                                     void *private_data)
436 {
437         struct dmaster_defer_call *call = talloc_get_type(
438                 private_data, struct dmaster_defer_call);
439
440         ctdb_input_pkt(call->ctdb, call->hdr);
441         talloc_free(call);
442 }
443
444 static int dmaster_defer_queue_destructor(struct dmaster_defer_queue *ddq)
445 {
446         /* Ignore requests, if database recovery happens in-between. */
447         if (ddq->generation != ddq->ctdb_db->generation) {
448                 return 0;
449         }
450
451         while (ddq->deferred_calls != NULL) {
452                 struct dmaster_defer_call *call = ddq->deferred_calls;
453
454                 DLIST_REMOVE(ddq->deferred_calls, call);
455
456                 talloc_steal(call->ctdb, call);
457                 tevent_add_timer(call->ctdb->ev, call, timeval_zero(),
458                                  dmaster_defer_reprocess, call);
459         }
460         return 0;
461 }
462
463 static void *insert_ddq_callback(void *parm, void *data)
464 {
465         if (data) {
466                 talloc_free(data);
467         }
468         return parm;
469 }
470
471 /**
472  * This function is used to reigster a key in database that needs to be updated.
473  * Any requests for that key should get deferred till this is completed.
474  */
475 static int dmaster_defer_setup(struct ctdb_db_context *ctdb_db,
476                                struct ctdb_req_header *hdr,
477                                TDB_DATA key)
478 {
479         uint32_t *k;
480         struct dmaster_defer_queue *ddq;
481
482         k = ctdb_key_to_idkey(hdr, key);
483         if (k == NULL) {
484                 DEBUG(DEBUG_ERR, ("Failed to allocate key for dmaster defer setup\n"));
485                 return -1;
486         }
487
488         /* Already exists */
489         ddq = trbt_lookuparray32(ctdb_db->defer_dmaster, k[0], k);
490         if (ddq != NULL) {
491                 if (ddq->generation == ctdb_db->generation) {
492                         talloc_free(k);
493                         return 0;
494                 }
495
496                 /* Recovery ocurred - get rid of old queue. All the deferred
497                  * requests will be resent anyway from ctdb_call_resend_db.
498                  */
499                 talloc_free(ddq);
500         }
501
502         ddq = talloc(hdr, struct dmaster_defer_queue);
503         if (ddq == NULL) {
504                 DEBUG(DEBUG_ERR, ("Failed to allocate dmaster defer queue\n"));
505                 talloc_free(k);
506                 return -1;
507         }
508         ddq->ctdb_db = ctdb_db;
509         ddq->generation = hdr->generation;
510         ddq->deferred_calls = NULL;
511
512         trbt_insertarray32_callback(ctdb_db->defer_dmaster, k[0], k,
513                                     insert_ddq_callback, ddq);
514         talloc_set_destructor(ddq, dmaster_defer_queue_destructor);
515
516         talloc_free(k);
517         return 0;
518 }
519
520 static int dmaster_defer_add(struct ctdb_db_context *ctdb_db,
521                              struct ctdb_req_header *hdr,
522                              TDB_DATA key)
523 {
524         struct dmaster_defer_queue *ddq;
525         struct dmaster_defer_call *call;
526         uint32_t *k;
527
528         k = ctdb_key_to_idkey(hdr, key);
529         if (k == NULL) {
530                 DEBUG(DEBUG_ERR, ("Failed to allocate key for dmaster defer add\n"));
531                 return -1;
532         }
533
534         ddq = trbt_lookuparray32(ctdb_db->defer_dmaster, k[0], k);
535         if (ddq == NULL) {
536                 talloc_free(k);
537                 return -1;
538         }
539
540         talloc_free(k);
541
542         if (ddq->generation != hdr->generation) {
543                 talloc_set_destructor(ddq, NULL);
544                 talloc_free(ddq);
545                 return -1;
546         }
547
548         call = talloc(ddq, struct dmaster_defer_call);
549         if (call == NULL) {
550                 DEBUG(DEBUG_ERR, ("Failed to allocate dmaster defer call\n"));
551                 return -1;
552         }
553
554         call->ctdb = ctdb_db->ctdb;
555         call->hdr = talloc_steal(call, hdr);
556
557         DLIST_ADD_END(ddq->deferred_calls, call, NULL);
558
559         return 0;
560 }
561
562 /*
563   called when a CTDB_REQ_DMASTER packet comes in
564
565   this comes into the lmaster for a record when the current dmaster
566   wants to give up the dmaster role and give it to someone else
567 */
568 void ctdb_request_dmaster(struct ctdb_context *ctdb, struct ctdb_req_header *hdr)
569 {
570         struct ctdb_req_dmaster *c = (struct ctdb_req_dmaster *)hdr;
571         TDB_DATA key, data, data2;
572         struct ctdb_ltdb_header header;
573         struct ctdb_db_context *ctdb_db;
574         uint32_t record_flags = 0;
575         size_t len;
576         int ret;
577
578         ctdb_db = find_ctdb_db(ctdb, c->db_id);
579         if (!ctdb_db) {
580                 ctdb_send_error(ctdb, hdr, -1,
581                                 "Unknown database in request. db_id==0x%08x",
582                                 c->db_id);
583                 return;
584         }
585
586         if (hdr->generation != ctdb_db->generation) {
587                 DEBUG(DEBUG_DEBUG,
588                       ("ctdb operation %u request %u from node %u to %u had an"
589                        " invalid generation:%u while our generation is:%u\n",
590                        hdr->operation, hdr->reqid, hdr->srcnode, hdr->destnode,
591                        hdr->generation, ctdb_db->generation));
592                 return;
593         }
594
595         key.dptr = c->data;
596         key.dsize = c->keylen;
597         data.dptr = c->data + c->keylen;
598         data.dsize = c->datalen;
599         len = offsetof(struct ctdb_req_dmaster, data) + key.dsize + data.dsize
600                         + sizeof(uint32_t);
601         if (len <= c->hdr.length) {
602                 memcpy(&record_flags, &c->data[c->keylen + c->datalen],
603                        sizeof(record_flags));
604         }
605
606         dmaster_defer_setup(ctdb_db, hdr, key);
607
608         /* fetch the current record */
609         ret = ctdb_ltdb_lock_fetch_requeue(ctdb_db, key, &header, hdr, &data2,
610                                            ctdb_call_input_pkt, ctdb, false);
611         if (ret == -1) {
612                 ctdb_fatal(ctdb, "ctdb_req_dmaster failed to fetch record");
613                 return;
614         }
615         if (ret == -2) {
616                 DEBUG(DEBUG_INFO,(__location__ " deferring ctdb_request_dmaster\n"));
617                 return;
618         }
619
620         if (ctdb_lmaster(ctdb, &key) != ctdb->pnn) {
621                 DEBUG(DEBUG_ALERT,("pnn %u dmaster request to non-lmaster lmaster=%u gen=%u curgen=%u\n",
622                          ctdb->pnn, ctdb_lmaster(ctdb, &key), 
623                          hdr->generation, ctdb->vnn_map->generation));
624                 ctdb_fatal(ctdb, "ctdb_req_dmaster to non-lmaster");
625         }
626
627         DEBUG(DEBUG_DEBUG,("pnn %u dmaster request on %08x for %u from %u\n", 
628                  ctdb->pnn, ctdb_hash(&key), c->dmaster, c->hdr.srcnode));
629
630         /* its a protocol error if the sending node is not the current dmaster */
631         if (header.dmaster != hdr->srcnode) {
632                 DEBUG(DEBUG_ALERT,("pnn %u dmaster request for new-dmaster %u from non-master %u real-dmaster=%u key %08x dbid 0x%08x gen=%u curgen=%u c->rsn=%llu header.rsn=%llu reqid=%u keyval=0x%08x\n",
633                          ctdb->pnn, c->dmaster, hdr->srcnode, header.dmaster, ctdb_hash(&key),
634                          ctdb_db->db_id, hdr->generation, ctdb_db->generation,
635                          (unsigned long long)c->rsn, (unsigned long long)header.rsn, c->hdr.reqid,
636                          (key.dsize >= 4)?(*(uint32_t *)key.dptr):0));
637                 if (header.rsn != 0 || header.dmaster != ctdb->pnn) {
638                         DEBUG(DEBUG_ERR,("ctdb_req_dmaster from non-master. Force a recovery.\n"));
639
640                         ctdb->recovery_mode = CTDB_RECOVERY_ACTIVE;
641                         ctdb_ltdb_unlock(ctdb_db, key);
642                         return;
643                 }
644         }
645
646         if (header.rsn > c->rsn) {
647                 DEBUG(DEBUG_ALERT,("pnn %u dmaster request with older RSN new-dmaster %u from %u real-dmaster=%u key %08x dbid 0x%08x gen=%u curgen=%u c->rsn=%llu header.rsn=%llu reqid=%u\n",
648                          ctdb->pnn, c->dmaster, hdr->srcnode, header.dmaster, ctdb_hash(&key),
649                          ctdb_db->db_id, hdr->generation, ctdb_db->generation,
650                          (unsigned long long)c->rsn, (unsigned long long)header.rsn, c->hdr.reqid));
651         }
652
653         /* use the rsn from the sending node */
654         header.rsn = c->rsn;
655
656         /* store the record flags from the sending node */
657         header.flags = record_flags;
658
659         /* check if the new dmaster is the lmaster, in which case we
660            skip the dmaster reply */
661         if (c->dmaster == ctdb->pnn) {
662                 ctdb_become_dmaster(ctdb_db, hdr, key, data, c->rsn, record_flags);
663         } else {
664                 ctdb_send_dmaster_reply(ctdb_db, &header, key, data, c->dmaster, hdr->reqid);
665
666                 ret = ctdb_ltdb_unlock(ctdb_db, key);
667                 if (ret != 0) {
668                         DEBUG(DEBUG_ERR,(__location__ " ctdb_ltdb_unlock() failed with error %d\n", ret));
669                 }
670         }
671 }
672
673 static void ctdb_sticky_record_timeout(struct tevent_context *ev,
674                                        struct tevent_timer *te,
675                                        struct timeval t, void *private_data)
676 {
677         struct ctdb_sticky_record *sr = talloc_get_type(private_data, 
678                                                        struct ctdb_sticky_record);
679         talloc_free(sr);
680 }
681
682 static void *ctdb_make_sticky_record_callback(void *parm, void *data)
683 {
684         if (data) {
685                 DEBUG(DEBUG_ERR,("Already have sticky record registered. Free old %p and create new %p\n", data, parm));
686                 talloc_free(data);
687         }
688         return parm;
689 }
690
691 static int
692 ctdb_make_record_sticky(struct ctdb_context *ctdb, struct ctdb_db_context *ctdb_db, TDB_DATA key)
693 {
694         TALLOC_CTX *tmp_ctx = talloc_new(NULL);
695         uint32_t *k;
696         struct ctdb_sticky_record *sr;
697
698         k = ctdb_key_to_idkey(tmp_ctx, key);
699         if (k == NULL) {
700                 DEBUG(DEBUG_ERR,("Failed to allocate key for sticky record\n"));
701                 talloc_free(tmp_ctx);
702                 return -1;
703         }
704
705         sr = trbt_lookuparray32(ctdb_db->sticky_records, k[0], &k[0]);
706         if (sr != NULL) {
707                 talloc_free(tmp_ctx);
708                 return 0;
709         }
710
711         sr = talloc(ctdb_db->sticky_records, struct ctdb_sticky_record);
712         if (sr == NULL) {
713                 talloc_free(tmp_ctx);
714                 DEBUG(DEBUG_ERR,("Failed to allocate sticky record structure\n"));
715                 return -1;
716         }
717
718         sr->ctdb    = ctdb;
719         sr->ctdb_db = ctdb_db;
720         sr->pindown = NULL;
721
722         DEBUG(DEBUG_ERR,("Make record sticky for %d seconds in db %s key:0x%08x.\n",
723                          ctdb->tunable.sticky_duration,
724                          ctdb_db->db_name, ctdb_hash(&key)));
725
726         trbt_insertarray32_callback(ctdb_db->sticky_records, k[0], &k[0], ctdb_make_sticky_record_callback, sr);
727
728         tevent_add_timer(ctdb->ev, sr,
729                          timeval_current_ofs(ctdb->tunable.sticky_duration, 0),
730                          ctdb_sticky_record_timeout, sr);
731
732         talloc_free(tmp_ctx);
733         return 0;
734 }
735
736 struct pinned_down_requeue_handle {
737         struct ctdb_context *ctdb;
738         struct ctdb_req_header *hdr;
739 };
740
741 struct pinned_down_deferred_call {
742         struct ctdb_context *ctdb;
743         struct ctdb_req_header *hdr;
744 };
745
746 static void pinned_down_requeue(struct tevent_context *ev,
747                                 struct tevent_timer *te,
748                                 struct timeval t, void *private_data)
749 {
750         struct pinned_down_requeue_handle *handle = talloc_get_type(private_data, struct pinned_down_requeue_handle);
751         struct ctdb_context *ctdb = handle->ctdb;
752
753         talloc_steal(ctdb, handle->hdr);
754         ctdb_call_input_pkt(ctdb, handle->hdr);
755
756         talloc_free(handle);
757 }
758
759 static int pinned_down_destructor(struct pinned_down_deferred_call *pinned_down)
760 {
761         struct ctdb_context *ctdb = pinned_down->ctdb;
762         struct pinned_down_requeue_handle *handle = talloc(ctdb, struct pinned_down_requeue_handle);
763
764         handle->ctdb = pinned_down->ctdb;
765         handle->hdr  = pinned_down->hdr;
766         talloc_steal(handle, handle->hdr);
767
768         tevent_add_timer(ctdb->ev, handle, timeval_zero(),
769                          pinned_down_requeue, handle);
770
771         return 0;
772 }
773
774 static int
775 ctdb_defer_pinned_down_request(struct ctdb_context *ctdb, struct ctdb_db_context *ctdb_db, TDB_DATA key, struct ctdb_req_header *hdr)
776 {
777         TALLOC_CTX *tmp_ctx = talloc_new(NULL);
778         uint32_t *k;
779         struct ctdb_sticky_record *sr;
780         struct pinned_down_deferred_call *pinned_down;
781
782         k = ctdb_key_to_idkey(tmp_ctx, key);
783         if (k == NULL) {
784                 DEBUG(DEBUG_ERR,("Failed to allocate key for sticky record\n"));
785                 talloc_free(tmp_ctx);
786                 return -1;
787         }
788
789         sr = trbt_lookuparray32(ctdb_db->sticky_records, k[0], &k[0]);
790         if (sr == NULL) {
791                 talloc_free(tmp_ctx);
792                 return -1;
793         }
794
795         talloc_free(tmp_ctx);
796
797         if (sr->pindown == NULL) {
798                 return -1;
799         }
800         
801         pinned_down = talloc(sr->pindown, struct pinned_down_deferred_call);
802         if (pinned_down == NULL) {
803                 DEBUG(DEBUG_ERR,("Failed to allocate structure for deferred pinned down request\n"));
804                 return -1;
805         }
806
807         pinned_down->ctdb = ctdb;
808         pinned_down->hdr  = hdr;
809
810         talloc_set_destructor(pinned_down, pinned_down_destructor);
811         talloc_steal(pinned_down, hdr);
812
813         return 0;
814 }
815
816 static void
817 ctdb_update_db_stat_hot_keys(struct ctdb_db_context *ctdb_db, TDB_DATA key, int hopcount)
818 {
819         int i, id;
820
821         /* smallest value is always at index 0 */
822         if (hopcount <= ctdb_db->statistics.hot_keys[0].count) {
823                 return;
824         }
825
826         /* see if we already know this key */
827         for (i = 0; i < MAX_HOT_KEYS; i++) {
828                 if (key.dsize != ctdb_db->statistics.hot_keys[i].key.dsize) {
829                         continue;
830                 }
831                 if (memcmp(key.dptr, ctdb_db->statistics.hot_keys[i].key.dptr, key.dsize)) {
832                         continue;
833                 }
834                 /* found an entry for this key */
835                 if (hopcount <= ctdb_db->statistics.hot_keys[i].count) {
836                         return;
837                 }
838                 ctdb_db->statistics.hot_keys[i].count = hopcount;
839                 goto sort_keys;
840         }
841
842         if (ctdb_db->statistics.num_hot_keys < MAX_HOT_KEYS) {
843                 id = ctdb_db->statistics.num_hot_keys;
844                 ctdb_db->statistics.num_hot_keys++;
845         } else {
846                 id = 0;
847         }
848
849         if (ctdb_db->statistics.hot_keys[id].key.dptr != NULL) {
850                 talloc_free(ctdb_db->statistics.hot_keys[id].key.dptr);
851         }
852         ctdb_db->statistics.hot_keys[id].key.dsize = key.dsize;
853         ctdb_db->statistics.hot_keys[id].key.dptr  = talloc_memdup(ctdb_db, key.dptr, key.dsize);
854         ctdb_db->statistics.hot_keys[id].count = hopcount;
855         DEBUG(DEBUG_NOTICE,("Updated hot key database=%s key=0x%08x id=%d hop_count=%d\n",
856                             ctdb_db->db_name, ctdb_hash(&key), id, hopcount));
857
858 sort_keys:
859         for (i = 1; i < MAX_HOT_KEYS; i++) {
860                 if (ctdb_db->statistics.hot_keys[i].count == 0) {
861                         continue;
862                 }
863                 if (ctdb_db->statistics.hot_keys[i].count < ctdb_db->statistics.hot_keys[0].count) {
864                         hopcount = ctdb_db->statistics.hot_keys[i].count;
865                         ctdb_db->statistics.hot_keys[i].count = ctdb_db->statistics.hot_keys[0].count;
866                         ctdb_db->statistics.hot_keys[0].count = hopcount;
867
868                         key = ctdb_db->statistics.hot_keys[i].key;
869                         ctdb_db->statistics.hot_keys[i].key = ctdb_db->statistics.hot_keys[0].key;
870                         ctdb_db->statistics.hot_keys[0].key = key;
871                 }
872         }
873 }
874
875 /*
876   called when a CTDB_REQ_CALL packet comes in
877 */
878 void ctdb_request_call(struct ctdb_context *ctdb, struct ctdb_req_header *hdr)
879 {
880         struct ctdb_req_call *c = (struct ctdb_req_call *)hdr;
881         TDB_DATA data;
882         struct ctdb_reply_call *r;
883         int ret, len;
884         struct ctdb_ltdb_header header;
885         struct ctdb_call *call;
886         struct ctdb_db_context *ctdb_db;
887         int tmp_count, bucket;
888
889         if (ctdb->methods == NULL) {
890                 DEBUG(DEBUG_INFO,(__location__ " Failed ctdb_request_call. Transport is DOWN\n"));
891                 return;
892         }
893
894         ctdb_db = find_ctdb_db(ctdb, c->db_id);
895         if (!ctdb_db) {
896                 ctdb_send_error(ctdb, hdr, -1,
897                                 "Unknown database in request. db_id==0x%08x",
898                                 c->db_id);
899                 return;
900         }
901
902         if (hdr->generation != ctdb_db->generation) {
903                 DEBUG(DEBUG_DEBUG,
904                       ("ctdb operation %u request %u from node %u to %u had an"
905                        " invalid generation:%u while our generation is:%u\n",
906                        hdr->operation, hdr->reqid, hdr->srcnode, hdr->destnode,
907                        hdr->generation, ctdb_db->generation));
908                 return;
909         }
910
911         call = talloc(hdr, struct ctdb_call);
912         CTDB_NO_MEMORY_FATAL(ctdb, call);
913
914         call->call_id  = c->callid;
915         call->key.dptr = c->data;
916         call->key.dsize = c->keylen;
917         call->call_data.dptr = c->data + c->keylen;
918         call->call_data.dsize = c->calldatalen;
919         call->reply_data.dptr  = NULL;
920         call->reply_data.dsize = 0;
921
922
923         /* If this record is pinned down we should defer the
924            request until the pindown times out
925         */
926         if (ctdb_db->sticky) {
927                 if (ctdb_defer_pinned_down_request(ctdb, ctdb_db, call->key, hdr) == 0) {
928                         DEBUG(DEBUG_WARNING,
929                               ("Defer request for pinned down record in %s\n", ctdb_db->db_name));
930                         talloc_free(call);
931                         return;
932                 }
933         }
934
935         if (dmaster_defer_add(ctdb_db, hdr, call->key) == 0) {
936                 talloc_free(call);
937                 return;
938         }
939
940         /* determine if we are the dmaster for this key. This also
941            fetches the record data (if any), thus avoiding a 2nd fetch of the data 
942            if the call will be answered locally */
943
944         ret = ctdb_ltdb_lock_fetch_requeue(ctdb_db, call->key, &header, hdr, &data,
945                                            ctdb_call_input_pkt, ctdb, false);
946         if (ret == -1) {
947                 ctdb_send_error(ctdb, hdr, ret, "ltdb fetch failed in ctdb_request_call");
948                 talloc_free(call);
949                 return;
950         }
951         if (ret == -2) {
952                 DEBUG(DEBUG_INFO,(__location__ " deferred ctdb_request_call\n"));
953                 talloc_free(call);
954                 return;
955         }
956
957         /* Dont do READONLY if we dont have a tracking database */
958         if ((c->flags & CTDB_WANT_READONLY) && !ctdb_db->readonly) {
959                 c->flags &= ~CTDB_WANT_READONLY;
960         }
961
962         if (header.flags & CTDB_REC_RO_REVOKE_COMPLETE) {
963                 header.flags &= ~CTDB_REC_RO_FLAGS;
964                 CTDB_INCREMENT_STAT(ctdb, total_ro_revokes);
965                 CTDB_INCREMENT_DB_STAT(ctdb_db, db_ro_revokes);
966                 if (ctdb_ltdb_store(ctdb_db, call->key, &header, data) != 0) {
967                         ctdb_fatal(ctdb, "Failed to write header with cleared REVOKE flag");
968                 }
969                 /* and clear out the tracking data */
970                 if (tdb_delete(ctdb_db->rottdb, call->key) != 0) {
971                         DEBUG(DEBUG_ERR,(__location__ " Failed to clear out trackingdb record\n"));
972                 }
973         }
974
975         /* if we are revoking, we must defer all other calls until the revoke
976          * had completed.
977          */
978         if (header.flags & CTDB_REC_RO_REVOKING_READONLY) {
979                 talloc_free(data.dptr);
980                 ret = ctdb_ltdb_unlock(ctdb_db, call->key);
981
982                 if (ctdb_add_revoke_deferred_call(ctdb, ctdb_db, call->key, hdr, ctdb_call_input_pkt, ctdb) != 0) {
983                         ctdb_fatal(ctdb, "Failed to add deferred call for revoke child");
984                 }
985                 talloc_free(call);
986                 return;
987         }
988
989         /*
990          * If we are not the dmaster and are not hosting any delegations,
991          * then we redirect the request to the node than can answer it
992          * (the lmaster or the dmaster).
993          */
994         if ((header.dmaster != ctdb->pnn) 
995             && (!(header.flags & CTDB_REC_RO_HAVE_DELEGATIONS)) ) {
996                 talloc_free(data.dptr);
997                 ctdb_call_send_redirect(ctdb, ctdb_db, call->key, c, &header);
998
999                 ret = ctdb_ltdb_unlock(ctdb_db, call->key);
1000                 if (ret != 0) {
1001                         DEBUG(DEBUG_ERR,(__location__ " ctdb_ltdb_unlock() failed with error %d\n", ret));
1002                 }
1003                 talloc_free(call);
1004                 return;
1005         }
1006
1007         if ( (!(c->flags & CTDB_WANT_READONLY))
1008         && (header.flags & (CTDB_REC_RO_HAVE_DELEGATIONS|CTDB_REC_RO_HAVE_READONLY)) ) {
1009                 header.flags   |= CTDB_REC_RO_REVOKING_READONLY;
1010                 if (ctdb_ltdb_store(ctdb_db, call->key, &header, data) != 0) {
1011                         ctdb_fatal(ctdb, "Failed to store record with HAVE_DELEGATIONS set");
1012                 }
1013                 ret = ctdb_ltdb_unlock(ctdb_db, call->key);
1014
1015                 if (ctdb_start_revoke_ro_record(ctdb, ctdb_db, call->key, &header, data) != 0) {
1016                         ctdb_fatal(ctdb, "Failed to start record revoke");
1017                 }
1018                 talloc_free(data.dptr);
1019
1020                 if (ctdb_add_revoke_deferred_call(ctdb, ctdb_db, call->key, hdr, ctdb_call_input_pkt, ctdb) != 0) {
1021                         ctdb_fatal(ctdb, "Failed to add deferred call for revoke child");
1022                 }
1023                 talloc_free(call);
1024
1025                 return;
1026         }               
1027
1028         /* If this is the first request for delegation. bump rsn and set
1029          * the delegations flag
1030          */
1031         if ((c->flags & CTDB_WANT_READONLY)
1032         &&  (c->callid == CTDB_FETCH_WITH_HEADER_FUNC)
1033         &&  (!(header.flags & CTDB_REC_RO_HAVE_DELEGATIONS))) {
1034                 header.rsn     += 3;
1035                 header.flags   |= CTDB_REC_RO_HAVE_DELEGATIONS;
1036                 if (ctdb_ltdb_store(ctdb_db, call->key, &header, data) != 0) {
1037                         ctdb_fatal(ctdb, "Failed to store record with HAVE_DELEGATIONS set");
1038                 }
1039         }
1040         if ((c->flags & CTDB_WANT_READONLY) 
1041         &&  (call->call_id == CTDB_FETCH_WITH_HEADER_FUNC)) {
1042                 TDB_DATA tdata;
1043
1044                 tdata = tdb_fetch(ctdb_db->rottdb, call->key);
1045                 if (ctdb_trackingdb_add_pnn(ctdb, &tdata, c->hdr.srcnode) != 0) {
1046                         ctdb_fatal(ctdb, "Failed to add node to trackingdb");
1047                 }
1048                 if (tdb_store(ctdb_db->rottdb, call->key, tdata, TDB_REPLACE) != 0) {
1049                         ctdb_fatal(ctdb, "Failed to store trackingdb data");
1050                 }
1051                 free(tdata.dptr);
1052
1053                 ret = ctdb_ltdb_unlock(ctdb_db, call->key);
1054                 if (ret != 0) {
1055                         DEBUG(DEBUG_ERR,(__location__ " ctdb_ltdb_unlock() failed with error %d\n", ret));
1056                 }
1057
1058                 len = offsetof(struct ctdb_reply_call, data) + data.dsize + sizeof(struct ctdb_ltdb_header);
1059                 r = ctdb_transport_allocate(ctdb, ctdb, CTDB_REPLY_CALL, len, 
1060                                             struct ctdb_reply_call);
1061                 CTDB_NO_MEMORY_FATAL(ctdb, r);
1062                 r->hdr.destnode  = c->hdr.srcnode;
1063                 r->hdr.reqid     = c->hdr.reqid;
1064                 r->hdr.generation = ctdb_db->generation;
1065                 r->status        = 0;
1066                 r->datalen       = data.dsize + sizeof(struct ctdb_ltdb_header);
1067                 header.rsn      -= 2;
1068                 header.flags   |= CTDB_REC_RO_HAVE_READONLY;
1069                 header.flags   &= ~CTDB_REC_RO_HAVE_DELEGATIONS;
1070                 memcpy(&r->data[0], &header, sizeof(struct ctdb_ltdb_header));
1071
1072                 if (data.dsize) {
1073                         memcpy(&r->data[sizeof(struct ctdb_ltdb_header)], data.dptr, data.dsize);
1074                 }
1075
1076                 ctdb_queue_packet(ctdb, &r->hdr);
1077                 CTDB_INCREMENT_STAT(ctdb, total_ro_delegations);
1078                 CTDB_INCREMENT_DB_STAT(ctdb_db, db_ro_delegations);
1079
1080                 talloc_free(r);
1081                 talloc_free(call);
1082                 return;
1083         }
1084
1085         CTDB_UPDATE_STAT(ctdb, max_hop_count, c->hopcount);
1086         tmp_count = c->hopcount;
1087         bucket = 0;
1088         while (tmp_count) {
1089                 tmp_count >>= 2;
1090                 bucket++;
1091         }
1092         if (bucket >= MAX_COUNT_BUCKETS) {
1093                 bucket = MAX_COUNT_BUCKETS - 1;
1094         }
1095         CTDB_INCREMENT_STAT(ctdb, hop_count_bucket[bucket]);
1096         CTDB_INCREMENT_DB_STAT(ctdb_db, hop_count_bucket[bucket]);
1097         ctdb_update_db_stat_hot_keys(ctdb_db, call->key, c->hopcount);
1098
1099         /* If this database supports sticky records, then check if the
1100            hopcount is big. If it is it means the record is hot and we
1101            should make it sticky.
1102         */
1103         if (ctdb_db->sticky && c->hopcount >= ctdb->tunable.hopcount_make_sticky) {
1104                 ctdb_make_record_sticky(ctdb, ctdb_db, call->key);
1105         }
1106
1107
1108         /* Try if possible to migrate the record off to the caller node.
1109          * From the clients perspective a fetch of the data is just as 
1110          * expensive as a migration.
1111          */
1112         if (c->hdr.srcnode != ctdb->pnn) {
1113                 if (ctdb_db->persistent_state) {
1114                         DEBUG(DEBUG_INFO, (__location__ " refusing migration"
1115                               " of key %s while transaction is active\n",
1116                               (char *)call->key.dptr));
1117                 } else {
1118                         DEBUG(DEBUG_DEBUG,("pnn %u starting migration of %08x to %u\n",
1119                                  ctdb->pnn, ctdb_hash(&(call->key)), c->hdr.srcnode));
1120                         ctdb_call_send_dmaster(ctdb_db, c, &header, &(call->key), &data);
1121                         talloc_free(data.dptr);
1122
1123                         ret = ctdb_ltdb_unlock(ctdb_db, call->key);
1124                         if (ret != 0) {
1125                                 DEBUG(DEBUG_ERR,(__location__ " ctdb_ltdb_unlock() failed with error %d\n", ret));
1126                         }
1127                 }
1128                 talloc_free(call);
1129                 return;
1130         }
1131
1132         ret = ctdb_call_local(ctdb_db, call, &header, hdr, &data, true);
1133         if (ret != 0) {
1134                 DEBUG(DEBUG_ERR,(__location__ " ctdb_call_local failed\n"));
1135                 call->status = -1;
1136         }
1137
1138         ret = ctdb_ltdb_unlock(ctdb_db, call->key);
1139         if (ret != 0) {
1140                 DEBUG(DEBUG_ERR,(__location__ " ctdb_ltdb_unlock() failed with error %d\n", ret));
1141         }
1142
1143         len = offsetof(struct ctdb_reply_call, data) + call->reply_data.dsize;
1144         r = ctdb_transport_allocate(ctdb, ctdb, CTDB_REPLY_CALL, len, 
1145                                     struct ctdb_reply_call);
1146         CTDB_NO_MEMORY_FATAL(ctdb, r);
1147         r->hdr.destnode  = hdr->srcnode;
1148         r->hdr.reqid     = hdr->reqid;
1149         r->hdr.generation = ctdb_db->generation;
1150         r->status        = call->status;
1151         r->datalen       = call->reply_data.dsize;
1152         if (call->reply_data.dsize) {
1153                 memcpy(&r->data[0], call->reply_data.dptr, call->reply_data.dsize);
1154         }
1155
1156         ctdb_queue_packet(ctdb, &r->hdr);
1157
1158         talloc_free(r);
1159         talloc_free(call);
1160 }
1161
1162 /**
1163  * called when a CTDB_REPLY_CALL packet comes in
1164  *
1165  * This packet comes in response to a CTDB_REQ_CALL request packet. It
1166  * contains any reply data from the call
1167  */
1168 void ctdb_reply_call(struct ctdb_context *ctdb, struct ctdb_req_header *hdr)
1169 {
1170         struct ctdb_reply_call *c = (struct ctdb_reply_call *)hdr;
1171         struct ctdb_call_state *state;
1172
1173         state = reqid_find(ctdb->idr, hdr->reqid, struct ctdb_call_state);
1174         if (state == NULL) {
1175                 DEBUG(DEBUG_ERR, (__location__ " reqid %u not found\n", hdr->reqid));
1176                 return;
1177         }
1178
1179         if (hdr->reqid != state->reqid) {
1180                 /* we found a record  but it was the wrong one */
1181                 DEBUG(DEBUG_ERR, ("Dropped orphaned call reply with reqid:%u\n",hdr->reqid));
1182                 return;
1183         }
1184
1185         if (hdr->generation != state->generation) {
1186                 DEBUG(DEBUG_DEBUG,
1187                       ("ctdb operation %u request %u from node %u to %u had an"
1188                        " invalid generation:%u while our generation is:%u\n",
1189                        hdr->operation, hdr->reqid, hdr->srcnode, hdr->destnode,
1190                        hdr->generation, state->generation));
1191                 return;
1192         }
1193
1194
1195         /* read only delegation processing */
1196         /* If we got a FETCH_WITH_HEADER we should check if this is a ro
1197          * delegation since we may need to update the record header
1198          */
1199         if (state->c->callid == CTDB_FETCH_WITH_HEADER_FUNC) {
1200                 struct ctdb_db_context *ctdb_db = state->ctdb_db;
1201                 struct ctdb_ltdb_header *header = (struct ctdb_ltdb_header *)&c->data[0];
1202                 struct ctdb_ltdb_header oldheader;
1203                 TDB_DATA key, data, olddata;
1204                 int ret;
1205
1206                 if (!(header->flags & CTDB_REC_RO_HAVE_READONLY)) {
1207                         goto finished_ro;
1208                         return;
1209                 }
1210
1211                 key.dsize = state->c->keylen;
1212                 key.dptr  = state->c->data;
1213                 ret = ctdb_ltdb_lock_requeue(ctdb_db, key, hdr,
1214                                      ctdb_call_input_pkt, ctdb, false);
1215                 if (ret == -2) {
1216                         return;
1217                 }
1218                 if (ret != 0) {
1219                         DEBUG(DEBUG_ERR,(__location__ " Failed to get lock in ctdb_reply_call\n"));
1220                         return;
1221                 }
1222
1223                 ret = ctdb_ltdb_fetch(ctdb_db, key, &oldheader, state, &olddata);
1224                 if (ret != 0) {
1225                         DEBUG(DEBUG_ERR, ("Failed to fetch old record in ctdb_reply_call\n"));
1226                         ctdb_ltdb_unlock(ctdb_db, key);
1227                         goto finished_ro;
1228                 }                       
1229
1230                 if (header->rsn <= oldheader.rsn) {
1231                         ctdb_ltdb_unlock(ctdb_db, key);
1232                         goto finished_ro;
1233                 }
1234
1235                 if (c->datalen < sizeof(struct ctdb_ltdb_header)) {
1236                         DEBUG(DEBUG_ERR,(__location__ " Got FETCH_WITH_HEADER reply with too little data: %d bytes\n", c->datalen));
1237                         ctdb_ltdb_unlock(ctdb_db, key);
1238                         goto finished_ro;
1239                 }
1240
1241                 data.dsize = c->datalen - sizeof(struct ctdb_ltdb_header);
1242                 data.dptr  = &c->data[sizeof(struct ctdb_ltdb_header)];
1243                 ret = ctdb_ltdb_store(ctdb_db, key, header, data);
1244                 if (ret != 0) {
1245                         DEBUG(DEBUG_ERR, ("Failed to store new record in ctdb_reply_call\n"));
1246                         ctdb_ltdb_unlock(ctdb_db, key);
1247                         goto finished_ro;
1248                 }                       
1249
1250                 ctdb_ltdb_unlock(ctdb_db, key);
1251         }
1252 finished_ro:
1253
1254         state->call->reply_data.dptr = c->data;
1255         state->call->reply_data.dsize = c->datalen;
1256         state->call->status = c->status;
1257
1258         talloc_steal(state, c);
1259
1260         state->state = CTDB_CALL_DONE;
1261         if (state->async.fn) {
1262                 state->async.fn(state);
1263         }
1264 }
1265
1266
1267 /**
1268  * called when a CTDB_REPLY_DMASTER packet comes in
1269  *
1270  * This packet comes in from the lmaster in response to a CTDB_REQ_CALL
1271  * request packet. It means that the current dmaster wants to give us
1272  * the dmaster role.
1273  */
1274 void ctdb_reply_dmaster(struct ctdb_context *ctdb, struct ctdb_req_header *hdr)
1275 {
1276         struct ctdb_reply_dmaster *c = (struct ctdb_reply_dmaster *)hdr;
1277         struct ctdb_db_context *ctdb_db;
1278         TDB_DATA key, data;
1279         uint32_t record_flags = 0;
1280         size_t len;
1281         int ret;
1282
1283         ctdb_db = find_ctdb_db(ctdb, c->db_id);
1284         if (ctdb_db == NULL) {
1285                 DEBUG(DEBUG_ERR,("Unknown db_id 0x%x in ctdb_reply_dmaster\n", c->db_id));
1286                 return;
1287         }
1288
1289         if (hdr->generation != ctdb_db->generation) {
1290                 DEBUG(DEBUG_DEBUG,
1291                       ("ctdb operation %u request %u from node %u to %u had an"
1292                        " invalid generation:%u while our generation is:%u\n",
1293                        hdr->operation, hdr->reqid, hdr->srcnode, hdr->destnode,
1294                        hdr->generation, ctdb_db->generation));
1295                 return;
1296         }
1297
1298         key.dptr = c->data;
1299         key.dsize = c->keylen;
1300         data.dptr = &c->data[key.dsize];
1301         data.dsize = c->datalen;
1302         len = offsetof(struct ctdb_reply_dmaster, data) + key.dsize + data.dsize
1303                 + sizeof(uint32_t);
1304         if (len <= c->hdr.length) {
1305                 memcpy(&record_flags, &c->data[c->keylen + c->datalen],
1306                        sizeof(record_flags));
1307         }
1308
1309         dmaster_defer_setup(ctdb_db, hdr, key);
1310
1311         ret = ctdb_ltdb_lock_requeue(ctdb_db, key, hdr,
1312                                      ctdb_call_input_pkt, ctdb, false);
1313         if (ret == -2) {
1314                 return;
1315         }
1316         if (ret != 0) {
1317                 DEBUG(DEBUG_ERR,(__location__ " Failed to get lock in ctdb_reply_dmaster\n"));
1318                 return;
1319         }
1320
1321         ctdb_become_dmaster(ctdb_db, hdr, key, data, c->rsn, record_flags);
1322 }
1323
1324
1325 /*
1326   called when a CTDB_REPLY_ERROR packet comes in
1327 */
1328 void ctdb_reply_error(struct ctdb_context *ctdb, struct ctdb_req_header *hdr)
1329 {
1330         struct ctdb_reply_error *c = (struct ctdb_reply_error *)hdr;
1331         struct ctdb_call_state *state;
1332
1333         state = reqid_find(ctdb->idr, hdr->reqid, struct ctdb_call_state);
1334         if (state == NULL) {
1335                 DEBUG(DEBUG_ERR,("pnn %u Invalid reqid %u in ctdb_reply_error\n",
1336                          ctdb->pnn, hdr->reqid));
1337                 return;
1338         }
1339
1340         if (hdr->reqid != state->reqid) {
1341                 /* we found a record  but it was the wrong one */
1342                 DEBUG(DEBUG_ERR, ("Dropped orphaned error reply with reqid:%u\n",hdr->reqid));
1343                 return;
1344         }
1345
1346         talloc_steal(state, c);
1347
1348         state->state  = CTDB_CALL_ERROR;
1349         state->errmsg = (char *)c->msg;
1350         if (state->async.fn) {
1351                 state->async.fn(state);
1352         }
1353 }
1354
1355
1356 /*
1357   destroy a ctdb_call
1358 */
1359 static int ctdb_call_destructor(struct ctdb_call_state *state)
1360 {
1361         DLIST_REMOVE(state->ctdb_db->pending_calls, state);
1362         reqid_remove(state->ctdb_db->ctdb->idr, state->reqid);
1363         return 0;
1364 }
1365
1366
1367 /*
1368   called when a ctdb_call needs to be resent after a reconfigure event
1369 */
1370 static void ctdb_call_resend(struct ctdb_call_state *state)
1371 {
1372         struct ctdb_context *ctdb = state->ctdb_db->ctdb;
1373
1374         state->generation = state->ctdb_db->generation;
1375
1376         /* use a new reqid, in case the old reply does eventually come in */
1377         reqid_remove(ctdb->idr, state->reqid);
1378         state->reqid = reqid_new(ctdb->idr, state);
1379         state->c->hdr.reqid = state->reqid;
1380
1381         /* update the generation count for this request, so its valid with the new vnn_map */
1382         state->c->hdr.generation = state->generation;
1383
1384         /* send the packet to ourselves, it will be redirected appropriately */
1385         state->c->hdr.destnode = ctdb->pnn;
1386
1387         ctdb_queue_packet(ctdb, &state->c->hdr);
1388         DEBUG(DEBUG_NOTICE,("resent ctdb_call for db %s reqid %u generation %u\n",
1389                             state->ctdb_db->db_name, state->reqid, state->generation));
1390 }
1391
1392 /*
1393   resend all pending calls on recovery
1394  */
1395 void ctdb_call_resend_db(struct ctdb_db_context *ctdb_db)
1396 {
1397         struct ctdb_call_state *state, *next;
1398
1399         for (state = ctdb_db->pending_calls; state; state = next) {
1400                 next = state->next;
1401                 ctdb_call_resend(state);
1402         }
1403 }
1404
1405 void ctdb_call_resend_all(struct ctdb_context *ctdb)
1406 {
1407         struct ctdb_db_context *ctdb_db;
1408
1409         for (ctdb_db = ctdb->db_list; ctdb_db; ctdb_db = ctdb_db->next) {
1410                 ctdb_call_resend_db(ctdb_db);
1411         }
1412 }
1413
1414 /*
1415   this allows the caller to setup a async.fn 
1416 */
1417 static void call_local_trigger(struct tevent_context *ev,
1418                                struct tevent_timer *te,
1419                                struct timeval t, void *private_data)
1420 {
1421         struct ctdb_call_state *state = talloc_get_type(private_data, struct ctdb_call_state);
1422         if (state->async.fn) {
1423                 state->async.fn(state);
1424         }
1425 }       
1426
1427
1428 /*
1429   construct an event driven local ctdb_call
1430
1431   this is used so that locally processed ctdb_call requests are processed
1432   in an event driven manner
1433 */
1434 struct ctdb_call_state *ctdb_call_local_send(struct ctdb_db_context *ctdb_db, 
1435                                              struct ctdb_call *call,
1436                                              struct ctdb_ltdb_header *header,
1437                                              TDB_DATA *data)
1438 {
1439         struct ctdb_call_state *state;
1440         struct ctdb_context *ctdb = ctdb_db->ctdb;
1441         int ret;
1442
1443         state = talloc_zero(ctdb_db, struct ctdb_call_state);
1444         CTDB_NO_MEMORY_NULL(ctdb, state);
1445
1446         talloc_steal(state, data->dptr);
1447
1448         state->state = CTDB_CALL_DONE;
1449         state->call  = talloc(state, struct ctdb_call);
1450         CTDB_NO_MEMORY_NULL(ctdb, state->call);
1451         *(state->call) = *call;
1452         state->ctdb_db = ctdb_db;
1453
1454         ret = ctdb_call_local(ctdb_db, state->call, header, state, data, true);
1455         if (ret != 0) {
1456                 DEBUG(DEBUG_DEBUG,("ctdb_call_local() failed, ignoring return code %d\n", ret));
1457         }
1458
1459         tevent_add_timer(ctdb->ev, state, timeval_zero(),
1460                          call_local_trigger, state);
1461
1462         return state;
1463 }
1464
1465
1466 /*
1467   make a remote ctdb call - async send. Called in daemon context.
1468
1469   This constructs a ctdb_call request and queues it for processing. 
1470   This call never blocks.
1471 */
1472 struct ctdb_call_state *ctdb_daemon_call_send_remote(struct ctdb_db_context *ctdb_db, 
1473                                                      struct ctdb_call *call, 
1474                                                      struct ctdb_ltdb_header *header)
1475 {
1476         uint32_t len;
1477         struct ctdb_call_state *state;
1478         struct ctdb_context *ctdb = ctdb_db->ctdb;
1479
1480         if (ctdb->methods == NULL) {
1481                 DEBUG(DEBUG_INFO,(__location__ " Failed send packet. Transport is down\n"));
1482                 return NULL;
1483         }
1484
1485         state = talloc_zero(ctdb_db, struct ctdb_call_state);
1486         CTDB_NO_MEMORY_NULL(ctdb, state);
1487         state->call = talloc(state, struct ctdb_call);
1488         CTDB_NO_MEMORY_NULL(ctdb, state->call);
1489
1490         state->reqid = reqid_new(ctdb->idr, state);
1491         state->ctdb_db = ctdb_db;
1492         talloc_set_destructor(state, ctdb_call_destructor);
1493
1494         len = offsetof(struct ctdb_req_call, data) + call->key.dsize + call->call_data.dsize;
1495         state->c = ctdb_transport_allocate(ctdb, state, CTDB_REQ_CALL, len, 
1496                                            struct ctdb_req_call);
1497         CTDB_NO_MEMORY_NULL(ctdb, state->c);
1498         state->c->hdr.destnode  = header->dmaster;
1499
1500         /* this limits us to 16k outstanding messages - not unreasonable */
1501         state->c->hdr.reqid     = state->reqid;
1502         state->c->hdr.generation = ctdb_db->generation;
1503         state->c->flags         = call->flags;
1504         state->c->db_id         = ctdb_db->db_id;
1505         state->c->callid        = call->call_id;
1506         state->c->hopcount      = 0;
1507         state->c->keylen        = call->key.dsize;
1508         state->c->calldatalen   = call->call_data.dsize;
1509         memcpy(&state->c->data[0], call->key.dptr, call->key.dsize);
1510         memcpy(&state->c->data[call->key.dsize], 
1511                call->call_data.dptr, call->call_data.dsize);
1512         *(state->call)              = *call;
1513         state->call->call_data.dptr = &state->c->data[call->key.dsize];
1514         state->call->key.dptr       = &state->c->data[0];
1515
1516         state->state  = CTDB_CALL_WAIT;
1517         state->generation = ctdb_db->generation;
1518
1519         DLIST_ADD(ctdb_db->pending_calls, state);
1520
1521         ctdb_queue_packet(ctdb, &state->c->hdr);
1522
1523         return state;
1524 }
1525
1526 /*
1527   make a remote ctdb call - async recv - called in daemon context
1528
1529   This is called when the program wants to wait for a ctdb_call to complete and get the 
1530   results. This call will block unless the call has already completed.
1531 */
1532 int ctdb_daemon_call_recv(struct ctdb_call_state *state, struct ctdb_call *call)
1533 {
1534         while (state->state < CTDB_CALL_DONE) {
1535                 tevent_loop_once(state->ctdb_db->ctdb->ev);
1536         }
1537         if (state->state != CTDB_CALL_DONE) {
1538                 ctdb_set_error(state->ctdb_db->ctdb, "%s", state->errmsg);
1539                 talloc_free(state);
1540                 return -1;
1541         }
1542
1543         if (state->call->reply_data.dsize) {
1544                 call->reply_data.dptr = talloc_memdup(call,
1545                                                       state->call->reply_data.dptr,
1546                                                       state->call->reply_data.dsize);
1547                 call->reply_data.dsize = state->call->reply_data.dsize;
1548         } else {
1549                 call->reply_data.dptr = NULL;
1550                 call->reply_data.dsize = 0;
1551         }
1552         call->status = state->call->status;
1553         talloc_free(state);
1554         return 0;
1555 }
1556
1557
1558 /* 
1559    send a keepalive packet to the other node
1560 */
1561 void ctdb_send_keepalive(struct ctdb_context *ctdb, uint32_t destnode)
1562 {
1563         struct ctdb_req_keepalive *r;
1564         
1565         if (ctdb->methods == NULL) {
1566                 DEBUG(DEBUG_INFO,(__location__ " Failed to send keepalive. Transport is DOWN\n"));
1567                 return;
1568         }
1569
1570         r = ctdb_transport_allocate(ctdb, ctdb, CTDB_REQ_KEEPALIVE,
1571                                     sizeof(struct ctdb_req_keepalive), 
1572                                     struct ctdb_req_keepalive);
1573         CTDB_NO_MEMORY_FATAL(ctdb, r);
1574         r->hdr.destnode  = destnode;
1575         r->hdr.reqid     = 0;
1576         
1577         CTDB_INCREMENT_STAT(ctdb, keepalive_packets_sent);
1578
1579         ctdb_queue_packet(ctdb, &r->hdr);
1580
1581         talloc_free(r);
1582 }
1583
1584
1585
1586 struct revokechild_deferred_call {
1587         struct ctdb_context *ctdb;
1588         struct ctdb_req_header *hdr;
1589         deferred_requeue_fn fn;
1590         void *ctx;
1591 };
1592
1593 struct revokechild_handle {
1594         struct revokechild_handle *next, *prev;
1595         struct ctdb_context *ctdb;
1596         struct ctdb_db_context *ctdb_db;
1597         struct tevent_fd *fde;
1598         int status;
1599         int fd[2];
1600         pid_t child;
1601         TDB_DATA key;
1602 };
1603
1604 struct revokechild_requeue_handle {
1605         struct ctdb_context *ctdb;
1606         struct ctdb_req_header *hdr;
1607         deferred_requeue_fn fn;
1608         void *ctx;
1609 };
1610
1611 static void deferred_call_requeue(struct tevent_context *ev,
1612                                   struct tevent_timer *te,
1613                                   struct timeval t, void *private_data)
1614 {
1615         struct revokechild_requeue_handle *requeue_handle = talloc_get_type(private_data, struct revokechild_requeue_handle);
1616
1617         requeue_handle->fn(requeue_handle->ctx, requeue_handle->hdr);
1618         talloc_free(requeue_handle);
1619 }
1620
1621 static int deferred_call_destructor(struct revokechild_deferred_call *deferred_call)
1622 {
1623         struct ctdb_context *ctdb = deferred_call->ctdb;
1624         struct revokechild_requeue_handle *requeue_handle = talloc(ctdb, struct revokechild_requeue_handle);
1625         struct ctdb_req_call *c = (struct ctdb_req_call *)deferred_call->hdr;
1626
1627         requeue_handle->ctdb = ctdb;
1628         requeue_handle->hdr  = deferred_call->hdr;
1629         requeue_handle->fn   = deferred_call->fn;
1630         requeue_handle->ctx  = deferred_call->ctx;
1631         talloc_steal(requeue_handle, requeue_handle->hdr);
1632
1633         /* when revoking, any READONLY requests have 1 second grace to let read/write finish first */
1634         tevent_add_timer(ctdb->ev, requeue_handle,
1635                          timeval_current_ofs(c->flags & CTDB_WANT_READONLY ? 1 : 0, 0),
1636                          deferred_call_requeue, requeue_handle);
1637
1638         return 0;
1639 }
1640
1641
1642 static int revokechild_destructor(struct revokechild_handle *rc)
1643 {
1644         if (rc->fde != NULL) {
1645                 talloc_free(rc->fde);
1646         }
1647
1648         if (rc->fd[0] != -1) {
1649                 close(rc->fd[0]);
1650         }
1651         if (rc->fd[1] != -1) {
1652                 close(rc->fd[1]);
1653         }
1654         ctdb_kill(rc->ctdb, rc->child, SIGKILL);
1655
1656         DLIST_REMOVE(rc->ctdb_db->revokechild_active, rc);
1657         return 0;
1658 }
1659
1660 static void revokechild_handler(struct tevent_context *ev,
1661                                 struct tevent_fd *fde,
1662                                 uint16_t flags, void *private_data)
1663 {
1664         struct revokechild_handle *rc = talloc_get_type(private_data, 
1665                                                      struct revokechild_handle);
1666         int ret;
1667         char c;
1668
1669         ret = sys_read(rc->fd[0], &c, 1);
1670         if (ret != 1) {
1671                 DEBUG(DEBUG_ERR,("Failed to read status from revokechild. errno:%d\n", errno));
1672                 rc->status = -1;
1673                 talloc_free(rc);
1674                 return;
1675         }
1676         if (c != 0) {
1677                 DEBUG(DEBUG_ERR,("revokechild returned failure. status:%d\n", c));
1678                 rc->status = -1;
1679                 talloc_free(rc);
1680                 return;
1681         }
1682
1683         talloc_free(rc);
1684 }
1685
1686 struct ctdb_revoke_state {
1687         struct ctdb_db_context *ctdb_db;
1688         TDB_DATA key;
1689         struct ctdb_ltdb_header *header;
1690         TDB_DATA data;
1691         int count;
1692         int status;
1693         int finished;
1694 };
1695
1696 static void update_record_cb(struct ctdb_client_control_state *state)
1697 {
1698         struct ctdb_revoke_state *revoke_state;
1699         int ret;
1700         int32_t res;
1701
1702         if (state == NULL) {
1703                 return;
1704         }
1705         revoke_state = state->async.private_data;
1706
1707         state->async.fn = NULL;
1708         ret = ctdb_control_recv(state->ctdb, state, state, NULL, &res, NULL);
1709         if ((ret != 0) || (res != 0)) {
1710                 DEBUG(DEBUG_ERR,("Recv for revoke update record failed ret:%d res:%d\n", ret, res));
1711                 revoke_state->status = -1;
1712         }
1713
1714         revoke_state->count--;
1715         if (revoke_state->count <= 0) {
1716                 revoke_state->finished = 1;
1717         }
1718 }
1719
1720 static void revoke_send_cb(struct ctdb_context *ctdb, uint32_t pnn, void *private_data)
1721 {
1722         struct ctdb_revoke_state *revoke_state = private_data;
1723         struct ctdb_client_control_state *state;
1724
1725         state = ctdb_ctrl_updaterecord_send(ctdb, revoke_state, timeval_current_ofs(ctdb->tunable.control_timeout,0), pnn, revoke_state->ctdb_db, revoke_state->key, revoke_state->header, revoke_state->data);
1726         if (state == NULL) {
1727                 DEBUG(DEBUG_ERR,("Failure to send update record to revoke readonly delegation\n"));
1728                 revoke_state->status = -1;
1729                 return;
1730         }
1731         state->async.fn           = update_record_cb;
1732         state->async.private_data = revoke_state;
1733
1734         revoke_state->count++;
1735
1736 }
1737
1738 static void ctdb_revoke_timeout_handler(struct tevent_context *ev,
1739                                         struct tevent_timer *te,
1740                                         struct timeval yt, void *private_data)
1741 {
1742         struct ctdb_revoke_state *state = private_data;
1743
1744         DEBUG(DEBUG_ERR,("Timed out waiting for revoke to finish\n"));
1745         state->finished = 1;
1746         state->status   = -1;
1747 }
1748
1749 static int ctdb_revoke_all_delegations(struct ctdb_context *ctdb, struct ctdb_db_context *ctdb_db, TDB_DATA tdata, TDB_DATA key, struct ctdb_ltdb_header *header, TDB_DATA data)
1750 {
1751         struct ctdb_revoke_state *state = talloc_zero(ctdb, struct ctdb_revoke_state);
1752         struct ctdb_ltdb_header new_header;
1753         TDB_DATA new_data;
1754
1755         state->ctdb_db = ctdb_db;
1756         state->key     = key;
1757         state->header  = header;
1758         state->data    = data;
1759  
1760         ctdb_trackingdb_traverse(ctdb, tdata, revoke_send_cb, state);
1761
1762         tevent_add_timer(ctdb->ev, state,
1763                          timeval_current_ofs(ctdb->tunable.control_timeout, 0),
1764                          ctdb_revoke_timeout_handler, state);
1765
1766         while (state->finished == 0) {
1767                 tevent_loop_once(ctdb->ev);
1768         }
1769
1770         if (ctdb_ltdb_lock(ctdb_db, key) != 0) {
1771                 DEBUG(DEBUG_ERR,("Failed to chainlock the database in revokechild\n"));
1772                 talloc_free(state);
1773                 return -1;
1774         }
1775         if (ctdb_ltdb_fetch(ctdb_db, key, &new_header, state, &new_data) != 0) {
1776                 ctdb_ltdb_unlock(ctdb_db, key);
1777                 DEBUG(DEBUG_ERR,("Failed for fetch tdb record in revokechild\n"));
1778                 talloc_free(state);
1779                 return -1;
1780         }
1781         header->rsn++;
1782         if (new_header.rsn > header->rsn) {
1783                 ctdb_ltdb_unlock(ctdb_db, key);
1784                 DEBUG(DEBUG_ERR,("RSN too high in tdb record in revokechild\n"));
1785                 talloc_free(state);
1786                 return -1;
1787         }
1788         if ( (new_header.flags & (CTDB_REC_RO_REVOKING_READONLY|CTDB_REC_RO_HAVE_DELEGATIONS)) != (CTDB_REC_RO_REVOKING_READONLY|CTDB_REC_RO_HAVE_DELEGATIONS) ) {
1789                 ctdb_ltdb_unlock(ctdb_db, key);
1790                 DEBUG(DEBUG_ERR,("Flags are wrong in tdb record in revokechild\n"));
1791                 talloc_free(state);
1792                 return -1;
1793         }
1794
1795         /*
1796          * If revoke on all nodes succeed, revoke is complete.  Otherwise,
1797          * remove CTDB_REC_RO_REVOKING_READONLY flag and retry.
1798          */
1799         if (state->status == 0) {
1800                 new_header.rsn++;
1801                 new_header.flags |= CTDB_REC_RO_REVOKE_COMPLETE;
1802         } else {
1803                 DEBUG(DEBUG_NOTICE, ("Revoke all delegations failed, retrying.\n"));
1804                 new_header.flags &= ~CTDB_REC_RO_REVOKING_READONLY;
1805         }
1806         if (ctdb_ltdb_store(ctdb_db, key, &new_header, new_data) != 0) {
1807                 ctdb_ltdb_unlock(ctdb_db, key);
1808                 DEBUG(DEBUG_ERR,("Failed to write new record in revokechild\n"));
1809                 talloc_free(state);
1810                 return -1;
1811         }
1812         ctdb_ltdb_unlock(ctdb_db, key);
1813
1814         talloc_free(state);
1815         return 0;
1816 }
1817
1818
1819 int ctdb_start_revoke_ro_record(struct ctdb_context *ctdb, struct ctdb_db_context *ctdb_db, TDB_DATA key, struct ctdb_ltdb_header *header, TDB_DATA data)
1820 {
1821         TDB_DATA tdata;
1822         struct revokechild_handle *rc;
1823         pid_t parent = getpid();
1824         int ret;
1825
1826         header->flags &= ~(CTDB_REC_RO_REVOKING_READONLY|CTDB_REC_RO_HAVE_DELEGATIONS|CTDB_REC_RO_HAVE_READONLY);
1827         header->flags |= CTDB_REC_FLAG_MIGRATED_WITH_DATA;
1828         header->rsn   -= 1;
1829
1830         if ((rc = talloc_zero(ctdb_db, struct revokechild_handle)) == NULL) {
1831                 DEBUG(DEBUG_ERR,("Failed to allocate revokechild_handle\n"));
1832                 return -1;
1833         }
1834
1835         tdata = tdb_fetch(ctdb_db->rottdb, key);
1836         if (tdata.dsize > 0) {
1837                 uint8_t *tmp;
1838
1839                 tmp = tdata.dptr;
1840                 tdata.dptr = talloc_memdup(rc, tdata.dptr, tdata.dsize);
1841                 free(tmp);
1842         }
1843
1844         rc->status    = 0;
1845         rc->ctdb      = ctdb;
1846         rc->ctdb_db   = ctdb_db;
1847         rc->fd[0]     = -1;
1848         rc->fd[1]     = -1;
1849
1850         talloc_set_destructor(rc, revokechild_destructor);
1851
1852         rc->key.dsize = key.dsize;
1853         rc->key.dptr  = talloc_memdup(rc, key.dptr, key.dsize);
1854         if (rc->key.dptr == NULL) {
1855                 DEBUG(DEBUG_ERR,("Failed to allocate key for revokechild_handle\n"));
1856                 talloc_free(rc);
1857                 return -1;
1858         }
1859
1860         ret = pipe(rc->fd);
1861         if (ret != 0) {
1862                 DEBUG(DEBUG_ERR,("Failed to allocate key for revokechild_handle\n"));
1863                 talloc_free(rc);
1864                 return -1;
1865         }
1866
1867
1868         rc->child = ctdb_fork(ctdb);
1869         if (rc->child == (pid_t)-1) {
1870                 DEBUG(DEBUG_ERR,("Failed to fork child for revokechild\n"));
1871                 talloc_free(rc);
1872                 return -1;
1873         }
1874
1875         if (rc->child == 0) {
1876                 char c = 0;
1877                 close(rc->fd[0]);
1878                 debug_extra = talloc_asprintf(NULL, "revokechild-%s:", ctdb_db->db_name);
1879
1880                 ctdb_set_process_name("ctdb_revokechild");
1881                 if (switch_from_server_to_client(ctdb, "revokechild-%s", ctdb_db->db_name) != 0) {
1882                         DEBUG(DEBUG_ERR,("Failed to switch from server to client for revokechild process\n"));
1883                         c = 1;
1884                         goto child_finished;
1885                 }
1886
1887                 c = ctdb_revoke_all_delegations(ctdb, ctdb_db, tdata, key, header, data);
1888
1889 child_finished:
1890                 sys_write(rc->fd[1], &c, 1);
1891                 /* make sure we die when our parent dies */
1892                 while (ctdb_kill(ctdb, parent, 0) == 0 || errno != ESRCH) {
1893                         sleep(5);
1894                 }
1895                 _exit(0);
1896         }
1897
1898         close(rc->fd[1]);
1899         rc->fd[1] = -1;
1900         set_close_on_exec(rc->fd[0]);
1901
1902         /* This is an active revokechild child process */
1903         DLIST_ADD_END(ctdb_db->revokechild_active, rc, NULL);
1904
1905         rc->fde = tevent_add_fd(ctdb->ev, rc, rc->fd[0], TEVENT_FD_READ,
1906                                 revokechild_handler, (void *)rc);
1907         if (rc->fde == NULL) {
1908                 DEBUG(DEBUG_ERR,("Failed to set up fd event for revokechild process\n"));
1909                 talloc_free(rc);
1910         }
1911         tevent_fd_set_auto_close(rc->fde);
1912
1913         return 0;
1914 }
1915
1916 int ctdb_add_revoke_deferred_call(struct ctdb_context *ctdb, struct ctdb_db_context *ctdb_db, TDB_DATA key, struct ctdb_req_header *hdr, deferred_requeue_fn fn, void *call_context)
1917 {
1918         struct revokechild_handle *rc;
1919         struct revokechild_deferred_call *deferred_call;
1920
1921         for (rc = ctdb_db->revokechild_active; rc; rc = rc->next) {
1922                 if (rc->key.dsize == 0) {
1923                         continue;
1924                 }
1925                 if (rc->key.dsize != key.dsize) {
1926                         continue;
1927                 }
1928                 if (!memcmp(rc->key.dptr, key.dptr, key.dsize)) {
1929                         break;
1930                 }
1931         }
1932
1933         if (rc == NULL) {
1934                 DEBUG(DEBUG_ERR,("Failed to add deferred call to revoke list. revoke structure not found\n"));
1935                 return -1;
1936         }
1937
1938         deferred_call = talloc(rc, struct revokechild_deferred_call);
1939         if (deferred_call == NULL) {
1940                 DEBUG(DEBUG_ERR,("Failed to allocate deferred call structure for revoking record\n"));
1941                 return -1;
1942         }
1943
1944         deferred_call->ctdb = ctdb;
1945         deferred_call->hdr  = hdr;
1946         deferred_call->fn   = fn;
1947         deferred_call->ctx  = call_context;
1948
1949         talloc_set_destructor(deferred_call, deferred_call_destructor);
1950         talloc_steal(deferred_call, hdr);
1951
1952         return 0;
1953 }