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