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