vacuum: improve debugging in delete_queue_traverse()
[ctdb.git] / 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/events/events.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/events/events.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 = (uint32_t)tdb_jenkins_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 = (uint32_t)tdb_jenkins_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         uint32_t hash = ctdb_hash(&(dd->key));
337
338         vdata->fast_total++;
339
340         res = tdb_chainlock(ctdb_db->ltdb->tdb, dd->key);
341         if (res != 0) {
342                 DEBUG(DEBUG_ERR,
343                       (__location__ " Error getting chainlock on record with "
344                        "key hash [0x%08x] on database db[%s].\n",
345                        hash, ctdb_db->db_name));
346                 vdata->fast_error++;
347                 return 0;
348         }
349
350         tdb_data = tdb_fetch(ctdb_db->ltdb->tdb, dd->key);
351         if (tdb_data.dsize < sizeof(struct ctdb_ltdb_header)) {
352                 /* Does not exist or not a ctdb record. Skip. */
353                 goto skipped;
354         }
355
356         if (tdb_data.dsize > sizeof(struct ctdb_ltdb_header)) {
357                 /* The record has been recycled (filled with data). Skip. */
358                 goto skipped;
359         }
360
361         header = (struct ctdb_ltdb_header *)tdb_data.dptr;
362
363         if (header->dmaster != ctdb->pnn) {
364                 /* The record has been migrated off the node. Skip. */
365                 goto skipped;
366         }
367
368         if (header->rsn != dd->hdr.rsn) {
369                 /*
370                  * The record has been migrated off the node and back again.
371                  * But not requeued for deletion. Skip it.
372                  */
373                 goto skipped;
374         }
375
376         /*
377          * We are dmaster, and the record has no data, and it has
378          * not been migrated after it has been queued for deletion.
379          *
380          * At this stage, the record could still have been revived locally
381          * and last been written with empty data. This can only be
382          * fixed with the addition of an active or delete flag. (TODO)
383          */
384
385         lmaster = ctdb_lmaster(ctdb_db->ctdb, &dd->key);
386
387         if (lmaster != ctdb->pnn) {
388                 res = add_record_to_vacuum_fetch_list(vdata, dd->key);
389
390                 if (res != 0) {
391                         DEBUG(DEBUG_ERR,
392                               (__location__ " Error adding record to list "
393                                "of records to send to lmaster.\n"));
394                         vdata->fast_error++;
395                 } else {
396                         vdata->fast_added_to_vacuum_fetch_list++;
397                 }
398                 goto done;
399         }
400
401         /* use header->flags or dd->hdr.flags ?? */
402         if (dd->hdr.flags & CTDB_REC_FLAG_MIGRATED_WITH_DATA) {
403                 res = add_record_to_delete_list(vdata, dd->key, &dd->hdr);
404
405                 if (res != 0) {
406                         DEBUG(DEBUG_ERR,
407                               (__location__ " Error adding record to list "
408                                "of records for deletion on lmaster.\n"));
409                         vdata->fast_error++;
410                 } else {
411                         vdata->fast_added_to_delete_list++;
412                 }
413         } else {
414                 res = tdb_delete(ctdb_db->ltdb->tdb, dd->key);
415
416                 if (res != 0) {
417                         DEBUG(DEBUG_ERR,
418                               (__location__ " Error deleting record with key "
419                                "hash [0x%08x] from local data base db[%s].\n",
420                                hash, ctdb_db->db_name));
421                         vdata->fast_error++;
422                 } else {
423                         DEBUG(DEBUG_DEBUG,
424                               (__location__ " Deleted record with key hash "
425                                "[0x%08x] from local data base db[%s].\n",
426                                hash, ctdb_db->db_name));
427                         vdata->fast_deleted++;
428                 }
429         }
430
431         goto done;
432
433 skipped:
434         vdata->fast_skipped++;
435
436 done:
437         if (tdb_data.dptr != NULL) {
438                 free(tdb_data.dptr);
439         }
440         tdb_chainunlock(ctdb_db->ltdb->tdb, dd->key);
441
442         return 0;
443 }
444
445 /**
446  * Delete the records that we are lmaster and dmaster for and
447  * that could be deleted on all other nodes via the TRY_DELETE_RECORDS
448  * control.
449  */
450 static int delete_record_traverse(void *param, void *data)
451 {
452         struct delete_record_data *dd =
453                 talloc_get_type(data, struct delete_record_data);
454         struct vacuum_data *vdata = talloc_get_type(param, struct vacuum_data);
455         struct ctdb_db_context *ctdb_db = dd->ctdb_db;
456         struct ctdb_context *ctdb = ctdb_db->ctdb;
457         int res;
458         struct ctdb_ltdb_header *header;
459         TDB_DATA tdb_data;
460         uint32_t lmaster;
461         bool deleted = false;
462
463         res = tdb_chainlock(ctdb_db->ltdb->tdb, dd->key);
464         if (res != 0) {
465                 DEBUG(DEBUG_ERR, (__location__ " Error getting chainlock.\n"));
466                 vdata->delete_local_error++;
467                 return 0;
468         }
469
470         /*
471          * Verify that the record is still empty, its RSN has not
472          * changed and that we are still its lmaster and dmaster.
473          */
474
475         tdb_data = tdb_fetch(ctdb_db->ltdb->tdb, dd->key);
476         if (tdb_data.dsize < sizeof(struct ctdb_ltdb_header)) {
477                 /* Does not exist or not a ctdb record. Skip. */
478                 vdata->delete_skipped++;
479                 goto done;
480         }
481
482         if (tdb_data.dsize > sizeof(struct ctdb_ltdb_header)) {
483                 /* The record has been recycled (filled with data). Skip. */
484                 vdata->delete_skipped++;
485                 goto done;
486         }
487
488         header = (struct ctdb_ltdb_header *)tdb_data.dptr;
489
490         if (header->dmaster != ctdb->pnn) {
491                 /* The record has been migrated off the node. Skip. */
492                 vdata->delete_skipped++;
493                 goto done;
494         }
495
496
497         if (header->rsn != dd->hdr.rsn) {
498                 /*
499                  * The record has been migrated off the node and back again.
500                  * But not requeued for deletion. Skip it.
501                  */
502                 vdata->delete_skipped++;
503                 goto done;
504         }
505
506         lmaster = ctdb_lmaster(ctdb_db->ctdb, &dd->key);
507
508         if (lmaster != ctdb->pnn) {
509                 /* we are not lmaster - strange */
510                 vdata->delete_skipped++;
511                 goto done;
512         }
513
514         res = tdb_delete(ctdb_db->ltdb->tdb, dd->key);
515
516         if (res != 0) {
517                 DEBUG(DEBUG_ERR,
518                       (__location__ " Error deleting record from local "
519                        "data base.\n"));
520                 vdata->delete_local_error++;
521                 goto done;
522         }
523
524         deleted = true;
525
526 done:
527         if (tdb_data.dptr != NULL) {
528                 free(tdb_data.dptr);
529         }
530
531         tdb_chainunlock(ctdb_db->ltdb->tdb, dd->key);
532
533         if (deleted) {
534                 /*
535                  * successfully deleted the record locally.
536                  * remove it from the list and update statistics.
537                  */
538                 talloc_free(dd);
539                 vdata->delete_deleted++;
540                 vdata->delete_left--;
541         }
542
543         return 0;
544 }
545
546 /**
547  * Fast vacuuming run:
548  * Traverse the delete_queue.
549  * This fills the same lists as the database traverse.
550  */
551 static void ctdb_vacuum_db_fast(struct ctdb_db_context *ctdb_db,
552                                 struct vacuum_data *vdata)
553 {
554         trbt_traversearray32(ctdb_db->delete_queue, 1, delete_queue_traverse, vdata);
555
556         if (vdata->fast_total > 0) {
557                 DEBUG(DEBUG_INFO,
558                       (__location__
559                        " fast vacuuming delete_queue traverse statistics: "
560                        "db[%s] "
561                        "total[%u] "
562                        "del[%u] "
563                        "skp[%u] "
564                        "err[%u] "
565                        "adl[%u] "
566                        "avf[%u]\n",
567                        ctdb_db->db_name,
568                        (unsigned)vdata->fast_total,
569                        (unsigned)vdata->fast_deleted,
570                        (unsigned)vdata->fast_skipped,
571                        (unsigned)vdata->fast_error,
572                        (unsigned)vdata->fast_added_to_delete_list,
573                        (unsigned)vdata->fast_added_to_vacuum_fetch_list));
574         }
575
576         return;
577 }
578
579 /**
580  * Full vacuum run:
581  * read-only traverse of the database, looking for records that
582  * might be able to be vacuumed.
583  *
584  * This is not done each time but only every tunable
585  * VacuumFastPathCount times.
586  */
587 static int ctdb_vacuum_db_full(struct ctdb_db_context *ctdb_db,
588                                struct vacuum_data *vdata,
589                                bool full_vacuum_run)
590 {
591         int ret;
592
593         if (!full_vacuum_run) {
594                 return 0;
595         }
596
597         ret = tdb_traverse_read(ctdb_db->ltdb->tdb, vacuum_traverse, vdata);
598         if (ret == -1 || vdata->traverse_error) {
599                 DEBUG(DEBUG_ERR, (__location__ " Traverse error in vacuuming "
600                                   "'%s'\n", ctdb_db->db_name));
601                 return -1;
602         }
603
604         if (vdata->full_total > 0) {
605                 DEBUG(DEBUG_INFO,
606                       (__location__
607                        " full vacuuming db traverse statistics: "
608                        "db[%s] "
609                        "total[%u] "
610                        "skp[%u] "
611                        "err[%u] "
612                        "adl[%u] "
613                        "avf[%u]\n",
614                        ctdb_db->db_name,
615                        (unsigned)vdata->full_total,
616                        (unsigned)vdata->full_skipped,
617                        (unsigned)vdata->full_error,
618                        (unsigned)vdata->full_added_to_delete_list,
619                        (unsigned)vdata->full_added_to_vacuum_fetch_list));
620         }
621
622         return 0;
623 }
624
625 /**
626  * Process the vacuum fetch lists:
627  * For records for which we are not the lmaster, tell the lmaster to
628  * fetch the record.
629  */
630 static int ctdb_process_vacuum_fetch_lists(struct ctdb_db_context *ctdb_db,
631                                            struct vacuum_data *vdata)
632 {
633         int i;
634         struct ctdb_context *ctdb = ctdb_db->ctdb;
635
636         for (i = 0; i < ctdb->num_nodes; i++) {
637                 TDB_DATA data;
638                 struct ctdb_marshall_buffer *vfl = vdata->vacuum_fetch_list[i];
639
640                 if (ctdb->nodes[i]->pnn == ctdb->pnn) {
641                         continue;
642                 }
643
644                 if (vfl->count == 0) {
645                         continue;
646                 }
647
648                 DEBUG(DEBUG_INFO, ("Found %u records for lmaster %u in '%s'\n",
649                                    vfl->count, ctdb->nodes[i]->pnn,
650                                    ctdb_db->db_name));
651
652                 data.dsize = talloc_get_size(vfl);
653                 data.dptr  = (void *)vfl;
654                 if (ctdb_send_message(ctdb, ctdb->nodes[i]->pnn,
655                                       CTDB_SRVID_VACUUM_FETCH,
656                                       data) != 0)
657                 {
658                         DEBUG(DEBUG_ERR, (__location__ " Failed to send vacuum "
659                                           "fetch message to %u\n",
660                                           ctdb->nodes[i]->pnn));
661                         return -1;
662                 }
663         }
664
665         return 0;
666 }
667
668 /**
669  * Proces the delete list:
670  * Send the records to delete to all other nodes with the
671  * try_delete_records control.
672  */
673 static int ctdb_process_delete_list(struct ctdb_db_context *ctdb_db,
674                                     struct vacuum_data *vdata)
675 {
676         int ret, i;
677         struct ctdb_context *ctdb = ctdb_db->ctdb;
678
679         vdata->delete_left = vdata->delete_count;
680
681         if (vdata->delete_count > 0) {
682                 struct delete_records_list *recs;
683                 TDB_DATA indata, outdata;
684                 int32_t res;
685                 struct ctdb_node_map *nodemap;
686                 uint32_t *active_nodes;
687                 int num_active_nodes;
688
689                 recs = talloc_zero(vdata, struct delete_records_list);
690                 if (recs == NULL) {
691                         DEBUG(DEBUG_ERR,(__location__ " Out of memory\n"));
692                         return -1;
693                 }
694                 recs->records = (struct ctdb_marshall_buffer *)
695                         talloc_zero_size(vdata,
696                                     offsetof(struct ctdb_marshall_buffer, data));
697                 if (recs->records == NULL) {
698                         DEBUG(DEBUG_ERR,(__location__ " Out of memory\n"));
699                         return -1;
700                 }
701                 recs->records->db_id = ctdb_db->db_id;
702
703                 /*
704                  * traverse the tree of all records we want to delete and
705                  * create a blob we can send to the other nodes.
706                  */
707                 trbt_traversearray32(vdata->delete_list, 1,
708                                      delete_marshall_traverse, recs);
709
710                 indata.dsize = talloc_get_size(recs->records);
711                 indata.dptr  = (void *)recs->records;
712
713                 /*
714                  * now tell all the active nodes to delete all these records
715                  * (if possible)
716                  */
717
718                 ret = ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(),
719                                            CTDB_CURRENT_NODE,
720                                            recs, /* talloc context */
721                                            &nodemap);
722                 if (ret != 0) {
723                         DEBUG(DEBUG_ERR,(__location__ " unable to get node map\n"));
724                         return -1;
725                 }
726
727                 active_nodes = list_of_active_nodes(ctdb, nodemap,
728                                                     nodemap, /* talloc context */
729                                                     false /* include self */);
730                 /* yuck! ;-) */
731                 num_active_nodes = talloc_get_size(active_nodes)/sizeof(*active_nodes);
732
733                 for (i = 0; i < num_active_nodes; i++) {
734                         struct ctdb_marshall_buffer *records;
735                         struct ctdb_rec_data *rec;
736
737                         ret = ctdb_control(ctdb, active_nodes[i], 0,
738                                         CTDB_CONTROL_TRY_DELETE_RECORDS, 0,
739                                         indata, recs, &outdata, &res,
740                                         NULL, NULL);
741                         if (ret != 0 || res != 0) {
742                                 DEBUG(DEBUG_ERR, ("Failed to delete records on "
743                                                   "node %u: ret[%d] res[%d]\n",
744                                                   active_nodes[i], ret, res));
745                                 return -1;
746                         }
747
748                         /*
749                          * outdata contains the list of records coming back
750                          * from the node: These are the records that the
751                          * remote node could not delete.
752                          *
753                          * NOTE: There is a problem here:
754                          *
755                          * When a node failed to delete the record, but
756                          * others succeeded, we may have created gaps in the
757                          * history of the record. Hence when a node dies, an
758                          * closed file handle might be resurrected or an open
759                          * file handle might be lost, leading to blocked access
760                          * or data corruption.
761                          *
762                          * TODO: This needs to be fixed!
763                          */
764                         records = (struct ctdb_marshall_buffer *)outdata.dptr;
765                         rec = (struct ctdb_rec_data *)&records->data[0];
766                         while (records->count-- > 1) {
767                                 TDB_DATA reckey, recdata;
768                                 struct ctdb_ltdb_header *rechdr;
769                                 struct delete_record_data *dd;
770
771                                 reckey.dptr = &rec->data[0];
772                                 reckey.dsize = rec->keylen;
773                                 recdata.dptr = &rec->data[reckey.dsize];
774                                 recdata.dsize = rec->datalen;
775
776                                 if (recdata.dsize < sizeof(struct ctdb_ltdb_header)) {
777                                         DEBUG(DEBUG_CRIT,(__location__ " bad ltdb record\n"));
778                                         return -1;
779                                 }
780                                 rechdr = (struct ctdb_ltdb_header *)recdata.dptr;
781                                 recdata.dptr += sizeof(*rechdr);
782                                 recdata.dsize -= sizeof(*rechdr);
783
784                                 dd = (struct delete_record_data *)trbt_lookup32(
785                                                 vdata->delete_list,
786                                                 (uint32_t)tdb_jenkins_hash(&reckey));
787                                 if (dd != NULL) {
788                                         /*
789                                          * The other node could not delete the
790                                          * record and it is the first node that
791                                          * failed. So we should remove it from
792                                          * the tree and update statistics.
793                                          */
794                                         talloc_free(dd);
795                                         vdata->delete_remote_error++;
796                                         vdata->delete_left--;
797                                 }
798
799                                 rec = (struct ctdb_rec_data *)(rec->length + (uint8_t *)rec);
800                         }
801                 }
802
803                 /* free nodemap and active_nodes */
804                 talloc_free(nodemap);
805         }
806
807         if (vdata->delete_left > 0) {
808                 /*
809                  * The only records remaining in the tree are those
810                  * records which all other nodes could successfully
811                  * delete, so we can safely delete them on the
812                  * lmaster as well.
813                  */
814                 trbt_traversearray32(vdata->delete_list, 1,
815                                      delete_record_traverse, vdata);
816         }
817
818         if (vdata->delete_count > 0) {
819                 DEBUG(DEBUG_INFO,
820                       (__location__
821                        " vacuum delete list statistics: "
822                        "db[%s] "
823                        "coll[%u] "
824                        "rem.err[%u] "
825                        "loc.err[%u] "
826                        "skip[%u] "
827                        "del[%u] "
828                        "left[%u]\n",
829                        ctdb_db->db_name,
830                        (unsigned)vdata->delete_count,
831                        (unsigned)vdata->delete_remote_error,
832                        (unsigned)vdata->delete_local_error,
833                        (unsigned)vdata->delete_skipped,
834                        (unsigned)vdata->delete_deleted,
835                        (unsigned)vdata->delete_left));
836         }
837
838         return 0;
839 }
840
841 /**
842  * initialize the vacuum_data
843  */
844 static int ctdb_vacuum_init_vacuum_data(struct ctdb_db_context *ctdb_db,
845                                         struct vacuum_data *vdata)
846 {
847         int i;
848         struct ctdb_context *ctdb = ctdb_db->ctdb;
849
850         vdata->fast_added_to_delete_list = 0;
851         vdata->fast_added_to_vacuum_fetch_list = 0;
852         vdata->fast_deleted = 0;
853         vdata->fast_skipped = 0;
854         vdata->fast_error = 0;
855         vdata->fast_total = 0;
856         vdata->full_added_to_delete_list = 0;
857         vdata->full_added_to_vacuum_fetch_list = 0;
858         vdata->full_skipped = 0;
859         vdata->full_error = 0;
860         vdata->full_total = 0;
861         vdata->delete_count = 0;
862         vdata->delete_left = 0;
863         vdata->delete_remote_error = 0;
864         vdata->delete_local_error = 0;
865         vdata->delete_skipped = 0;
866         vdata->delete_deleted = 0;
867
868         /* the list needs to be of length num_nodes */
869         vdata->vacuum_fetch_list = talloc_zero_array(vdata,
870                                                 struct ctdb_marshall_buffer *,
871                                                 ctdb->num_nodes);
872         if (vdata->vacuum_fetch_list == NULL) {
873                 DEBUG(DEBUG_ERR,(__location__ " Out of memory\n"));
874                 return -1;
875         }
876         for (i = 0; i < ctdb->num_nodes; i++) {
877                 vdata->vacuum_fetch_list[i] = (struct ctdb_marshall_buffer *)
878                         talloc_zero_size(vdata->vacuum_fetch_list,
879                                          offsetof(struct ctdb_marshall_buffer, data));
880                 if (vdata->vacuum_fetch_list[i] == NULL) {
881                         DEBUG(DEBUG_ERR,(__location__ " Out of memory\n"));
882                         return -1;
883                 }
884                 vdata->vacuum_fetch_list[i]->db_id = ctdb_db->db_id;
885         }
886
887         return 0;
888 }
889
890 /**
891  * Vacuum a DB:
892  *  - Always do the fast vacuuming run, which traverses
893  *    the in-memory delete queue: these records have been
894  *    scheduled for deletion.
895  *  - Only if explicitly requested, the database is traversed
896  *    in order to use the traditional heuristics on empty records
897  *    to trigger deletion.
898  *    This is done only every VacuumFastPathCount'th vacuuming run.
899  *
900  * The traverse runs fill two lists:
901  *
902  * - The delete_list:
903  *   This is the list of empty records the current
904  *   node is lmaster and dmaster for. These records are later
905  *   deleted first on other nodes and then locally.
906  *
907  *   The fast vacuuming run has a short cut for those records
908  *   that have never been migrated with data: these records
909  *   are immediately deleted locally, since they have left
910  *   no trace on other nodes.
911  *
912  * - The vacuum_fetch lists
913  *   (one for each other lmaster node):
914  *   The records in this list are sent for deletion to
915  *   their lmaster in a bulk VACUUM_FETCH message.
916  *
917  *   The lmaster then migrates all these records to itelf
918  *   so that they can be vacuumed there.
919  *
920  * This executes in the child context.
921  */
922 static int ctdb_vacuum_db(struct ctdb_db_context *ctdb_db,
923                           struct vacuum_data *vdata,
924                           bool full_vacuum_run)
925 {
926         struct ctdb_context *ctdb = ctdb_db->ctdb;
927         int ret, pnn;
928
929         DEBUG(DEBUG_INFO, (__location__ " Entering %s vacuum run for db "
930                            "%s db_id[0x%08x]\n",
931                            full_vacuum_run ? "full" : "fast",
932                            ctdb_db->db_name, ctdb_db->db_id));
933
934         ret = ctdb_ctrl_getvnnmap(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE, ctdb, &ctdb->vnn_map);
935         if (ret != 0) {
936                 DEBUG(DEBUG_ERR, ("Unable to get vnnmap from local node\n"));
937                 return ret;
938         }
939
940         pnn = ctdb_ctrl_getpnn(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE);
941         if (pnn == -1) {
942                 DEBUG(DEBUG_ERR, ("Unable to get pnn from local node\n"));
943                 return -1;
944         }
945
946         ctdb->pnn = pnn;
947
948         ret = ctdb_vacuum_init_vacuum_data(ctdb_db, vdata);
949         if (ret != 0) {
950                 return ret;
951         }
952
953         ctdb_vacuum_db_fast(ctdb_db, vdata);
954
955         ret = ctdb_vacuum_db_full(ctdb_db, vdata, full_vacuum_run);
956         if (ret != 0) {
957                 return ret;
958         }
959
960         ret = ctdb_process_vacuum_fetch_lists(ctdb_db, vdata);
961         if (ret != 0) {
962                 return ret;
963         }
964
965         ret = ctdb_process_delete_list(ctdb_db, vdata);
966         if (ret != 0) {
967                 return ret;
968         }
969
970         /* this ensures we run our event queue */
971         ctdb_ctrl_getpnn(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE);
972
973         return 0;
974 }
975
976
977 /*
978  * traverse function for repacking
979  */
980 static int repack_traverse(struct tdb_context *tdb, TDB_DATA key, TDB_DATA data, void *private)
981 {
982         struct vacuum_data *vdata = (struct vacuum_data *)private;
983
984         if (vdata->vacuum) {
985                 uint32_t hash = (uint32_t)tdb_jenkins_hash(&key);
986                 struct delete_record_data *kd;
987                 /*
988                  * check if we can ignore this record because it's in the delete_list
989                  */
990                 kd = (struct delete_record_data *)trbt_lookup32(vdata->delete_list, hash);
991                 /*
992                  * there might be hash collisions so we have to compare the keys here to be sure
993                  */
994                 if (kd && kd->key.dsize == key.dsize && memcmp(kd->key.dptr, key.dptr, key.dsize) == 0) {
995                         struct ctdb_ltdb_header *hdr = (struct ctdb_ltdb_header *)data.dptr;
996                         /*
997                          * we have to check if the record hasn't changed in the meantime in order to
998                          * savely remove it from the database
999                          */
1000                         if (data.dsize == sizeof(struct ctdb_ltdb_header) &&
1001                                 hdr->dmaster == kd->ctdb->pnn &&
1002                                 ctdb_lmaster(kd->ctdb, &(kd->key)) == kd->ctdb->pnn &&
1003                                 kd->hdr.rsn == hdr->rsn) {
1004                                 vdata->vacuumed++;
1005                                 return 0;
1006                         }
1007                 }
1008         }
1009         if (tdb_store(vdata->dest_db, key, data, TDB_INSERT) != 0) {
1010                 vdata->traverse_error = true;
1011                 return -1;
1012         }
1013         vdata->copied++;
1014         return 0;
1015 }
1016
1017 /*
1018  * repack a tdb
1019  */
1020 static int ctdb_repack_tdb(struct tdb_context *tdb, TALLOC_CTX *mem_ctx, struct vacuum_data *vdata)
1021 {
1022         struct tdb_context *tmp_db;
1023
1024         if (tdb_transaction_start(tdb) != 0) {
1025                 DEBUG(DEBUG_ERR,(__location__ " Failed to start transaction\n"));
1026                 return -1;
1027         }
1028
1029         tmp_db = tdb_open("tmpdb", tdb_hash_size(tdb),
1030                           TDB_INTERNAL|TDB_DISALLOW_NESTING,
1031                           O_RDWR|O_CREAT, 0);
1032         if (tmp_db == NULL) {
1033                 DEBUG(DEBUG_ERR,(__location__ " Failed to create tmp_db\n"));
1034                 tdb_transaction_cancel(tdb);
1035                 return -1;
1036         }
1037
1038         vdata->traverse_error = false;
1039         vdata->dest_db = tmp_db;
1040         vdata->vacuum = true;
1041         vdata->vacuumed = 0;
1042         vdata->copied = 0;
1043
1044         /*
1045          * repack and vacuum on-the-fly by not writing the records that are
1046          * no longer needed
1047          */
1048         if (tdb_traverse_read(tdb, repack_traverse, vdata) == -1) {
1049                 DEBUG(DEBUG_ERR,(__location__ " Failed to traverse copying out\n"));
1050                 tdb_transaction_cancel(tdb);
1051                 tdb_close(tmp_db);
1052                 return -1;              
1053         }
1054
1055         DEBUG(DEBUG_INFO,(__location__ " %u records vacuumed\n", vdata->vacuumed));
1056         
1057         if (vdata->traverse_error) {
1058                 DEBUG(DEBUG_ERR,(__location__ " Error during traversal\n"));
1059                 tdb_transaction_cancel(tdb);
1060                 tdb_close(tmp_db);
1061                 return -1;
1062         }
1063
1064         if (tdb_wipe_all(tdb) != 0) {
1065                 DEBUG(DEBUG_ERR,(__location__ " Failed to wipe database\n"));
1066                 tdb_transaction_cancel(tdb);
1067                 tdb_close(tmp_db);
1068                 return -1;
1069         }
1070
1071         vdata->traverse_error = false;
1072         vdata->dest_db = tdb;
1073         vdata->vacuum = false;
1074         vdata->copied = 0;
1075
1076         if (tdb_traverse_read(tmp_db, repack_traverse, vdata) == -1) {
1077                 DEBUG(DEBUG_ERR,(__location__ " Failed to traverse copying back\n"));
1078                 tdb_transaction_cancel(tdb);
1079                 tdb_close(tmp_db);
1080                 return -1;              
1081         }
1082
1083         if (vdata->traverse_error) {
1084                 DEBUG(DEBUG_ERR,(__location__ " Error during second traversal\n"));
1085                 tdb_transaction_cancel(tdb);
1086                 tdb_close(tmp_db);
1087                 return -1;
1088         }
1089
1090         tdb_close(tmp_db);
1091
1092
1093         if (tdb_transaction_commit(tdb) != 0) {
1094                 DEBUG(DEBUG_ERR,(__location__ " Failed to commit\n"));
1095                 return -1;
1096         }
1097         DEBUG(DEBUG_INFO,(__location__ " %u records copied\n", vdata->copied));
1098
1099         return 0;
1100 }
1101
1102 /*
1103  * repack and vaccum a db
1104  * called from the child context
1105  */
1106 static int ctdb_vacuum_and_repack_db(struct ctdb_db_context *ctdb_db,
1107                                      TALLOC_CTX *mem_ctx,
1108                                      bool full_vacuum_run)
1109 {
1110         uint32_t repack_limit = ctdb_db->ctdb->tunable.repack_limit;
1111         uint32_t vacuum_limit = ctdb_db->ctdb->tunable.vacuum_limit;
1112         const char *name = ctdb_db->db_name;
1113         int freelist_size;
1114         struct vacuum_data *vdata;
1115
1116         freelist_size = tdb_freelist_size(ctdb_db->ltdb->tdb);
1117         if (freelist_size == -1) {
1118                 DEBUG(DEBUG_ERR,(__location__ " Failed to get freelist size for '%s'\n", name));
1119                 return -1;
1120         }
1121
1122         vdata = talloc_zero(mem_ctx, struct vacuum_data);
1123         if (vdata == NULL) {
1124                 DEBUG(DEBUG_ERR,(__location__ " Out of memory\n"));
1125                 return -1;
1126         }
1127
1128         vdata->ctdb = ctdb_db->ctdb;
1129         vdata->vacuum_limit = vacuum_limit;
1130         vdata->repack_limit = repack_limit;
1131         vdata->delete_list = trbt_create(vdata, 0);
1132         vdata->ctdb_db = ctdb_db;
1133         if (vdata->delete_list == NULL) {
1134                 DEBUG(DEBUG_ERR,(__location__ " Out of memory\n"));
1135                 talloc_free(vdata);
1136                 return -1;
1137         }
1138
1139         vdata->start = timeval_current();
1140  
1141         /*
1142          * gather all records that can be deleted in vdata
1143          */
1144         if (ctdb_vacuum_db(ctdb_db, vdata, full_vacuum_run) != 0) {
1145                 DEBUG(DEBUG_ERR,(__location__ " Failed to vacuum '%s'\n", name));
1146         }
1147
1148         /*
1149          * decide if a repack is necessary
1150          */
1151         if (freelist_size < repack_limit && vdata->delete_left < vacuum_limit)
1152         {
1153                 talloc_free(vdata);
1154                 return 0;
1155         }
1156
1157         DEBUG(DEBUG_INFO,("Repacking %s with %u freelist entries and %u records to delete\n", 
1158                         name, freelist_size, vdata->delete_left));
1159
1160         /*
1161          * repack and implicitely get rid of the records we can delete
1162          */
1163         if (ctdb_repack_tdb(ctdb_db->ltdb->tdb, mem_ctx, vdata) != 0) {
1164                 DEBUG(DEBUG_ERR,(__location__ " Failed to repack '%s'\n", name));
1165                 talloc_free(vdata);
1166                 return -1;
1167         }
1168         talloc_free(vdata);
1169
1170         return 0;
1171 }
1172
1173 static uint32_t get_vacuum_interval(struct ctdb_db_context *ctdb_db)
1174 {
1175         uint32_t interval = ctdb_db->ctdb->tunable.vacuum_interval;
1176
1177         return interval;
1178 }
1179
1180 static int vacuum_child_destructor(struct ctdb_vacuum_child_context *child_ctx)
1181 {
1182         double l = timeval_elapsed(&child_ctx->start_time);
1183         struct ctdb_db_context *ctdb_db = child_ctx->vacuum_handle->ctdb_db;
1184         struct ctdb_context *ctdb = ctdb_db->ctdb;
1185
1186         DEBUG(DEBUG_INFO,("Vacuuming took %.3f seconds for database %s\n", l, ctdb_db->db_name));
1187
1188         if (child_ctx->child_pid != -1) {
1189                 kill(child_ctx->child_pid, SIGKILL);
1190         } else {
1191                 /* Bump the number of successful fast-path runs. */
1192                 child_ctx->vacuum_handle->fast_path_count++;
1193         }
1194
1195         DLIST_REMOVE(ctdb->vacuumers, child_ctx);
1196
1197         event_add_timed(ctdb->ev, child_ctx->vacuum_handle,
1198                         timeval_current_ofs(get_vacuum_interval(ctdb_db), 0), 
1199                         ctdb_vacuum_event, child_ctx->vacuum_handle);
1200
1201         return 0;
1202 }
1203
1204 /*
1205  * this event is generated when a vacuum child process times out
1206  */
1207 static void vacuum_child_timeout(struct event_context *ev, struct timed_event *te,
1208                                          struct timeval t, void *private_data)
1209 {
1210         struct ctdb_vacuum_child_context *child_ctx = talloc_get_type(private_data, struct ctdb_vacuum_child_context);
1211
1212         DEBUG(DEBUG_ERR,("Vacuuming child process timed out for db %s\n", child_ctx->vacuum_handle->ctdb_db->db_name));
1213
1214         child_ctx->status = VACUUM_TIMEOUT;
1215
1216         talloc_free(child_ctx);
1217 }
1218
1219
1220 /*
1221  * this event is generated when a vacuum child process has completed
1222  */
1223 static void vacuum_child_handler(struct event_context *ev, struct fd_event *fde,
1224                              uint16_t flags, void *private_data)
1225 {
1226         struct ctdb_vacuum_child_context *child_ctx = talloc_get_type(private_data, struct ctdb_vacuum_child_context);
1227         char c = 0;
1228         int ret;
1229
1230         DEBUG(DEBUG_INFO,("Vacuuming child process %d finished for db %s\n", child_ctx->child_pid, child_ctx->vacuum_handle->ctdb_db->db_name));
1231         child_ctx->child_pid = -1;
1232
1233         ret = read(child_ctx->fd[0], &c, 1);
1234         if (ret != 1 || c != 0) {
1235                 child_ctx->status = VACUUM_ERROR;
1236                 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));
1237         } else {
1238                 child_ctx->status = VACUUM_OK;
1239         }
1240
1241         talloc_free(child_ctx);
1242 }
1243
1244 /*
1245  * this event is called every time we need to start a new vacuum process
1246  */
1247 static void
1248 ctdb_vacuum_event(struct event_context *ev, struct timed_event *te,
1249                                struct timeval t, void *private_data)
1250 {
1251         struct ctdb_vacuum_handle *vacuum_handle = talloc_get_type(private_data, struct ctdb_vacuum_handle);
1252         struct ctdb_db_context *ctdb_db = vacuum_handle->ctdb_db;
1253         struct ctdb_context *ctdb = ctdb_db->ctdb;
1254         struct ctdb_vacuum_child_context *child_ctx;
1255         int ret;
1256
1257         /* we dont vacuum if we are in recovery mode, or db frozen */
1258         if (ctdb->recovery_mode == CTDB_RECOVERY_ACTIVE ||
1259             ctdb->freeze_mode[ctdb_db->priority] != CTDB_FREEZE_NONE) {
1260                 DEBUG(DEBUG_INFO, ("Not vacuuming %s (%s)\n", ctdb_db->db_name,
1261                                    ctdb->recovery_mode == CTDB_RECOVERY_ACTIVE ? "in recovery"
1262                                    : ctdb->freeze_mode[ctdb_db->priority] == CTDB_FREEZE_PENDING
1263                                    ? "freeze pending"
1264                                    : "frozen"));
1265                 event_add_timed(ctdb->ev, vacuum_handle,
1266                         timeval_current_ofs(get_vacuum_interval(ctdb_db), 0),
1267                         ctdb_vacuum_event, vacuum_handle);
1268                 return;
1269         }
1270
1271         child_ctx = talloc(vacuum_handle, struct ctdb_vacuum_child_context);
1272         if (child_ctx == NULL) {
1273                 DEBUG(DEBUG_CRIT, (__location__ " Failed to allocate child context for vacuuming of %s\n", ctdb_db->db_name));
1274                 ctdb_fatal(ctdb, "Out of memory when crating vacuum child context. Shutting down\n");
1275         }
1276
1277
1278         ret = pipe(child_ctx->fd);
1279         if (ret != 0) {
1280                 talloc_free(child_ctx);
1281                 DEBUG(DEBUG_ERR, ("Failed to create pipe for vacuum child process.\n"));
1282                 event_add_timed(ctdb->ev, vacuum_handle,
1283                         timeval_current_ofs(get_vacuum_interval(ctdb_db), 0),
1284                         ctdb_vacuum_event, vacuum_handle);
1285                 return;
1286         }
1287
1288         if (vacuum_handle->fast_path_count > ctdb->tunable.vacuum_fast_path_count) {
1289                 vacuum_handle->fast_path_count = 0;
1290         }
1291
1292         child_ctx->child_pid = fork();
1293         if (child_ctx->child_pid == (pid_t)-1) {
1294                 close(child_ctx->fd[0]);
1295                 close(child_ctx->fd[1]);
1296                 talloc_free(child_ctx);
1297                 DEBUG(DEBUG_ERR, ("Failed to fork vacuum child process.\n"));
1298                 event_add_timed(ctdb->ev, vacuum_handle,
1299                         timeval_current_ofs(get_vacuum_interval(ctdb_db), 0),
1300                         ctdb_vacuum_event, vacuum_handle);
1301                 return;
1302         }
1303
1304
1305         if (child_ctx->child_pid == 0) {
1306                 char cc = 0;
1307                 bool full_vacuum_run = false;
1308                 close(child_ctx->fd[0]);
1309
1310                 DEBUG(DEBUG_INFO,("Vacuuming child process %d for db %s started\n", getpid(), ctdb_db->db_name));
1311         
1312                 if (switch_from_server_to_client(ctdb) != 0) {
1313                         DEBUG(DEBUG_CRIT, (__location__ "ERROR: failed to switch vacuum daemon into client mode. Shutting down.\n"));
1314                         _exit(1);
1315                 }
1316
1317                 /* 
1318                  * repack the db
1319                  */
1320                 if ((ctdb->tunable.vacuum_fast_path_count > 0) &&
1321                     (vacuum_handle->fast_path_count == 0))
1322                 {
1323                         full_vacuum_run = true;
1324                 }
1325                 cc = ctdb_vacuum_and_repack_db(ctdb_db, child_ctx,
1326                                                full_vacuum_run);
1327
1328                 write(child_ctx->fd[1], &cc, 1);
1329                 _exit(0);
1330         }
1331
1332         set_close_on_exec(child_ctx->fd[0]);
1333         close(child_ctx->fd[1]);
1334
1335         child_ctx->status = VACUUM_RUNNING;
1336         child_ctx->start_time = timeval_current();
1337
1338         DLIST_ADD(ctdb->vacuumers, child_ctx);
1339         talloc_set_destructor(child_ctx, vacuum_child_destructor);
1340
1341         /*
1342          * Clear the fastpath vacuuming list in the parent.
1343          */
1344         talloc_free(ctdb_db->delete_queue);
1345         ctdb_db->delete_queue = trbt_create(ctdb_db, 0);
1346         if (ctdb_db->delete_queue == NULL) {
1347                 /* fatal here? ... */
1348                 ctdb_fatal(ctdb, "Out of memory when re-creating vacuum tree "
1349                                  "in parent context. Shutting down\n");
1350         }
1351
1352         event_add_timed(ctdb->ev, child_ctx,
1353                 timeval_current_ofs(ctdb->tunable.vacuum_max_run_time, 0),
1354                 vacuum_child_timeout, child_ctx);
1355
1356         DEBUG(DEBUG_DEBUG, (__location__ " Created PIPE FD:%d to child vacuum process\n", child_ctx->fd[0]));
1357
1358         event_add_fd(ctdb->ev, child_ctx, child_ctx->fd[0],
1359                 EVENT_FD_READ|EVENT_FD_AUTOCLOSE,
1360                 vacuum_child_handler,
1361                 child_ctx);
1362
1363         vacuum_handle->child_ctx = child_ctx;
1364         child_ctx->vacuum_handle = vacuum_handle;
1365 }
1366
1367 void ctdb_stop_vacuuming(struct ctdb_context *ctdb)
1368 {
1369         /* Simply free them all. */
1370         while (ctdb->vacuumers) {
1371                 DEBUG(DEBUG_INFO, ("Aborting vacuuming for %s (%i)\n",
1372                            ctdb->vacuumers->vacuum_handle->ctdb_db->db_name,
1373                            (int)ctdb->vacuumers->child_pid));
1374                 /* vacuum_child_destructor kills it, removes from list */
1375                 talloc_free(ctdb->vacuumers);
1376         }
1377 }
1378
1379 /* this function initializes the vacuuming context for a database
1380  * starts the vacuuming events
1381  */
1382 int ctdb_vacuum_init(struct ctdb_db_context *ctdb_db)
1383 {
1384         if (ctdb_db->persistent != 0) {
1385                 DEBUG(DEBUG_ERR,("Vacuuming is disabled for persistent database %s\n", ctdb_db->db_name));
1386                 return 0;
1387         }
1388
1389         ctdb_db->vacuum_handle = talloc(ctdb_db, struct ctdb_vacuum_handle);
1390         CTDB_NO_MEMORY(ctdb_db->ctdb, ctdb_db->vacuum_handle);
1391
1392         ctdb_db->vacuum_handle->ctdb_db         = ctdb_db;
1393         ctdb_db->vacuum_handle->fast_path_count = 0;
1394
1395         event_add_timed(ctdb_db->ctdb->ev, ctdb_db->vacuum_handle, 
1396                         timeval_current_ofs(get_vacuum_interval(ctdb_db), 0), 
1397                         ctdb_vacuum_event, ctdb_db->vacuum_handle);
1398
1399         return 0;
1400 }
1401
1402 static void remove_record_from_delete_queue(struct ctdb_db_context *ctdb_db,
1403                                             const struct ctdb_ltdb_header *hdr,
1404                                             const TDB_DATA key)
1405 {
1406         struct delete_record_data *kd;
1407         uint32_t hash;
1408
1409         hash = (uint32_t)tdb_jenkins_hash(discard_const(&key));
1410
1411         DEBUG(DEBUG_DEBUG, (__location__
1412                             " remove_record_from_delete_queue: db[%s] "
1413                             "db_id[0x%08x] "
1414                             "key_hash[0x%08x] "
1415                             "lmaster[%u] "
1416                             "migrated_with_data[%s]\n",
1417                              ctdb_db->db_name, ctdb_db->db_id,
1418                              hash,
1419                              ctdb_lmaster(ctdb_db->ctdb, &key),
1420                              hdr->flags & CTDB_REC_FLAG_MIGRATED_WITH_DATA ? "yes" : "no"));
1421
1422         kd = (struct delete_record_data *)trbt_lookup32(ctdb_db->delete_queue, hash);
1423         if (kd == NULL) {
1424                 return;
1425         }
1426         if (kd->key.dsize != key.dsize) {
1427                 return;
1428         }
1429         if (memcmp(kd->key.dptr, key.dptr, key.dsize) != 0) {
1430                 return;
1431         }
1432
1433         talloc_free(kd);
1434
1435         return;
1436 }
1437
1438 /**
1439  * Insert a record into the ctdb_db context's delete queue,
1440  * handling hash collisions.
1441  */
1442 static int insert_record_into_delete_queue(struct ctdb_db_context *ctdb_db,
1443                                            const struct ctdb_ltdb_header *hdr,
1444                                            TDB_DATA key)
1445 {
1446         struct delete_record_data *kd;
1447         uint32_t hash;
1448         int ret;
1449
1450         hash = (uint32_t)tdb_jenkins_hash(&key);
1451
1452         DEBUG(DEBUG_INFO, (__location__ " schedule for deletion: db[%s] "
1453                            "db_id[0x%08x] "
1454                            "key_hash[0x%08x] "
1455                            "lmaster[%u] "
1456                            "migrated_with_data[%s]\n",
1457                             ctdb_db->db_name, ctdb_db->db_id,
1458                             hash,
1459                             ctdb_lmaster(ctdb_db->ctdb, &key),
1460                             hdr->flags & CTDB_REC_FLAG_MIGRATED_WITH_DATA ? "yes" : "no"));
1461
1462         kd = (struct delete_record_data *)trbt_lookup32(ctdb_db->delete_queue, hash);
1463         if (kd != NULL) {
1464                 if ((kd->key.dsize != key.dsize) ||
1465                     (memcmp(kd->key.dptr, key.dptr, key.dsize) != 0))
1466                 {
1467                         DEBUG(DEBUG_INFO,
1468                               (__location__ " schedule for deletion: "
1469                                "hash collision (0x%08x)."
1470                                " Skipping the record.\n", hash));
1471                         return 0;
1472                 } else {
1473                         DEBUG(DEBUG_DEBUG,
1474                               (__location__ " schedule for deletion: "
1475                                "updating entry for key with hash 0x%08x.\n",
1476                                hash));
1477                 }
1478         }
1479
1480         ret = insert_delete_record_data_into_tree(ctdb_db->ctdb, ctdb_db,
1481                                                   ctdb_db->delete_queue,
1482                                                   hdr, key);
1483         if (ret != 0) {
1484                 DEBUG(DEBUG_INFO,
1485                       (__location__ " schedule for deletion: error "
1486                        "inserting key with hash 0x%08x into delete queue\n",
1487                        hash));
1488                 return -1;
1489         }
1490
1491         return 0;
1492 }
1493
1494 /**
1495  * Schedule a record for deletetion.
1496  * Called from the parent context.
1497  */
1498 int32_t ctdb_control_schedule_for_deletion(struct ctdb_context *ctdb,
1499                                            TDB_DATA indata)
1500 {
1501         struct ctdb_control_schedule_for_deletion *dd;
1502         struct ctdb_db_context *ctdb_db;
1503         int ret;
1504         TDB_DATA key;
1505
1506         dd = (struct ctdb_control_schedule_for_deletion *)indata.dptr;
1507
1508         ctdb_db = find_ctdb_db(ctdb, dd->db_id);
1509         if (ctdb_db == NULL) {
1510                 DEBUG(DEBUG_ERR, (__location__ " Unknown db id 0x%08x\n",
1511                                   dd->db_id));
1512                 return -1;
1513         }
1514
1515         key.dsize = dd->keylen;
1516         key.dptr = dd->key;
1517
1518         ret = insert_record_into_delete_queue(ctdb_db, &dd->hdr, key);
1519
1520         return ret;
1521 }
1522
1523 int32_t ctdb_local_schedule_for_deletion(struct ctdb_db_context *ctdb_db,
1524                                          const struct ctdb_ltdb_header *hdr,
1525                                          TDB_DATA key)
1526 {
1527         int ret;
1528         struct ctdb_control_schedule_for_deletion *dd;
1529         TDB_DATA indata;
1530         int32_t status;
1531
1532         if (ctdb_db->ctdb->ctdbd_pid == getpid()) {
1533                 /* main daemon - directly queue */
1534                 ret = insert_record_into_delete_queue(ctdb_db, hdr, key);
1535
1536                 return ret;
1537         }
1538
1539         /* child process: send the main daemon a control */
1540
1541         indata.dsize = offsetof(struct ctdb_control_schedule_for_deletion, key) + key.dsize;
1542         indata.dptr = talloc_zero_array(ctdb_db, uint8_t, indata.dsize);
1543         if (indata.dptr == NULL) {
1544                 DEBUG(DEBUG_ERR, (__location__ " out of memory\n"));
1545                 return -1;
1546         }
1547         dd = (struct ctdb_control_schedule_for_deletion *)(void *)indata.dptr;
1548         dd->db_id = ctdb_db->db_id;
1549         dd->hdr = *hdr;
1550         dd->keylen = key.dsize;
1551         memcpy(dd->key, key.dptr, key.dsize);
1552
1553         ret = ctdb_control(ctdb_db->ctdb,
1554                            CTDB_CURRENT_NODE,
1555                            ctdb_db->db_id,
1556                            CTDB_CONTROL_SCHEDULE_FOR_DELETION,
1557                            CTDB_CTRL_FLAG_NOREPLY, /* flags */
1558                            indata,
1559                            NULL, /* mem_ctx */
1560                            NULL, /* outdata */
1561                            &status,
1562                            NULL, /* timeout : NULL == wait forever */
1563                            NULL); /* error message */
1564
1565         talloc_free(indata.dptr);
1566
1567         if (ret != 0 || status != 0) {
1568                 DEBUG(DEBUG_ERR, (__location__ " Error sending "
1569                                   "SCHEDULE_FOR_DELETION "
1570                                   "control.\n"));
1571                 if (status != 0) {
1572                         ret = -1;
1573                 }
1574         }
1575
1576         return ret;
1577 }
1578
1579 void ctdb_local_remove_from_delete_queue(struct ctdb_db_context *ctdb_db,
1580                                          const struct ctdb_ltdb_header *hdr,
1581                                          const TDB_DATA key)
1582 {
1583         if (ctdb_db->ctdb->ctdbd_pid != getpid()) {
1584                 /*
1585                  * Only remove the record from the delete queue if called
1586                  * in the main daemon.
1587                  */
1588                 return;
1589         }
1590
1591         remove_record_from_delete_queue(ctdb_db, hdr, key);
1592
1593         return;
1594 }