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