vacuum: factor out the fast vacuuming run into ctdb_vacuum_db_fast()
[garming/samba-autobuild/.git] / ctdb / server / ctdb_vacuum.c
1 /*
2    ctdb vacuuming events
3
4    Copyright (C) Ronnie Sahlberg  2009
5    Copyright (C) Michael Adam 2010-2011
6    Copyright (C) Stefan Metzmacher 2010-2011
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program; if not, see <http://www.gnu.org/licenses/>.
20 */
21
22 #include "includes.h"
23 #include "lib/tevent/tevent.h"
24 #include "lib/tdb/include/tdb.h"
25 #include "system/network.h"
26 #include "system/filesys.h"
27 #include "system/dir.h"
28 #include "../include/ctdb_private.h"
29 #include "db_wrap.h"
30 #include "lib/util/dlinklist.h"
31 #include "lib/tevent/tevent.h"
32 #include "../include/ctdb_private.h"
33 #include "../common/rb_tree.h"
34
35 #define TIMELIMIT() timeval_current_ofs(10, 0)
36
37 enum vacuum_child_status { VACUUM_RUNNING, VACUUM_OK, VACUUM_ERROR, VACUUM_TIMEOUT};
38
39 struct ctdb_vacuum_child_context {
40         struct ctdb_vacuum_child_context *next, *prev;
41         struct ctdb_vacuum_handle *vacuum_handle;
42         /* fd child writes status to */
43         int fd[2];
44         pid_t child_pid;
45         enum vacuum_child_status status;
46         struct timeval start_time;
47 };
48
49 struct ctdb_vacuum_handle {
50         struct ctdb_db_context *ctdb_db;
51         struct ctdb_vacuum_child_context *child_ctx;
52         uint32_t fast_path_count;
53 };
54
55
56 /*  a list of records to possibly delete */
57 struct vacuum_data {
58         uint32_t vacuum_limit;
59         uint32_t repack_limit;
60         struct ctdb_context *ctdb;
61         struct ctdb_db_context *ctdb_db;
62         struct tdb_context *dest_db;
63         trbt_tree_t *delete_list;
64         uint32_t delete_count;
65         struct ctdb_marshall_buffer **vacuum_fetch_list;
66         struct timeval start;
67         bool traverse_error;
68         bool vacuum;
69         uint32_t total;
70         uint32_t vacuumed;
71         uint32_t copied;
72         uint32_t fast_added_to_vacuum_fetch_list;
73         uint32_t fast_added_to_delete_list;
74         uint32_t fast_deleted;
75         uint32_t fast_skipped;
76         uint32_t fast_error;
77         uint32_t fast_total;
78         uint32_t full_added_to_vacuum_fetch_list;
79         uint32_t full_added_to_delete_list;
80         uint32_t full_skipped;
81         uint32_t full_error;
82         uint32_t full_total;
83         uint32_t delete_left;
84         uint32_t delete_remote_error;
85         uint32_t delete_local_error;
86         uint32_t delete_deleted;
87         uint32_t delete_skipped;
88 };
89
90 /* this structure contains the information for one record to be deleted */
91 struct delete_record_data {
92         struct ctdb_context *ctdb;
93         struct ctdb_db_context *ctdb_db;
94         struct ctdb_ltdb_header hdr;
95         TDB_DATA key;
96 };
97
98 struct delete_records_list {
99         struct ctdb_marshall_buffer *records;
100 };
101
102 /**
103  * Store key and header in a tree, indexed by the key hash.
104  */
105 static int insert_delete_record_data_into_tree(struct ctdb_context *ctdb,
106                                                struct ctdb_db_context *ctdb_db,
107                                                trbt_tree_t *tree,
108                                                const struct ctdb_ltdb_header *hdr,
109                                                TDB_DATA key)
110 {
111         struct delete_record_data *dd;
112         uint32_t hash;
113
114         dd = talloc_zero(tree, struct delete_record_data);
115         if (dd == NULL) {
116                 DEBUG(DEBUG_ERR,(__location__ " Out of memory\n"));
117                 return -1;
118         }
119
120         dd->ctdb      = ctdb;
121         dd->ctdb_db   = ctdb_db;
122         dd->key.dsize = key.dsize;
123         dd->key.dptr  = talloc_memdup(dd, key.dptr, key.dsize);
124         if (dd->key.dptr == NULL) {
125                 DEBUG(DEBUG_ERR,(__location__ " Out of memory\n"));
126                 return -1;
127         }
128
129         dd->hdr = *hdr;
130
131         hash = ctdb_hash(&key);
132
133         trbt_insert32(tree, hash, dd);
134
135         return 0;
136 }
137
138 static int add_record_to_delete_list(struct vacuum_data *vdata, TDB_DATA key,
139                                      struct ctdb_ltdb_header *hdr)
140 {
141         struct ctdb_context *ctdb = vdata->ctdb;
142         struct ctdb_db_context *ctdb_db = vdata->ctdb_db;
143         uint32_t hash;
144         int ret;
145
146         hash = ctdb_hash(&key);
147
148         if (trbt_lookup32(vdata->delete_list, hash)) {
149                 DEBUG(DEBUG_INFO, (__location__ " Hash collission when vacuuming, skipping this record.\n"));
150                 return 0;
151         }
152
153         ret = insert_delete_record_data_into_tree(ctdb, ctdb_db,
154                                                   vdata->delete_list,
155                                                   hdr, key);
156         if (ret != 0) {
157                 return -1;
158         }
159
160         vdata->delete_count++;
161
162         return 0;
163 }
164
165 /**
166  * Add a record to the list of records to be sent
167  * to their lmaster with VACUUM_FETCH.
168  */
169 static int add_record_to_vacuum_fetch_list(struct vacuum_data *vdata,
170                                            TDB_DATA key)
171 {
172         struct ctdb_context *ctdb = vdata->ctdb;
173         struct ctdb_rec_data *rec;
174         uint32_t lmaster;
175         size_t old_size;
176         struct ctdb_marshall_buffer *vfl;
177
178         lmaster = ctdb_lmaster(ctdb, &key);
179
180         vfl = vdata->vacuum_fetch_list[lmaster];
181
182         rec = ctdb_marshall_record(vfl, ctdb->pnn, key, NULL, tdb_null);
183         if (rec == NULL) {
184                 DEBUG(DEBUG_ERR,(__location__ " Out of memory\n"));
185                 vdata->traverse_error = true;
186                 return -1;
187         }
188
189         old_size = talloc_get_size(vfl);
190         vfl = talloc_realloc_size(NULL, vfl, old_size + rec->length);
191         if (vfl == NULL) {
192                 DEBUG(DEBUG_ERR,(__location__ " Failed to expand\n"));
193                 vdata->traverse_error = true;
194                 return -1;
195         }
196         vdata->vacuum_fetch_list[lmaster] = vfl;
197
198         vfl->count++;
199         memcpy(old_size+(uint8_t *)vfl, rec, rec->length);
200         talloc_free(rec);
201
202         vdata->total++;
203
204         return 0;
205 }
206
207
208 static void ctdb_vacuum_event(struct event_context *ev, struct timed_event *te,
209                               struct timeval t, void *private_data);
210
211
212 /*
213  * traverse function for gathering the records that can be deleted
214  */
215 static int vacuum_traverse(struct tdb_context *tdb, TDB_DATA key, TDB_DATA data, void *private)
216 {
217         struct vacuum_data *vdata = talloc_get_type(private, struct vacuum_data);
218         struct ctdb_context *ctdb = vdata->ctdb;
219         uint32_t lmaster;
220         struct ctdb_ltdb_header *hdr;
221         int res = 0;
222
223         vdata->full_total++;
224
225         lmaster = ctdb_lmaster(ctdb, &key);
226         if (lmaster >= ctdb->num_nodes) {
227                 vdata->full_error++;
228                 DEBUG(DEBUG_CRIT, (__location__
229                                    " lmaster[%u] >= ctdb->num_nodes[%u] for key"
230                                    " with hash[%u]!\n",
231                                    (unsigned)lmaster,
232                                    (unsigned)ctdb->num_nodes,
233                                    (unsigned)ctdb_hash(&key)));
234                 return -1;
235         }
236
237         if (data.dsize != sizeof(struct ctdb_ltdb_header)) {
238                 /* it is not a deleted record */
239                 vdata->full_skipped++;
240                 return 0;
241         }
242
243         hdr = (struct ctdb_ltdb_header *)data.dptr;
244
245         if (hdr->dmaster != ctdb->pnn) {
246                 vdata->full_skipped++;
247                 return 0;
248         }
249
250         if (lmaster == ctdb->pnn) {
251                 /*
252                  * We are both lmaster and dmaster, and the record is empty.
253                  * So we should be able to delete it.
254                  */
255                 res = add_record_to_delete_list(vdata, key, hdr);
256                 if (res != 0) {
257                         vdata->full_error++;
258                 } else {
259                         vdata->full_added_to_delete_list++;
260                 }
261         } else {
262                 /*
263                  * We are not lmaster.
264                  * Add the record to the blob ready to send to the nodes.
265                  */
266                 res = add_record_to_vacuum_fetch_list(vdata, key);
267                 if (res != 0) {
268                         vdata->full_error++;
269                 } else {
270                         vdata->full_added_to_vacuum_fetch_list++;
271                 }
272         }
273
274         return res;
275 }
276
277 /*
278  * traverse the tree of records to delete and marshall them into
279  * a blob
280  */
281 static int delete_marshall_traverse(void *param, void *data)
282 {
283         struct delete_record_data *dd = talloc_get_type(data, struct delete_record_data);
284         struct delete_records_list *recs = talloc_get_type(param, struct delete_records_list);
285         struct ctdb_rec_data *rec;
286         size_t old_size;
287
288         rec = ctdb_marshall_record(dd, recs->records->db_id, dd->key, &dd->hdr, tdb_null);
289         if (rec == NULL) {
290                 DEBUG(DEBUG_ERR, (__location__ " failed to marshall record\n"));
291                 return 0;
292         }
293
294         old_size = talloc_get_size(recs->records);
295         recs->records = talloc_realloc_size(NULL, recs->records, old_size + rec->length);
296         if (recs->records == NULL) {
297                 DEBUG(DEBUG_ERR,(__location__ " Failed to expand\n"));
298                 return 0;
299         }
300         recs->records->count++;
301         memcpy(old_size+(uint8_t *)(recs->records), rec, rec->length);
302         return 0;
303 }
304
305 /**
306  * traverse function for the traversal of the delete_queue,
307  * the fast-path vacuuming list.
308  *
309  *  - If the record has been migrated off the node
310  *    or has been revived (filled with data) on the node,
311  *    then skip the record.
312  *
313  *  - If the current node is the record's lmaster and it is
314  *    a record that has never been migrated with data, then
315  *    delete the record from the local tdb.
316  *
317  *  - If the current node is the record's lmaster and it has
318  *    been migrated with data, then schedule it for the normal
319  *    vacuuming procedure (i.e. add it to the delete_list).
320  *
321  *  - If the current node is NOT the record's lmaster then
322  *    add it to the list of records that are to be sent to
323  *    the lmaster with the VACUUM_FETCH message.
324  */
325 static int delete_queue_traverse(void *param, void *data)
326 {
327         struct delete_record_data *dd =
328                 talloc_get_type(data, struct delete_record_data);
329         struct vacuum_data *vdata = talloc_get_type(param, struct vacuum_data);
330         struct ctdb_db_context *ctdb_db = dd->ctdb_db;
331         struct ctdb_context *ctdb = ctdb_db->ctdb; /* or dd->ctdb ??? */
332         int res;
333         struct ctdb_ltdb_header *header;
334         TDB_DATA tdb_data;
335         uint32_t lmaster;
336
337         vdata->fast_total++;
338
339         res = tdb_chainlock(ctdb_db->ltdb->tdb, dd->key);
340         if (res != 0) {
341                 DEBUG(DEBUG_ERR, (__location__ " Error getting chainlock.\n"));
342                 vdata->fast_error++;
343                 return 0;
344         }
345
346         tdb_data = tdb_fetch(ctdb_db->ltdb->tdb, dd->key);
347         if (tdb_data.dsize < sizeof(struct ctdb_ltdb_header)) {
348                 /* Does not exist or not a ctdb record. Skip. */
349                 goto skipped;
350         }
351
352         if (tdb_data.dsize > sizeof(struct ctdb_ltdb_header)) {
353                 /* The record has been recycled (filled with data). Skip. */
354                 goto skipped;
355         }
356
357         header = (struct ctdb_ltdb_header *)tdb_data.dptr;
358
359         if (header->dmaster != ctdb->pnn) {
360                 /* The record has been migrated off the node. Skip. */
361                 goto skipped;
362         }
363
364
365         if (header->rsn != dd->hdr.rsn) {
366                 /*
367                  * The record has been migrated off the node and back again.
368                  * But not requeued for deletion. Skip it.
369                  */
370                 goto skipped;
371         }
372
373         /*
374          * We are dmaster, and the record has no data, and it has
375          * not been migrated after it has been queued for deletion.
376          *
377          * At this stage, the record could still have been revived locally
378          * and last been written with empty data. This can only be
379          * fixed with the addition of an active or delete flag. (TODO)
380          */
381
382         lmaster = ctdb_lmaster(ctdb_db->ctdb, &dd->key);
383
384         if (lmaster != ctdb->pnn) {
385                 res = add_record_to_vacuum_fetch_list(vdata, dd->key);
386
387                 if (res != 0) {
388                         DEBUG(DEBUG_ERR,
389                               (__location__ " Error adding record to list "
390                                "of records to send to lmaster.\n"));
391                         vdata->fast_error++;
392                 } else {
393                         vdata->fast_added_to_vacuum_fetch_list++;
394                 }
395                 goto done;
396         }
397
398         /* use header->flags or dd->hdr.flags ?? */
399         if (dd->hdr.flags & CTDB_REC_FLAG_MIGRATED_WITH_DATA) {
400                 res = add_record_to_delete_list(vdata, dd->key, &dd->hdr);
401
402                 if (res != 0) {
403                         DEBUG(DEBUG_ERR,
404                               (__location__ " Error adding record to list "
405                                "of records for deletion on lmaster.\n"));
406                         vdata->fast_error++;
407                 } else {
408                         vdata->fast_added_to_delete_list++;
409                 }
410         } else {
411                 res = tdb_delete(ctdb_db->ltdb->tdb, dd->key);
412
413                 if (res != 0) {
414                         DEBUG(DEBUG_ERR,
415                               (__location__ " Error deleting record from local "
416                                "data base.\n"));
417                         vdata->fast_error++;
418                 } else {
419                         vdata->fast_deleted++;
420                 }
421         }
422
423         goto done;
424
425 skipped:
426         vdata->fast_skipped++;
427
428 done:
429         if (tdb_data.dptr != NULL) {
430                 free(tdb_data.dptr);
431         }
432         tdb_chainunlock(ctdb_db->ltdb->tdb, dd->key);
433
434         return 0;
435 }
436
437 /**
438  * Delete the records that we are lmaster and dmaster for and
439  * that could be deleted on all other nodes via the TRY_DELETE_RECORDS
440  * control.
441  */
442 static int delete_record_traverse(void *param, void *data)
443 {
444         struct delete_record_data *dd =
445                 talloc_get_type(data, struct delete_record_data);
446         struct vacuum_data *vdata = talloc_get_type(param, struct vacuum_data);
447         struct ctdb_db_context *ctdb_db = dd->ctdb_db;
448         struct ctdb_context *ctdb = ctdb_db->ctdb;
449         int res;
450         struct ctdb_ltdb_header *header;
451         TDB_DATA tdb_data;
452         uint32_t lmaster;
453         bool deleted = false;
454
455         res = tdb_chainlock(ctdb_db->ltdb->tdb, dd->key);
456         if (res != 0) {
457                 DEBUG(DEBUG_ERR, (__location__ " Error getting chainlock.\n"));
458                 vdata->delete_local_error++;
459                 return 0;
460         }
461
462         /*
463          * Verify that the record is still empty, its RSN has not
464          * changed and that we are still its lmaster and dmaster.
465          */
466
467         tdb_data = tdb_fetch(ctdb_db->ltdb->tdb, dd->key);
468         if (tdb_data.dsize < sizeof(struct ctdb_ltdb_header)) {
469                 /* Does not exist or not a ctdb record. Skip. */
470                 vdata->delete_skipped++;
471                 goto done;
472         }
473
474         if (tdb_data.dsize > sizeof(struct ctdb_ltdb_header)) {
475                 /* The record has been recycled (filled with data). Skip. */
476                 vdata->delete_skipped++;
477                 goto done;
478         }
479
480         header = (struct ctdb_ltdb_header *)tdb_data.dptr;
481
482         if (header->dmaster != ctdb->pnn) {
483                 /* The record has been migrated off the node. Skip. */
484                 vdata->delete_skipped++;
485                 goto done;
486         }
487
488
489         if (header->rsn != dd->hdr.rsn) {
490                 /*
491                  * The record has been migrated off the node and back again.
492                  * But not requeued for deletion. Skip it.
493                  */
494                 vdata->delete_skipped++;
495                 goto done;
496         }
497
498         lmaster = ctdb_lmaster(ctdb_db->ctdb, &dd->key);
499
500         if (lmaster != ctdb->pnn) {
501                 /* we are not lmaster - strange */
502                 vdata->delete_skipped++;
503                 goto done;
504         }
505
506         res = tdb_delete(ctdb_db->ltdb->tdb, dd->key);
507
508         if (res != 0) {
509                 DEBUG(DEBUG_ERR,
510                       (__location__ " Error deleting record from local "
511                        "data base.\n"));
512                 vdata->delete_local_error++;
513                 goto done;
514         }
515
516         deleted = true;
517
518 done:
519         if (tdb_data.dptr != NULL) {
520                 free(tdb_data.dptr);
521         }
522
523         tdb_chainunlock(ctdb_db->ltdb->tdb, dd->key);
524
525         if (deleted) {
526                 /*
527                  * successfully deleted the record locally.
528                  * remove it from the list and update statistics.
529                  */
530                 talloc_free(dd);
531                 vdata->delete_deleted++;
532                 vdata->delete_left--;
533         }
534
535         return 0;
536 }
537
538 /**
539  * Fast vacuuming run:
540  * Traverse the delete_queue.
541  * This fills the same lists as the database traverse.
542  */
543 static void ctdb_vacuum_db_fast(struct ctdb_db_context *ctdb_db,
544                                 struct vacuum_data *vdata)
545 {
546         trbt_traversearray32(ctdb_db->delete_queue, 1, delete_queue_traverse, vdata);
547
548         if (vdata->fast_total > 0) {
549                 DEBUG(DEBUG_INFO,
550                       (__location__
551                        " fast vacuuming delete_queue traverse statistics: "
552                        "db[%s] "
553                        "total[%u] "
554                        "del[%u] "
555                        "skp[%u] "
556                        "err[%u] "
557                        "adl[%u] "
558                        "avf[%u]\n",
559                        ctdb_db->db_name,
560                        (unsigned)vdata->fast_total,
561                        (unsigned)vdata->fast_deleted,
562                        (unsigned)vdata->fast_skipped,
563                        (unsigned)vdata->fast_error,
564                        (unsigned)vdata->fast_added_to_delete_list,
565                        (unsigned)vdata->fast_added_to_vacuum_fetch_list));
566         }
567
568         return;
569 }
570
571 /**
572  * Vacuum a DB:
573  *  - Always do the fast vacuuming run, which traverses
574  *    the in-memory delete queue: these records have been
575  *    scheduled for deletion.
576  *  - Only if explicitly requested, the database is traversed
577  *    in order to use the traditional heuristics on empty records
578  *    to trigger deletion.
579  *    This is done only every VacuumFastPathCount'th vacuuming run.
580  *
581  * The traverse runs fill two lists:
582  *
583  * - The delete_list:
584  *   This is the list of empty records the current
585  *   node is lmaster and dmaster for. These records are later
586  *   deleted first on other nodes and then locally.
587  *
588  *   The fast vacuuming run has a short cut for those records
589  *   that have never been migrated with data: these records
590  *   are immediately deleted locally, since they have left
591  *   no trace on other nodes.
592  *
593  * - The vacuum_fetch lists
594  *   (one for each other lmaster node):
595  *   The records in this list are sent for deletion to
596  *   their lmaster in a bulk VACUUM_FETCH message.
597  *
598  *   The lmaster then migrates all these records to itelf
599  *   so that they can be vacuumed there.
600  *
601  * This executes in the child context.
602  */
603 static int ctdb_vacuum_db(struct ctdb_db_context *ctdb_db,
604                           struct vacuum_data *vdata,
605                           bool full_vacuum_run)
606 {
607         struct ctdb_context *ctdb = ctdb_db->ctdb;
608         const char *name = ctdb_db->db_name;
609         int ret, i, pnn;
610
611         DEBUG(DEBUG_INFO, (__location__ " Entering %s vacuum run for db "
612                            "%s db_id[0x%08x]\n",
613                            full_vacuum_run ? "full" : "fast",
614                            ctdb_db->db_name, ctdb_db->db_id));
615
616         ret = ctdb_ctrl_getvnnmap(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE, ctdb, &ctdb->vnn_map);
617         if (ret != 0) {
618                 DEBUG(DEBUG_ERR, ("Unable to get vnnmap from local node\n"));
619                 return ret;
620         }
621
622         pnn = ctdb_ctrl_getpnn(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE);
623         if (pnn == -1) {
624                 DEBUG(DEBUG_ERR, ("Unable to get pnn from local node\n"));
625                 return -1;
626         }
627
628         ctdb->pnn = pnn;
629
630         vdata->fast_added_to_delete_list = 0;
631         vdata->fast_added_to_vacuum_fetch_list = 0;
632         vdata->fast_deleted = 0;
633         vdata->fast_skipped = 0;
634         vdata->fast_error = 0;
635         vdata->fast_total = 0;
636         vdata->full_added_to_delete_list = 0;
637         vdata->full_added_to_vacuum_fetch_list = 0;
638         vdata->full_skipped = 0;
639         vdata->full_error = 0;
640         vdata->full_total = 0;
641         vdata->delete_count = 0;
642         vdata->delete_left = 0;
643         vdata->delete_remote_error = 0;
644         vdata->delete_local_error = 0;
645         vdata->delete_skipped = 0;
646         vdata->delete_deleted = 0;
647
648         /* the list needs to be of length num_nodes */
649         vdata->vacuum_fetch_list = talloc_array(vdata,
650                                                 struct ctdb_marshall_buffer *,
651                                                 ctdb->num_nodes);
652         if (vdata->vacuum_fetch_list == NULL) {
653                 DEBUG(DEBUG_ERR,(__location__ " Out of memory\n"));
654                 return -1;
655         }
656         for (i = 0; i < ctdb->num_nodes; i++) {
657                 vdata->vacuum_fetch_list[i] = (struct ctdb_marshall_buffer *)
658                         talloc_zero_size(vdata->vacuum_fetch_list,
659                                          offsetof(struct ctdb_marshall_buffer, data));
660                 if (vdata->vacuum_fetch_list[i] == NULL) {
661                         DEBUG(DEBUG_ERR,(__location__ " Out of memory\n"));
662                         return -1;
663                 }
664                 vdata->vacuum_fetch_list[i]->db_id = ctdb_db->db_id;
665         }
666
667         ctdb_vacuum_db_fast(ctdb_db, vdata);
668
669         /*
670          * read-only traverse of the database, looking for records that
671          * might be able to be vacuumed.
672          *
673          * This is not done each time but only every tunable
674          * VacuumFastPathCount times.
675          */
676         if (full_vacuum_run) {
677                 ret = tdb_traverse_read(ctdb_db->ltdb->tdb, vacuum_traverse, vdata);
678                 if (ret == -1 || vdata->traverse_error) {
679                         DEBUG(DEBUG_ERR,(__location__ " Traverse error in vacuuming '%s'\n", name));
680                         return -1;
681                 }
682                 if (vdata->full_total > 0) {
683                         DEBUG(DEBUG_INFO,
684                               (__location__
685                                " full vacuuming db traverse statistics: "
686                                "db[%s] "
687                                "total[%u] "
688                                "skp[%u] "
689                                "err[%u] "
690                                "adl[%u] "
691                                "avf[%u]\n",
692                                ctdb_db->db_name,
693                                (unsigned)vdata->full_total,
694                                (unsigned)vdata->full_skipped,
695                                (unsigned)vdata->full_error,
696                                (unsigned)vdata->full_added_to_delete_list,
697                                (unsigned)vdata->full_added_to_vacuum_fetch_list));
698                 }
699         }
700
701         /*
702          * For records where we are not the lmaster,
703          * tell the lmaster to fetch the record.
704          */
705         for (i = 0; i < ctdb->num_nodes; i++) {
706                 TDB_DATA data;
707                 struct ctdb_marshall_buffer *vfl = vdata->vacuum_fetch_list[i];
708
709                 if (ctdb->nodes[i]->pnn == ctdb->pnn) {
710                         continue;
711                 }
712
713                 if (vfl->count == 0) {
714                         continue;
715                 }
716
717                 DEBUG(DEBUG_INFO, ("Found %u records for lmaster %u in '%s'\n",
718                                    vfl->count, ctdb->nodes[i]->pnn,
719                                    name));
720
721                 data.dsize = talloc_get_size(vfl);
722                 data.dptr  = (void *)vfl;
723                 if (ctdb_client_send_message(ctdb, ctdb->nodes[i]->pnn, CTDB_SRVID_VACUUM_FETCH, data) != 0) {
724                         DEBUG(DEBUG_ERR, (__location__ " Failed to send vacuum "
725                                           "fetch message to %u\n",
726                                           ctdb->nodes[i]->pnn));
727                         return -1;
728                 }
729         }       
730
731         /* Process all records we can delete (if any) */
732         if (vdata->delete_count > 0) {
733                 struct delete_records_list *recs;
734                 TDB_DATA indata, outdata;
735                 int32_t res;
736                 struct ctdb_node_map *nodemap;
737                 uint32_t *active_nodes;
738                 int num_active_nodes;
739
740                 vdata->delete_left = vdata->delete_count;
741
742                 recs = talloc_zero(vdata, struct delete_records_list);
743                 if (recs == NULL) {
744                         DEBUG(DEBUG_ERR,(__location__ " Out of memory\n"));
745                         return -1;
746                 }
747                 recs->records = (struct ctdb_marshall_buffer *)
748                         talloc_zero_size(vdata, 
749                                     offsetof(struct ctdb_marshall_buffer, data));
750                 if (recs->records == NULL) {
751                         DEBUG(DEBUG_ERR,(__location__ " Out of memory\n"));
752                         return -1;
753                 }
754                 recs->records->db_id = ctdb_db->db_id;
755
756                 /* 
757                  * traverse the tree of all records we want to delete and
758                  * create a blob we can send to the other nodes.
759                  */
760                 trbt_traversearray32(vdata->delete_list, 1,
761                                      delete_marshall_traverse, recs);
762
763                 indata.dsize = talloc_get_size(recs->records);
764                 indata.dptr  = (void *)recs->records;
765
766                 /* 
767                  * now tell all the active nodes to delete all these records
768                  * (if possible)
769                  */
770
771                 ret = ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(),
772                                            CTDB_CURRENT_NODE,
773                                            recs, /* talloc context */
774                                            &nodemap);
775                 if (ret != 0) {
776                         DEBUG(DEBUG_ERR,(__location__ " unable to get node map\n"));
777                         return -1;
778                 }
779
780                 active_nodes = list_of_active_nodes(ctdb, nodemap,
781                                                     nodemap, /* talloc context */
782                                                     false /* include self */);
783                 /* yuck! ;-) */
784                 num_active_nodes = talloc_get_size(active_nodes)/sizeof(*active_nodes);
785
786                 for (i = 0; i < num_active_nodes; i++) {
787                         struct ctdb_marshall_buffer *records;
788                         struct ctdb_rec_data *rec;
789
790                         ret = ctdb_control(ctdb, active_nodes[i], 0,
791                                         CTDB_CONTROL_TRY_DELETE_RECORDS, 0,
792                                         indata, recs, &outdata, &res,
793                                         NULL, NULL);
794                         if (ret != 0 || res != 0) {
795                                 DEBUG(DEBUG_ERR, ("Failed to delete records on "
796                                                   "node %u: ret[%d] res[%d]\n",
797                                                   active_nodes[i], ret, res));
798                                 return -1;
799                         }
800
801                         /*
802                          * outdata contains the list of records coming back
803                          * from the node: These are the records that the
804                          * remote node could not delete.
805                          */
806                         records = (struct ctdb_marshall_buffer *)outdata.dptr;
807                         rec = (struct ctdb_rec_data *)&records->data[0];
808                         while (records->count-- > 1) {
809                                 TDB_DATA reckey, recdata;
810                                 struct ctdb_ltdb_header *rechdr;
811                                 struct delete_record_data *dd;
812
813                                 reckey.dptr = &rec->data[0];
814                                 reckey.dsize = rec->keylen;
815                                 recdata.dptr = &rec->data[reckey.dsize];
816                                 recdata.dsize = rec->datalen;
817
818                                 if (recdata.dsize < sizeof(struct ctdb_ltdb_header)) {
819                                         DEBUG(DEBUG_CRIT,(__location__ " bad ltdb record\n"));
820                                         return -1;
821                                 }
822                                 rechdr = (struct ctdb_ltdb_header *)recdata.dptr;
823                                 recdata.dptr += sizeof(*rechdr);
824                                 recdata.dsize -= sizeof(*rechdr);
825
826                                 dd = (struct delete_record_data *)trbt_lookup32(
827                                                 vdata->delete_list,
828                                                 ctdb_hash(&reckey));
829                                 if (dd != NULL) {
830                                         /*
831                                          * The other node could not delete the
832                                          * record and it is the first node that
833                                          * failed. So we should remove it from
834                                          * the tree and update statistics.
835                                          */
836                                         talloc_free(dd);
837                                         vdata->delete_remote_error++;
838                                         vdata->delete_left--;
839                                 }
840
841                                 rec = (struct ctdb_rec_data *)(rec->length + (uint8_t *)rec);
842                         }
843                 }
844
845                 /* free nodemap and active_nodes */
846                 talloc_free(nodemap);
847         }
848
849         if (vdata->delete_left > 0) {
850                 /*
851                  * The only records remaining in the tree are those
852                  * records which all other nodes could successfully
853                  * delete, so we can safely delete them on the
854                  * lmaster as well.
855                  */
856                 trbt_traversearray32(vdata->delete_list, 1,
857                                      delete_record_traverse, vdata);
858         }
859
860         /* this ensures we run our event queue */
861         ctdb_ctrl_getpnn(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE);
862
863         return 0;
864 }
865
866
867 /*
868  * traverse function for repacking
869  */
870 static int repack_traverse(struct tdb_context *tdb, TDB_DATA key, TDB_DATA data, void *private)
871 {
872         struct vacuum_data *vdata = (struct vacuum_data *)private;
873
874         if (vdata->vacuum) {
875                 uint32_t hash = ctdb_hash(&key);
876                 struct delete_record_data *kd;
877                 /*
878                  * check if we can ignore this record because it's in the delete_list
879                  */
880                 kd = (struct delete_record_data *)trbt_lookup32(vdata->delete_list, hash);
881                 /*
882                  * there might be hash collisions so we have to compare the keys here to be sure
883                  */
884                 if (kd && kd->key.dsize == key.dsize && memcmp(kd->key.dptr, key.dptr, key.dsize) == 0) {
885                         struct ctdb_ltdb_header *hdr = (struct ctdb_ltdb_header *)data.dptr;
886                         /*
887                          * we have to check if the record hasn't changed in the meantime in order to
888                          * savely remove it from the database
889                          */
890                         if (data.dsize == sizeof(struct ctdb_ltdb_header) &&
891                                 hdr->dmaster == kd->ctdb->pnn &&
892                                 ctdb_lmaster(kd->ctdb, &(kd->key)) == kd->ctdb->pnn &&
893                                 kd->hdr.rsn == hdr->rsn) {
894                                 vdata->vacuumed++;
895                                 return 0;
896                         }
897                 }
898         }
899         if (tdb_store(vdata->dest_db, key, data, TDB_INSERT) != 0) {
900                 vdata->traverse_error = true;
901                 return -1;
902         }
903         vdata->copied++;
904         return 0;
905 }
906
907 /*
908  * repack a tdb
909  */
910 static int ctdb_repack_tdb(struct tdb_context *tdb, TALLOC_CTX *mem_ctx, struct vacuum_data *vdata)
911 {
912         struct tdb_context *tmp_db;
913
914         if (tdb_transaction_start(tdb) != 0) {
915                 DEBUG(DEBUG_ERR,(__location__ " Failed to start transaction\n"));
916                 return -1;
917         }
918
919         tmp_db = tdb_open("tmpdb", tdb_hash_size(tdb),
920                           TDB_INTERNAL|TDB_DISALLOW_NESTING,
921                           O_RDWR|O_CREAT, 0);
922         if (tmp_db == NULL) {
923                 DEBUG(DEBUG_ERR,(__location__ " Failed to create tmp_db\n"));
924                 tdb_transaction_cancel(tdb);
925                 return -1;
926         }
927
928         vdata->traverse_error = false;
929         vdata->dest_db = tmp_db;
930         vdata->vacuum = true;
931         vdata->vacuumed = 0;
932         vdata->copied = 0;
933
934         /*
935          * repack and vacuum on-the-fly by not writing the records that are
936          * no longer needed
937          */
938         if (tdb_traverse_read(tdb, repack_traverse, vdata) == -1) {
939                 DEBUG(DEBUG_ERR,(__location__ " Failed to traverse copying out\n"));
940                 tdb_transaction_cancel(tdb);
941                 tdb_close(tmp_db);
942                 return -1;              
943         }
944
945         DEBUG(DEBUG_INFO,(__location__ " %u records vacuumed\n", vdata->vacuumed));
946         
947         if (vdata->traverse_error) {
948                 DEBUG(DEBUG_ERR,(__location__ " Error during traversal\n"));
949                 tdb_transaction_cancel(tdb);
950                 tdb_close(tmp_db);
951                 return -1;
952         }
953
954         if (tdb_wipe_all(tdb) != 0) {
955                 DEBUG(DEBUG_ERR,(__location__ " Failed to wipe database\n"));
956                 tdb_transaction_cancel(tdb);
957                 tdb_close(tmp_db);
958                 return -1;
959         }
960
961         vdata->traverse_error = false;
962         vdata->dest_db = tdb;
963         vdata->vacuum = false;
964         vdata->copied = 0;
965
966         if (tdb_traverse_read(tmp_db, repack_traverse, vdata) == -1) {
967                 DEBUG(DEBUG_ERR,(__location__ " Failed to traverse copying back\n"));
968                 tdb_transaction_cancel(tdb);
969                 tdb_close(tmp_db);
970                 return -1;              
971         }
972
973         if (vdata->traverse_error) {
974                 DEBUG(DEBUG_ERR,(__location__ " Error during second traversal\n"));
975                 tdb_transaction_cancel(tdb);
976                 tdb_close(tmp_db);
977                 return -1;
978         }
979
980         tdb_close(tmp_db);
981
982
983         if (tdb_transaction_commit(tdb) != 0) {
984                 DEBUG(DEBUG_ERR,(__location__ " Failed to commit\n"));
985                 return -1;
986         }
987         DEBUG(DEBUG_INFO,(__location__ " %u records copied\n", vdata->copied));
988
989         return 0;
990 }
991
992 /*
993  * repack and vaccum a db
994  * called from the child context
995  */
996 static int ctdb_vacuum_and_repack_db(struct ctdb_db_context *ctdb_db,
997                                      TALLOC_CTX *mem_ctx,
998                                      bool full_vacuum_run)
999 {
1000         uint32_t repack_limit = ctdb_db->ctdb->tunable.repack_limit;
1001         uint32_t vacuum_limit = ctdb_db->ctdb->tunable.vacuum_limit;
1002         const char *name = ctdb_db->db_name;
1003         int freelist_size;
1004         struct vacuum_data *vdata;
1005
1006         freelist_size = tdb_freelist_size(ctdb_db->ltdb->tdb);
1007         if (freelist_size == -1) {
1008                 DEBUG(DEBUG_ERR,(__location__ " Failed to get freelist size for '%s'\n", name));
1009                 return -1;
1010         }
1011
1012         vdata = talloc_zero(mem_ctx, struct vacuum_data);
1013         if (vdata == NULL) {
1014                 DEBUG(DEBUG_ERR,(__location__ " Out of memory\n"));
1015                 return -1;
1016         }
1017
1018         vdata->ctdb = ctdb_db->ctdb;
1019         vdata->vacuum_limit = vacuum_limit;
1020         vdata->repack_limit = repack_limit;
1021         vdata->delete_list = trbt_create(vdata, 0);
1022         vdata->ctdb_db = ctdb_db;
1023         if (vdata->delete_list == NULL) {
1024                 DEBUG(DEBUG_ERR,(__location__ " Out of memory\n"));
1025                 talloc_free(vdata);
1026                 return -1;
1027         }
1028
1029         vdata->start = timeval_current();
1030  
1031         /*
1032          * gather all records that can be deleted in vdata
1033          */
1034         if (ctdb_vacuum_db(ctdb_db, vdata, full_vacuum_run) != 0) {
1035                 DEBUG(DEBUG_ERR,(__location__ " Failed to vacuum '%s'\n", name));
1036         }
1037
1038         /*
1039          * decide if a repack is necessary
1040          */
1041         if (freelist_size < repack_limit && vdata->delete_left < vacuum_limit)
1042         {
1043                 talloc_free(vdata);
1044                 return 0;
1045         }
1046
1047         DEBUG(DEBUG_INFO,("Repacking %s with %u freelist entries and %u records to delete\n", 
1048                         name, freelist_size, vdata->delete_left));
1049
1050         /*
1051          * repack and implicitely get rid of the records we can delete
1052          */
1053         if (ctdb_repack_tdb(ctdb_db->ltdb->tdb, mem_ctx, vdata) != 0) {
1054                 DEBUG(DEBUG_ERR,(__location__ " Failed to repack '%s'\n", name));
1055                 talloc_free(vdata);
1056                 return -1;
1057         }
1058         talloc_free(vdata);
1059
1060         return 0;
1061 }
1062
1063 static uint32_t get_vacuum_interval(struct ctdb_db_context *ctdb_db)
1064 {
1065         uint32_t interval = ctdb_db->ctdb->tunable.vacuum_interval;
1066
1067         return interval;
1068 }
1069
1070 static int vacuum_child_destructor(struct ctdb_vacuum_child_context *child_ctx)
1071 {
1072         double l = timeval_elapsed(&child_ctx->start_time);
1073         struct ctdb_db_context *ctdb_db = child_ctx->vacuum_handle->ctdb_db;
1074         struct ctdb_context *ctdb = ctdb_db->ctdb;
1075
1076         DEBUG(DEBUG_INFO,("Vacuuming took %.3f seconds for database %s\n", l, ctdb_db->db_name));
1077
1078         if (child_ctx->child_pid != -1) {
1079                 kill(child_ctx->child_pid, SIGKILL);
1080         } else {
1081                 /* Bump the number of successful fast-path runs. */
1082                 child_ctx->vacuum_handle->fast_path_count++;
1083         }
1084
1085         DLIST_REMOVE(ctdb->vacuumers, child_ctx);
1086
1087         event_add_timed(ctdb->ev, child_ctx->vacuum_handle,
1088                         timeval_current_ofs(get_vacuum_interval(ctdb_db), 0), 
1089                         ctdb_vacuum_event, child_ctx->vacuum_handle);
1090
1091         return 0;
1092 }
1093
1094 /*
1095  * this event is generated when a vacuum child process times out
1096  */
1097 static void vacuum_child_timeout(struct event_context *ev, struct timed_event *te,
1098                                          struct timeval t, void *private_data)
1099 {
1100         struct ctdb_vacuum_child_context *child_ctx = talloc_get_type(private_data, struct ctdb_vacuum_child_context);
1101
1102         DEBUG(DEBUG_ERR,("Vacuuming child process timed out for db %s\n", child_ctx->vacuum_handle->ctdb_db->db_name));
1103
1104         child_ctx->status = VACUUM_TIMEOUT;
1105
1106         talloc_free(child_ctx);
1107 }
1108
1109
1110 /*
1111  * this event is generated when a vacuum child process has completed
1112  */
1113 static void vacuum_child_handler(struct event_context *ev, struct fd_event *fde,
1114                              uint16_t flags, void *private_data)
1115 {
1116         struct ctdb_vacuum_child_context *child_ctx = talloc_get_type(private_data, struct ctdb_vacuum_child_context);
1117         char c = 0;
1118         int ret;
1119
1120         DEBUG(DEBUG_INFO,("Vacuuming child process %d finished for db %s\n", child_ctx->child_pid, child_ctx->vacuum_handle->ctdb_db->db_name));
1121         child_ctx->child_pid = -1;
1122
1123         ret = read(child_ctx->fd[0], &c, 1);
1124         if (ret != 1 || c != 0) {
1125                 child_ctx->status = VACUUM_ERROR;
1126                 DEBUG(DEBUG_ERR, ("A vacuum child process failed with an error for database %s. ret=%d c=%d\n", child_ctx->vacuum_handle->ctdb_db->db_name, ret, c));
1127         } else {
1128                 child_ctx->status = VACUUM_OK;
1129         }
1130
1131         talloc_free(child_ctx);
1132 }
1133
1134 /*
1135  * this event is called every time we need to start a new vacuum process
1136  */
1137 static void
1138 ctdb_vacuum_event(struct event_context *ev, struct timed_event *te,
1139                                struct timeval t, void *private_data)
1140 {
1141         struct ctdb_vacuum_handle *vacuum_handle = talloc_get_type(private_data, struct ctdb_vacuum_handle);
1142         struct ctdb_db_context *ctdb_db = vacuum_handle->ctdb_db;
1143         struct ctdb_context *ctdb = ctdb_db->ctdb;
1144         struct ctdb_vacuum_child_context *child_ctx;
1145         struct tevent_fd *fde;
1146         int ret;
1147
1148         /* we dont vacuum if we are in recovery mode, or db frozen */
1149         if (ctdb->recovery_mode == CTDB_RECOVERY_ACTIVE ||
1150             ctdb->freeze_mode[ctdb_db->priority] != CTDB_FREEZE_NONE) {
1151                 DEBUG(DEBUG_INFO, ("Not vacuuming %s (%s)\n", ctdb_db->db_name,
1152                                    ctdb->recovery_mode == CTDB_RECOVERY_ACTIVE ? "in recovery"
1153                                    : ctdb->freeze_mode[ctdb_db->priority] == CTDB_FREEZE_PENDING
1154                                    ? "freeze pending"
1155                                    : "frozen"));
1156                 event_add_timed(ctdb->ev, vacuum_handle,
1157                         timeval_current_ofs(get_vacuum_interval(ctdb_db), 0),
1158                         ctdb_vacuum_event, vacuum_handle);
1159                 return;
1160         }
1161
1162         child_ctx = talloc(vacuum_handle, struct ctdb_vacuum_child_context);
1163         if (child_ctx == NULL) {
1164                 DEBUG(DEBUG_CRIT, (__location__ " Failed to allocate child context for vacuuming of %s\n", ctdb_db->db_name));
1165                 ctdb_fatal(ctdb, "Out of memory when crating vacuum child context. Shutting down\n");
1166         }
1167
1168
1169         ret = pipe(child_ctx->fd);
1170         if (ret != 0) {
1171                 talloc_free(child_ctx);
1172                 DEBUG(DEBUG_ERR, ("Failed to create pipe for vacuum child process.\n"));
1173                 event_add_timed(ctdb->ev, vacuum_handle,
1174                         timeval_current_ofs(get_vacuum_interval(ctdb_db), 0),
1175                         ctdb_vacuum_event, vacuum_handle);
1176                 return;
1177         }
1178
1179         if (vacuum_handle->fast_path_count > ctdb->tunable.vacuum_fast_path_count) {
1180                 vacuum_handle->fast_path_count = 0;
1181         }
1182
1183         child_ctx->child_pid = ctdb_fork(ctdb);
1184         if (child_ctx->child_pid == (pid_t)-1) {
1185                 close(child_ctx->fd[0]);
1186                 close(child_ctx->fd[1]);
1187                 talloc_free(child_ctx);
1188                 DEBUG(DEBUG_ERR, ("Failed to fork vacuum child process.\n"));
1189                 event_add_timed(ctdb->ev, vacuum_handle,
1190                         timeval_current_ofs(get_vacuum_interval(ctdb_db), 0),
1191                         ctdb_vacuum_event, vacuum_handle);
1192                 return;
1193         }
1194
1195
1196         if (child_ctx->child_pid == 0) {
1197                 char cc = 0;
1198                 bool full_vacuum_run = false;
1199                 close(child_ctx->fd[0]);
1200
1201                 DEBUG(DEBUG_INFO,("Vacuuming child process %d for db %s started\n", getpid(), ctdb_db->db_name));
1202         
1203                 if (switch_from_server_to_client(ctdb, "vacuum-%s", ctdb_db->db_name) != 0) {
1204                         DEBUG(DEBUG_CRIT, (__location__ "ERROR: failed to switch vacuum daemon into client mode. Shutting down.\n"));
1205                         _exit(1);
1206                 }
1207
1208                 /* 
1209                  * repack the db
1210                  */
1211                 if ((ctdb->tunable.vacuum_fast_path_count > 0) &&
1212                     (vacuum_handle->fast_path_count == 0))
1213                 {
1214                         full_vacuum_run = true;
1215                 }
1216                 cc = ctdb_vacuum_and_repack_db(ctdb_db, child_ctx,
1217                                                full_vacuum_run);
1218
1219                 write(child_ctx->fd[1], &cc, 1);
1220                 _exit(0);
1221         }
1222
1223         set_close_on_exec(child_ctx->fd[0]);
1224         close(child_ctx->fd[1]);
1225
1226         child_ctx->status = VACUUM_RUNNING;
1227         child_ctx->start_time = timeval_current();
1228
1229         DLIST_ADD(ctdb->vacuumers, child_ctx);
1230         talloc_set_destructor(child_ctx, vacuum_child_destructor);
1231
1232         /*
1233          * Clear the fastpath vacuuming list in the parent.
1234          */
1235         talloc_free(ctdb_db->delete_queue);
1236         ctdb_db->delete_queue = trbt_create(ctdb_db, 0);
1237         if (ctdb_db->delete_queue == NULL) {
1238                 /* fatal here? ... */
1239                 ctdb_fatal(ctdb, "Out of memory when re-creating vacuum tree "
1240                                  "in parent context. Shutting down\n");
1241         }
1242
1243         event_add_timed(ctdb->ev, child_ctx,
1244                 timeval_current_ofs(ctdb->tunable.vacuum_max_run_time, 0),
1245                 vacuum_child_timeout, child_ctx);
1246
1247         DEBUG(DEBUG_DEBUG, (__location__ " Created PIPE FD:%d to child vacuum process\n", child_ctx->fd[0]));
1248
1249         fde = event_add_fd(ctdb->ev, child_ctx, child_ctx->fd[0],
1250                            EVENT_FD_READ, vacuum_child_handler, child_ctx);
1251         tevent_fd_set_auto_close(fde);
1252
1253         vacuum_handle->child_ctx = child_ctx;
1254         child_ctx->vacuum_handle = vacuum_handle;
1255 }
1256
1257 void ctdb_stop_vacuuming(struct ctdb_context *ctdb)
1258 {
1259         /* Simply free them all. */
1260         while (ctdb->vacuumers) {
1261                 DEBUG(DEBUG_INFO, ("Aborting vacuuming for %s (%i)\n",
1262                            ctdb->vacuumers->vacuum_handle->ctdb_db->db_name,
1263                            (int)ctdb->vacuumers->child_pid));
1264                 /* vacuum_child_destructor kills it, removes from list */
1265                 talloc_free(ctdb->vacuumers);
1266         }
1267 }
1268
1269 /* this function initializes the vacuuming context for a database
1270  * starts the vacuuming events
1271  */
1272 int ctdb_vacuum_init(struct ctdb_db_context *ctdb_db)
1273 {
1274         if (ctdb_db->persistent != 0) {
1275                 DEBUG(DEBUG_ERR,("Vacuuming is disabled for persistent database %s\n", ctdb_db->db_name));
1276                 return 0;
1277         }
1278
1279         ctdb_db->vacuum_handle = talloc(ctdb_db, struct ctdb_vacuum_handle);
1280         CTDB_NO_MEMORY(ctdb_db->ctdb, ctdb_db->vacuum_handle);
1281
1282         ctdb_db->vacuum_handle->ctdb_db         = ctdb_db;
1283         ctdb_db->vacuum_handle->fast_path_count = 0;
1284
1285         event_add_timed(ctdb_db->ctdb->ev, ctdb_db->vacuum_handle, 
1286                         timeval_current_ofs(get_vacuum_interval(ctdb_db), 0), 
1287                         ctdb_vacuum_event, ctdb_db->vacuum_handle);
1288
1289         return 0;
1290 }
1291
1292 static void remove_record_from_delete_queue(struct ctdb_db_context *ctdb_db,
1293                                             const struct ctdb_ltdb_header *hdr,
1294                                             const TDB_DATA key)
1295 {
1296         struct delete_record_data *kd;
1297         uint32_t hash;
1298
1299         hash = (uint32_t)ctdb_hash(&key);
1300
1301         DEBUG(DEBUG_DEBUG, (__location__
1302                             " remove_record_from_delete_queue: db[%s] "
1303                             "db_id[0x%08x] "
1304                             "key_hash[0x%08x] "
1305                             "lmaster[%u] "
1306                             "migrated_with_data[%s]\n",
1307                              ctdb_db->db_name, ctdb_db->db_id,
1308                              hash,
1309                              ctdb_lmaster(ctdb_db->ctdb, &key),
1310                              hdr->flags & CTDB_REC_FLAG_MIGRATED_WITH_DATA ? "yes" : "no"));
1311
1312         kd = (struct delete_record_data *)trbt_lookup32(ctdb_db->delete_queue, hash);
1313         if (kd == NULL) {
1314                 return;
1315         }
1316         if (kd->key.dsize != key.dsize) {
1317                 return;
1318         }
1319         if (memcmp(kd->key.dptr, key.dptr, key.dsize) != 0) {
1320                 return;
1321         }
1322
1323         talloc_free(kd);
1324
1325         return;
1326 }
1327
1328 /**
1329  * Insert a record into the ctdb_db context's delete queue,
1330  * handling hash collisions.
1331  */
1332 static int insert_record_into_delete_queue(struct ctdb_db_context *ctdb_db,
1333                                            const struct ctdb_ltdb_header *hdr,
1334                                            TDB_DATA key)
1335 {
1336         struct delete_record_data *kd;
1337         uint32_t hash;
1338         int ret;
1339
1340         hash = (uint32_t)ctdb_hash(&key);
1341
1342         DEBUG(DEBUG_INFO, (__location__ " Schedule for deletion: db[%s] "
1343                            "db_id[0x%08x] "
1344                            "key_hash[0x%08x] "
1345                            "lmaster[%u] "
1346                            "migrated_with_data[%s]\n",
1347                             ctdb_db->db_name, ctdb_db->db_id,
1348                             hash,
1349                             ctdb_lmaster(ctdb_db->ctdb, &key),
1350                             hdr->flags & CTDB_REC_FLAG_MIGRATED_WITH_DATA ? "yes" : "no"));
1351
1352         kd = (struct delete_record_data *)trbt_lookup32(ctdb_db->delete_queue, hash);
1353         if (kd != NULL) {
1354                 if ((kd->key.dsize != key.dsize) ||
1355                     (memcmp(kd->key.dptr, key.dptr, key.dsize) != 0))
1356                 {
1357                         DEBUG(DEBUG_INFO,
1358                               ("schedule for deletion: Hash collision (0x%08x)."
1359                                " Skipping the record.\n", hash));
1360                         return 0;
1361                 } else {
1362                         DEBUG(DEBUG_DEBUG,
1363                               ("schedule for deletion: Overwriting entry for "
1364                                "key with hash 0x%08x.\n", hash));
1365                 }
1366         }
1367
1368         ret = insert_delete_record_data_into_tree(ctdb_db->ctdb, ctdb_db,
1369                                                   ctdb_db->delete_queue,
1370                                                   hdr, key);
1371         if (ret != 0) {
1372                 return -1;
1373         }
1374
1375         return 0;
1376 }
1377
1378 /**
1379  * Schedule a record for deletetion.
1380  * Called from the parent context.
1381  */
1382 int32_t ctdb_control_schedule_for_deletion(struct ctdb_context *ctdb,
1383                                            TDB_DATA indata)
1384 {
1385         struct ctdb_control_schedule_for_deletion *dd;
1386         struct ctdb_db_context *ctdb_db;
1387         int ret;
1388         TDB_DATA key;
1389
1390         dd = (struct ctdb_control_schedule_for_deletion *)indata.dptr;
1391
1392         ctdb_db = find_ctdb_db(ctdb, dd->db_id);
1393         if (ctdb_db == NULL) {
1394                 DEBUG(DEBUG_ERR, (__location__ " Unknown db id 0x%08x\n",
1395                                   dd->db_id));
1396                 return -1;
1397         }
1398
1399         key.dsize = dd->keylen;
1400         key.dptr = dd->key;
1401
1402         ret = insert_record_into_delete_queue(ctdb_db, &dd->hdr, key);
1403
1404         return ret;
1405 }
1406
1407 int32_t ctdb_local_schedule_for_deletion(struct ctdb_db_context *ctdb_db,
1408                                          const struct ctdb_ltdb_header *hdr,
1409                                          TDB_DATA key)
1410 {
1411         int ret;
1412         struct ctdb_control_schedule_for_deletion *dd;
1413         TDB_DATA indata;
1414         int32_t status;
1415
1416         if (ctdb_db->ctdb->ctdbd_pid == getpid()) {
1417                 /* main daemon - directly queue */
1418                 ret = insert_record_into_delete_queue(ctdb_db, hdr, key);
1419
1420                 return ret;
1421         }
1422
1423         /* child process: send the main daemon a control */
1424
1425         indata.dsize = offsetof(struct ctdb_control_schedule_for_deletion, key) + key.dsize;
1426         indata.dptr = talloc_zero_array(ctdb_db, uint8_t, indata.dsize);
1427         if (indata.dptr == NULL) {
1428                 DEBUG(DEBUG_ERR, (__location__ " out of memory\n"));
1429                 return -1;
1430         }
1431         dd = (struct ctdb_control_schedule_for_deletion *)(void *)indata.dptr;
1432         dd->db_id = ctdb_db->db_id;
1433         dd->hdr = *hdr;
1434         dd->keylen = key.dsize;
1435         memcpy(dd->key, key.dptr, key.dsize);
1436
1437         ret = ctdb_control(ctdb_db->ctdb,
1438                            CTDB_CURRENT_NODE,
1439                            ctdb_db->db_id,
1440                            CTDB_CONTROL_SCHEDULE_FOR_DELETION,
1441                            CTDB_CTRL_FLAG_NOREPLY, /* flags */
1442                            indata,
1443                            NULL, /* mem_ctx */
1444                            NULL, /* outdata */
1445                            &status,
1446                            NULL, /* timeout : NULL == wait forever */
1447                            NULL); /* error message */
1448
1449         talloc_free(indata.dptr);
1450
1451         if (ret != 0 || status != 0) {
1452                 DEBUG(DEBUG_ERR, (__location__ " Error sending "
1453                                   "SCHEDULE_FOR_DELETION "
1454                                   "control.\n"));
1455                 if (status != 0) {
1456                         ret = -1;
1457                 }
1458         }
1459
1460         return ret;
1461 }
1462
1463 void ctdb_local_remove_from_delete_queue(struct ctdb_db_context *ctdb_db,
1464                                          const struct ctdb_ltdb_header *hdr,
1465                                          const TDB_DATA key)
1466 {
1467         if (ctdb_db->ctdb->ctdbd_pid != getpid()) {
1468                 /*
1469                  * Only remove the record from the delete queue if called
1470                  * in the main daemon.
1471                  */
1472                 return;
1473         }
1474
1475         remove_record_from_delete_queue(ctdb_db, hdr, key);
1476
1477         return;
1478 }