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