vacuum: reorder some of ctdb_process_delete_list() more intuitively
[obnox/ctdb.git] / server / ctdb_vacuum.c
1 /*
2    ctdb vacuuming events
3
4    Copyright (C) Ronnie Sahlberg  2009
5    Copyright (C) Michael Adam 2010-2011
6    Copyright (C) Stefan Metzmacher 2010-2011
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program; if not, see <http://www.gnu.org/licenses/>.
20 */
21
22 #include "includes.h"
23 #include "lib/tdb/include/tdb.h"
24 #include "system/network.h"
25 #include "system/filesys.h"
26 #include "system/dir.h"
27 #include "../include/ctdb_private.h"
28 #include "db_wrap.h"
29 #include "lib/util/dlinklist.h"
30 #include "../include/ctdb_private.h"
31 #include "../common/rb_tree.h"
32
33 #define TIMELIMIT() timeval_current_ofs(10, 0)
34
35 enum vacuum_child_status { VACUUM_RUNNING, VACUUM_OK, VACUUM_ERROR, VACUUM_TIMEOUT};
36
37 struct ctdb_vacuum_child_context {
38         struct ctdb_vacuum_child_context *next, *prev;
39         struct ctdb_vacuum_handle *vacuum_handle;
40         /* fd child writes status to */
41         int fd[2];
42         pid_t child_pid;
43         enum vacuum_child_status status;
44         struct timeval start_time;
45 };
46
47 struct ctdb_vacuum_handle {
48         struct ctdb_db_context *ctdb_db;
49         struct ctdb_vacuum_child_context *child_ctx;
50         uint32_t fast_path_count;
51 };
52
53
54 /*  a list of records to possibly delete */
55 struct vacuum_data {
56         uint32_t vacuum_limit;
57         uint32_t repack_limit;
58         struct ctdb_context *ctdb;
59         struct ctdb_db_context *ctdb_db;
60         struct tdb_context *dest_db;
61         trbt_tree_t *delete_list;
62         uint32_t delete_count;
63         struct ctdb_marshall_buffer **vacuum_fetch_list;
64         struct timeval start;
65         bool traverse_error;
66         bool vacuum;
67         uint32_t total;
68         uint32_t vacuumed;
69         uint32_t copied;
70         uint32_t fast_added_to_vacuum_fetch_list;
71         uint32_t fast_added_to_delete_list;
72         uint32_t fast_deleted;
73         uint32_t fast_skipped;
74         uint32_t fast_error;
75         uint32_t fast_total;
76         uint32_t full_added_to_vacuum_fetch_list;
77         uint32_t full_added_to_delete_list;
78         uint32_t full_skipped;
79         uint32_t full_error;
80         uint32_t full_total;
81         uint32_t delete_left;
82         uint32_t delete_remote_error;
83         uint32_t delete_local_error;
84         uint32_t delete_deleted;
85         uint32_t delete_skipped;
86 };
87
88 /* this structure contains the information for one record to be deleted */
89 struct delete_record_data {
90         struct ctdb_context *ctdb;
91         struct ctdb_db_context *ctdb_db;
92         struct ctdb_ltdb_header hdr;
93         TDB_DATA key;
94         uint8_t keydata[1];
95 };
96
97 struct delete_records_list {
98         struct ctdb_marshall_buffer *records;
99 };
100
101 /**
102  * Store key and header in a tree, indexed by the key hash.
103  */
104 static int insert_delete_record_data_into_tree(struct ctdb_context *ctdb,
105                                                struct ctdb_db_context *ctdb_db,
106                                                trbt_tree_t *tree,
107                                                const struct ctdb_ltdb_header *hdr,
108                                                TDB_DATA key)
109 {
110         struct delete_record_data *dd;
111         uint32_t hash;
112         size_t len;
113
114         len = offsetof(struct delete_record_data, keydata) + key.dsize;
115
116         dd = (struct delete_record_data *)talloc_size(tree, len);
117         if (dd == NULL) {
118                 DEBUG(DEBUG_ERR,(__location__ " Out of memory\n"));
119                 return -1;
120         }
121         talloc_set_name_const(dd, "struct delete_record_data");
122
123         dd->ctdb      = ctdb;
124         dd->ctdb_db   = ctdb_db;
125         dd->key.dsize = key.dsize;
126         dd->key.dptr  = dd->keydata;
127         memcpy(dd->keydata, key.dptr, key.dsize);
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                 DEBUG(DEBUG_ERR, (__location__ ": record with hash [0x%08x] "
482                                   "on database db[%s] does not exist or is not "
483                                   "a ctdb-record.  skipping.\n",
484                                   hash, ctdb_db->db_name));
485                 vdata->delete_skipped++;
486                 goto done;
487         }
488
489         if (tdb_data.dsize > sizeof(struct ctdb_ltdb_header)) {
490                 DEBUG(DEBUG_ERR, (__location__ ": record with hash [0x%08x] "
491                                   "on database db[%s] has been recycled. "
492                                   "skipping.\n",
493                                   hash, ctdb_db->db_name));
494                 vdata->delete_skipped++;
495                 goto done;
496         }
497
498         header = (struct ctdb_ltdb_header *)tdb_data.dptr;
499
500         if (header->flags & (CTDB_REC_RO_HAVE_DELEGATIONS|
501                              CTDB_REC_RO_HAVE_READONLY|
502                              CTDB_REC_RO_REVOKING_READONLY|
503                              CTDB_REC_RO_REVOKE_COMPLETE))
504         {
505                 DEBUG(DEBUG_ERR, (__location__ ": record with hash [0x%08x] "
506                                   "on database db[%s] has read-only flags. "
507                                   "skipping.\n",
508                                   hash, ctdb_db->db_name));
509                 vdata->delete_skipped++;
510                 goto done;
511         }
512
513         if (header->dmaster != ctdb->pnn) {
514                 DEBUG(DEBUG_ERR, (__location__ ": record with hash [0x%08x] "
515                                   "on database db[%s] has been migrated away. "
516                                   "skipping.\n",
517                                   hash, ctdb_db->db_name));
518                 vdata->delete_skipped++;
519                 goto done;
520         }
521
522
523         if (header->rsn != dd->hdr.rsn) {
524                 /*
525                  * The record has been migrated off the node and back again.
526                  * But not requeued for deletion. Skip it.
527                  */
528                 DEBUG(DEBUG_ERR, (__location__ ": record with hash [0x%08x] "
529                                   "on database db[%s] seems to have been "
530                                   "migrated away and back again (with empty "
531                                   "data). skipping.\n",
532                                   hash, ctdb_db->db_name));
533                 vdata->delete_skipped++;
534                 goto done;
535         }
536
537         lmaster = ctdb_lmaster(ctdb_db->ctdb, &dd->key);
538
539         if (lmaster != ctdb->pnn) {
540                 DEBUG(DEBUG_ERR, (__location__ ": not lmaster for record in "
541                                   "delete list (key hash [0x%08x], db[%s]). "
542                                   "Strange! skipping.\n",
543                                   hash, ctdb_db->db_name));
544                 vdata->delete_skipped++;
545                 goto done;
546         }
547
548         res = tdb_delete(ctdb_db->ltdb->tdb, dd->key);
549
550         if (res != 0) {
551                 DEBUG(DEBUG_ERR,
552                       (__location__ " Error deleting record with key hash "
553                        "[0x%08x] from local data base db[%s].\n",
554                        hash, ctdb_db->db_name));
555                 vdata->delete_local_error++;
556                 goto done;
557         }
558
559         deleted = true;
560
561         DEBUG(DEBUG_DEBUG,
562               (__location__ " Deleted record with key hash [0x%08x] from "
563                "local data base db[%s].\n", hash, ctdb_db->db_name));
564
565 done:
566         if (tdb_data.dptr != NULL) {
567                 free(tdb_data.dptr);
568         }
569
570         tdb_chainunlock(ctdb_db->ltdb->tdb, dd->key);
571
572         if (deleted) {
573                 /*
574                  * successfully deleted the record locally.
575                  * remove it from the list and update statistics.
576                  */
577                 talloc_free(dd);
578                 vdata->delete_deleted++;
579                 vdata->delete_left--;
580         }
581
582         return 0;
583 }
584
585 /**
586  * Fast vacuuming run:
587  * Traverse the delete_queue.
588  * This fills the same lists as the database traverse.
589  */
590 static void ctdb_vacuum_db_fast(struct ctdb_db_context *ctdb_db,
591                                 struct vacuum_data *vdata)
592 {
593         trbt_traversearray32(ctdb_db->delete_queue, 1, delete_queue_traverse, vdata);
594
595         if (vdata->fast_total > 0) {
596                 DEBUG(DEBUG_INFO,
597                       (__location__
598                        " fast vacuuming delete_queue traverse statistics: "
599                        "db[%s] "
600                        "total[%u] "
601                        "del[%u] "
602                        "skp[%u] "
603                        "err[%u] "
604                        "adl[%u] "
605                        "avf[%u]\n",
606                        ctdb_db->db_name,
607                        (unsigned)vdata->fast_total,
608                        (unsigned)vdata->fast_deleted,
609                        (unsigned)vdata->fast_skipped,
610                        (unsigned)vdata->fast_error,
611                        (unsigned)vdata->fast_added_to_delete_list,
612                        (unsigned)vdata->fast_added_to_vacuum_fetch_list));
613         }
614
615         return;
616 }
617
618 /**
619  * Full vacuum run:
620  * read-only traverse of the database, looking for records that
621  * might be able to be vacuumed.
622  *
623  * This is not done each time but only every tunable
624  * VacuumFastPathCount times.
625  */
626 static int ctdb_vacuum_db_full(struct ctdb_db_context *ctdb_db,
627                                struct vacuum_data *vdata,
628                                bool full_vacuum_run)
629 {
630         int ret;
631
632         if (!full_vacuum_run) {
633                 return 0;
634         }
635
636         ret = tdb_traverse_read(ctdb_db->ltdb->tdb, vacuum_traverse, vdata);
637         if (ret == -1 || vdata->traverse_error) {
638                 DEBUG(DEBUG_ERR, (__location__ " Traverse error in vacuuming "
639                                   "'%s'\n", ctdb_db->db_name));
640                 return -1;
641         }
642
643         if (vdata->full_total > 0) {
644                 DEBUG(DEBUG_INFO,
645                       (__location__
646                        " full vacuuming db traverse statistics: "
647                        "db[%s] "
648                        "total[%u] "
649                        "skp[%u] "
650                        "err[%u] "
651                        "adl[%u] "
652                        "avf[%u]\n",
653                        ctdb_db->db_name,
654                        (unsigned)vdata->full_total,
655                        (unsigned)vdata->full_skipped,
656                        (unsigned)vdata->full_error,
657                        (unsigned)vdata->full_added_to_delete_list,
658                        (unsigned)vdata->full_added_to_vacuum_fetch_list));
659         }
660
661         return 0;
662 }
663
664 /**
665  * Process the vacuum fetch lists:
666  * For records for which we are not the lmaster, tell the lmaster to
667  * fetch the record.
668  */
669 static int ctdb_process_vacuum_fetch_lists(struct ctdb_db_context *ctdb_db,
670                                            struct vacuum_data *vdata)
671 {
672         int i;
673         struct ctdb_context *ctdb = ctdb_db->ctdb;
674
675         for (i = 0; i < ctdb->num_nodes; i++) {
676                 TDB_DATA data;
677                 struct ctdb_marshall_buffer *vfl = vdata->vacuum_fetch_list[i];
678
679                 if (ctdb->nodes[i]->pnn == ctdb->pnn) {
680                         continue;
681                 }
682
683                 if (vfl->count == 0) {
684                         continue;
685                 }
686
687                 DEBUG(DEBUG_INFO, ("Found %u records for lmaster %u in '%s'\n",
688                                    vfl->count, ctdb->nodes[i]->pnn,
689                                    ctdb_db->db_name));
690
691                 data.dsize = talloc_get_size(vfl);
692                 data.dptr  = (void *)vfl;
693                 if (ctdb_client_send_message(ctdb, ctdb->nodes[i]->pnn,
694                                              CTDB_SRVID_VACUUM_FETCH,
695                                              data) != 0)
696                 {
697                         DEBUG(DEBUG_ERR, (__location__ " Failed to send vacuum "
698                                           "fetch message to %u\n",
699                                           ctdb->nodes[i]->pnn));
700                         return -1;
701                 }
702         }
703
704         return 0;
705 }
706
707 /**
708  * Process the delete list:
709  * Send the records to delete to all other nodes with the
710  * try_delete_records control.
711  */
712 static int ctdb_process_delete_list(struct ctdb_db_context *ctdb_db,
713                                     struct vacuum_data *vdata)
714 {
715         int ret, i;
716         struct ctdb_context *ctdb = ctdb_db->ctdb;
717         struct delete_records_list *recs;
718         TDB_DATA indata;
719         struct ctdb_node_map *nodemap;
720         uint32_t *active_nodes;
721         int num_active_nodes;
722         TALLOC_CTX *tmp_ctx;
723
724         if (vdata->delete_count == 0) {
725                 return 0;
726         }
727
728         tmp_ctx = talloc_new(vdata);
729         if (tmp_ctx == NULL) {
730                 DEBUG(DEBUG_ERR,(__location__ " Out of memory\n"));
731                 return 0;
732         }
733
734         vdata->delete_left = vdata->delete_count;
735
736         /*
737          * now tell all the active nodes to delete all these records
738          * (if possible)
739          */
740
741         ret = ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(),
742                                    CTDB_CURRENT_NODE,
743                                    tmp_ctx,
744                                    &nodemap);
745         if (ret != 0) {
746                 DEBUG(DEBUG_ERR,(__location__ " unable to get node map\n"));
747                 ret = -1;
748                 goto done;
749         }
750
751         active_nodes = list_of_active_nodes(ctdb, nodemap,
752                                             nodemap, /* talloc context */
753                                             false /* include self */);
754         /* yuck! ;-) */
755         num_active_nodes = talloc_get_size(active_nodes)/sizeof(*active_nodes);
756
757         recs = talloc_zero(tmp_ctx, struct delete_records_list);
758         if (recs == NULL) {
759                 DEBUG(DEBUG_ERR,(__location__ " Out of memory\n"));
760                 ret = -1;
761                 goto done;
762         }
763         recs->records = (struct ctdb_marshall_buffer *)
764                 talloc_zero_size(recs,
765                                  offsetof(struct ctdb_marshall_buffer, data));
766         if (recs->records == NULL) {
767                 DEBUG(DEBUG_ERR,(__location__ " Out of memory\n"));
768                 ret = -1;
769                 goto done;
770         }
771         recs->records->db_id = ctdb_db->db_id;
772
773         /*
774          * traverse the tree of all records we want to delete and
775          * create a blob we can send to the other nodes.
776          */
777         trbt_traversearray32(vdata->delete_list, 1,
778                              delete_marshall_traverse, recs);
779
780         indata.dsize = talloc_get_size(recs->records);
781         indata.dptr  = (void *)recs->records;
782
783         for (i = 0; i < num_active_nodes; i++) {
784                 struct ctdb_marshall_buffer *records;
785                 struct ctdb_rec_data *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                         ret = -1;
798                         goto done;
799                 }
800
801                 /*
802                  * outdata contains the list of records coming back
803                  * from the node: These are the records that the
804                  * remote node could not delete.
805                  *
806                  * NOTE: There is a problem here:
807                  *
808                  * When a node failed to delete the record, but
809                  * others succeeded, we may have created gaps in the
810                  * history of the record. Hence when a node dies, an
811                  * closed file handle might be resurrected or an open
812                  * file handle might be lost, leading to blocked access
813                  * or data corruption.
814                  *
815                  * TODO: This needs to be fixed!
816                  */
817                 records = (struct ctdb_marshall_buffer *)outdata.dptr;
818                 rec = (struct ctdb_rec_data *)&records->data[0];
819                 while (records->count-- > 1) {
820                         TDB_DATA reckey, recdata;
821                         struct ctdb_ltdb_header *rechdr;
822                         struct delete_record_data *dd;
823
824                         reckey.dptr = &rec->data[0];
825                         reckey.dsize = rec->keylen;
826                         recdata.dptr = &rec->data[reckey.dsize];
827                         recdata.dsize = rec->datalen;
828
829                         if (recdata.dsize < sizeof(struct ctdb_ltdb_header)) {
830                                 DEBUG(DEBUG_CRIT,(__location__ " bad ltdb record\n"));
831                                 ret = -1;
832                                 goto done;
833                         }
834                         rechdr = (struct ctdb_ltdb_header *)recdata.dptr;
835                         recdata.dptr += sizeof(*rechdr);
836                         recdata.dsize -= sizeof(*rechdr);
837
838                         dd = (struct delete_record_data *)trbt_lookup32(
839                                         vdata->delete_list,
840                                         ctdb_hash(&reckey));
841                         if (dd != NULL) {
842                                 /*
843                                  * The other node could not delete the
844                                  * record and it is the first node that
845                                  * failed. So we should remove it from
846                                  * the tree and update statistics.
847                                  */
848                                 talloc_free(dd);
849                                 vdata->delete_remote_error++;
850                                 vdata->delete_left--;
851                         }
852
853                         rec = (struct ctdb_rec_data *)(rec->length + (uint8_t *)rec);
854                 }
855         }
856
857         if (vdata->delete_left > 0) {
858                 /*
859                  * The only records remaining in the tree are those
860                  * records which all other nodes could successfully
861                  * delete, so we can safely delete them on the
862                  * lmaster as well.
863                  */
864                 trbt_traversearray32(vdata->delete_list, 1,
865                                      delete_record_traverse, vdata);
866         }
867
868         if (vdata->delete_count > 0) {
869                 DEBUG(DEBUG_INFO,
870                       (__location__
871                        " vacuum delete list statistics: "
872                        "db[%s] "
873                        "coll[%u] "
874                        "rem.err[%u] "
875                        "loc.err[%u] "
876                        "skip[%u] "
877                        "del[%u] "
878                        "left[%u]\n",
879                        ctdb_db->db_name,
880                        (unsigned)vdata->delete_count,
881                        (unsigned)vdata->delete_remote_error,
882                        (unsigned)vdata->delete_local_error,
883                        (unsigned)vdata->delete_skipped,
884                        (unsigned)vdata->delete_deleted,
885                        (unsigned)vdata->delete_left));
886         }
887
888         ret = 0;
889
890 done:
891         talloc_free(tmp_ctx);
892
893         return ret;
894 }
895
896 /**
897  * initialize the vacuum_data
898  */
899 static int ctdb_vacuum_init_vacuum_data(struct ctdb_db_context *ctdb_db,
900                                         struct vacuum_data *vdata)
901 {
902         int i;
903         struct ctdb_context *ctdb = ctdb_db->ctdb;
904
905         vdata->fast_added_to_delete_list = 0;
906         vdata->fast_added_to_vacuum_fetch_list = 0;
907         vdata->fast_deleted = 0;
908         vdata->fast_skipped = 0;
909         vdata->fast_error = 0;
910         vdata->fast_total = 0;
911         vdata->full_added_to_delete_list = 0;
912         vdata->full_added_to_vacuum_fetch_list = 0;
913         vdata->full_skipped = 0;
914         vdata->full_error = 0;
915         vdata->full_total = 0;
916         vdata->delete_count = 0;
917         vdata->delete_left = 0;
918         vdata->delete_remote_error = 0;
919         vdata->delete_local_error = 0;
920         vdata->delete_skipped = 0;
921         vdata->delete_deleted = 0;
922
923         /* the list needs to be of length num_nodes */
924         vdata->vacuum_fetch_list = talloc_zero_array(vdata,
925                                                 struct ctdb_marshall_buffer *,
926                                                 ctdb->num_nodes);
927         if (vdata->vacuum_fetch_list == NULL) {
928                 DEBUG(DEBUG_ERR,(__location__ " Out of memory\n"));
929                 return -1;
930         }
931         for (i = 0; i < ctdb->num_nodes; i++) {
932                 vdata->vacuum_fetch_list[i] = (struct ctdb_marshall_buffer *)
933                         talloc_zero_size(vdata->vacuum_fetch_list,
934                                          offsetof(struct ctdb_marshall_buffer, data));
935                 if (vdata->vacuum_fetch_list[i] == NULL) {
936                         DEBUG(DEBUG_ERR,(__location__ " Out of memory\n"));
937                         return -1;
938                 }
939                 vdata->vacuum_fetch_list[i]->db_id = ctdb_db->db_id;
940         }
941
942         return 0;
943 }
944
945 /**
946  * Vacuum a DB:
947  *  - Always do the fast vacuuming run, which traverses
948  *    the in-memory delete queue: these records have been
949  *    scheduled for deletion.
950  *  - Only if explicitly requested, the database is traversed
951  *    in order to use the traditional heuristics on empty records
952  *    to trigger deletion.
953  *    This is done only every VacuumFastPathCount'th vacuuming run.
954  *
955  * The traverse runs fill two lists:
956  *
957  * - The delete_list:
958  *   This is the list of empty records the current
959  *   node is lmaster and dmaster for. These records are later
960  *   deleted first on other nodes and then locally.
961  *
962  *   The fast vacuuming run has a short cut for those records
963  *   that have never been migrated with data: these records
964  *   are immediately deleted locally, since they have left
965  *   no trace on other nodes.
966  *
967  * - The vacuum_fetch lists
968  *   (one for each other lmaster node):
969  *   The records in this list are sent for deletion to
970  *   their lmaster in a bulk VACUUM_FETCH message.
971  *
972  *   The lmaster then migrates all these records to itelf
973  *   so that they can be vacuumed there.
974  *
975  * This executes in the child context.
976  */
977 static int ctdb_vacuum_db(struct ctdb_db_context *ctdb_db,
978                           struct vacuum_data *vdata,
979                           bool full_vacuum_run)
980 {
981         struct ctdb_context *ctdb = ctdb_db->ctdb;
982         int ret, pnn;
983
984         DEBUG(DEBUG_INFO, (__location__ " Entering %s vacuum run for db "
985                            "%s db_id[0x%08x]\n",
986                            full_vacuum_run ? "full" : "fast",
987                            ctdb_db->db_name, ctdb_db->db_id));
988
989         ret = ctdb_ctrl_getvnnmap(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE, ctdb, &ctdb->vnn_map);
990         if (ret != 0) {
991                 DEBUG(DEBUG_ERR, ("Unable to get vnnmap from local node\n"));
992                 return ret;
993         }
994
995         pnn = ctdb_ctrl_getpnn(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE);
996         if (pnn == -1) {
997                 DEBUG(DEBUG_ERR, ("Unable to get pnn from local node\n"));
998                 return -1;
999         }
1000
1001         ctdb->pnn = pnn;
1002
1003         ret = ctdb_vacuum_init_vacuum_data(ctdb_db, vdata);
1004         if (ret != 0) {
1005                 return ret;
1006         }
1007
1008         ctdb_vacuum_db_fast(ctdb_db, vdata);
1009
1010         ret = ctdb_vacuum_db_full(ctdb_db, vdata, full_vacuum_run);
1011         if (ret != 0) {
1012                 return ret;
1013         }
1014
1015         ret = ctdb_process_vacuum_fetch_lists(ctdb_db, vdata);
1016         if (ret != 0) {
1017                 return ret;
1018         }
1019
1020         ret = ctdb_process_delete_list(ctdb_db, vdata);
1021         if (ret != 0) {
1022                 return ret;
1023         }
1024
1025         /* this ensures we run our event queue */
1026         ctdb_ctrl_getpnn(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE);
1027
1028         return 0;
1029 }
1030
1031
1032 /*
1033  * traverse function for repacking
1034  */
1035 static int repack_traverse(struct tdb_context *tdb, TDB_DATA key, TDB_DATA data, void *private)
1036 {
1037         struct vacuum_data *vdata = (struct vacuum_data *)private;
1038
1039         if (vdata->vacuum) {
1040                 uint32_t hash = ctdb_hash(&key);
1041                 struct delete_record_data *kd;
1042                 /*
1043                  * check if we can ignore this record because it's in the delete_list
1044                  */
1045                 kd = (struct delete_record_data *)trbt_lookup32(vdata->delete_list, hash);
1046                 /*
1047                  * there might be hash collisions so we have to compare the keys here to be sure
1048                  */
1049                 if (kd && kd->key.dsize == key.dsize && memcmp(kd->key.dptr, key.dptr, key.dsize) == 0) {
1050                         struct ctdb_ltdb_header *hdr = (struct ctdb_ltdb_header *)data.dptr;
1051                         /*
1052                          * we have to check if the record hasn't changed in the meantime in order to
1053                          * savely remove it from the database
1054                          */
1055                         if (data.dsize == sizeof(struct ctdb_ltdb_header) &&
1056                                 hdr->dmaster == kd->ctdb->pnn &&
1057                                 ctdb_lmaster(kd->ctdb, &(kd->key)) == kd->ctdb->pnn &&
1058                                 kd->hdr.rsn == hdr->rsn) {
1059                                 vdata->vacuumed++;
1060                                 return 0;
1061                         }
1062                 }
1063         }
1064         if (tdb_store(vdata->dest_db, key, data, TDB_INSERT) != 0) {
1065                 vdata->traverse_error = true;
1066                 return -1;
1067         }
1068         vdata->copied++;
1069         return 0;
1070 }
1071
1072 /*
1073  * repack a tdb
1074  */
1075 static int ctdb_repack_tdb(struct tdb_context *tdb, TALLOC_CTX *mem_ctx, struct vacuum_data *vdata)
1076 {
1077         struct tdb_context *tmp_db;
1078
1079         if (tdb_transaction_start(tdb) != 0) {
1080                 DEBUG(DEBUG_ERR,(__location__ " Failed to start transaction\n"));
1081                 return -1;
1082         }
1083
1084         tmp_db = tdb_open("tmpdb", tdb_hash_size(tdb),
1085                           TDB_INTERNAL|TDB_DISALLOW_NESTING,
1086                           O_RDWR|O_CREAT, 0);
1087         if (tmp_db == NULL) {
1088                 DEBUG(DEBUG_ERR,(__location__ " Failed to create tmp_db\n"));
1089                 tdb_transaction_cancel(tdb);
1090                 return -1;
1091         }
1092
1093         vdata->traverse_error = false;
1094         vdata->dest_db = tmp_db;
1095         vdata->vacuum = true;
1096         vdata->vacuumed = 0;
1097         vdata->copied = 0;
1098
1099         /*
1100          * repack and vacuum on-the-fly by not writing the records that are
1101          * no longer needed
1102          */
1103         if (tdb_traverse_read(tdb, repack_traverse, vdata) == -1) {
1104                 DEBUG(DEBUG_ERR,(__location__ " Failed to traverse copying out\n"));
1105                 tdb_transaction_cancel(tdb);
1106                 tdb_close(tmp_db);
1107                 return -1;              
1108         }
1109
1110         DEBUG(DEBUG_INFO,(__location__ " %u records vacuumed\n", vdata->vacuumed));
1111         
1112         if (vdata->traverse_error) {
1113                 DEBUG(DEBUG_ERR,(__location__ " Error during traversal\n"));
1114                 tdb_transaction_cancel(tdb);
1115                 tdb_close(tmp_db);
1116                 return -1;
1117         }
1118
1119         if (tdb_wipe_all(tdb) != 0) {
1120                 DEBUG(DEBUG_ERR,(__location__ " Failed to wipe database\n"));
1121                 tdb_transaction_cancel(tdb);
1122                 tdb_close(tmp_db);
1123                 return -1;
1124         }
1125
1126         vdata->traverse_error = false;
1127         vdata->dest_db = tdb;
1128         vdata->vacuum = false;
1129         vdata->copied = 0;
1130
1131         if (tdb_traverse_read(tmp_db, repack_traverse, vdata) == -1) {
1132                 DEBUG(DEBUG_ERR,(__location__ " Failed to traverse copying back\n"));
1133                 tdb_transaction_cancel(tdb);
1134                 tdb_close(tmp_db);
1135                 return -1;              
1136         }
1137
1138         if (vdata->traverse_error) {
1139                 DEBUG(DEBUG_ERR,(__location__ " Error during second traversal\n"));
1140                 tdb_transaction_cancel(tdb);
1141                 tdb_close(tmp_db);
1142                 return -1;
1143         }
1144
1145         tdb_close(tmp_db);
1146
1147
1148         if (tdb_transaction_commit(tdb) != 0) {
1149                 DEBUG(DEBUG_ERR,(__location__ " Failed to commit\n"));
1150                 return -1;
1151         }
1152         DEBUG(DEBUG_INFO,(__location__ " %u records copied\n", vdata->copied));
1153
1154         return 0;
1155 }
1156
1157 /*
1158  * repack and vaccum a db
1159  * called from the child context
1160  */
1161 static int ctdb_vacuum_and_repack_db(struct ctdb_db_context *ctdb_db,
1162                                      TALLOC_CTX *mem_ctx,
1163                                      bool full_vacuum_run)
1164 {
1165         uint32_t repack_limit = ctdb_db->ctdb->tunable.repack_limit;
1166         uint32_t vacuum_limit = ctdb_db->ctdb->tunable.vacuum_limit;
1167         const char *name = ctdb_db->db_name;
1168         int freelist_size;
1169         struct vacuum_data *vdata;
1170
1171         freelist_size = tdb_freelist_size(ctdb_db->ltdb->tdb);
1172         if (freelist_size == -1) {
1173                 DEBUG(DEBUG_ERR,(__location__ " Failed to get freelist size for '%s'\n", name));
1174                 return -1;
1175         }
1176
1177         vdata = talloc_zero(mem_ctx, struct vacuum_data);
1178         if (vdata == NULL) {
1179                 DEBUG(DEBUG_ERR,(__location__ " Out of memory\n"));
1180                 return -1;
1181         }
1182
1183         vdata->ctdb = ctdb_db->ctdb;
1184         vdata->vacuum_limit = vacuum_limit;
1185         vdata->repack_limit = repack_limit;
1186         vdata->delete_list = trbt_create(vdata, 0);
1187         vdata->ctdb_db = ctdb_db;
1188         if (vdata->delete_list == NULL) {
1189                 DEBUG(DEBUG_ERR,(__location__ " Out of memory\n"));
1190                 talloc_free(vdata);
1191                 return -1;
1192         }
1193
1194         vdata->start = timeval_current();
1195  
1196         /*
1197          * gather all records that can be deleted in vdata
1198          */
1199         if (ctdb_vacuum_db(ctdb_db, vdata, full_vacuum_run) != 0) {
1200                 DEBUG(DEBUG_ERR,(__location__ " Failed to vacuum '%s'\n", name));
1201         }
1202
1203         /*
1204          * decide if a repack is necessary
1205          */
1206         if (freelist_size < repack_limit && vdata->delete_left < vacuum_limit)
1207         {
1208                 talloc_free(vdata);
1209                 return 0;
1210         }
1211
1212         DEBUG(DEBUG_INFO,("Repacking %s with %u freelist entries and %u records to delete\n", 
1213                         name, freelist_size, vdata->delete_left));
1214
1215         /*
1216          * repack and implicitely get rid of the records we can delete
1217          */
1218         if (ctdb_repack_tdb(ctdb_db->ltdb->tdb, mem_ctx, vdata) != 0) {
1219                 DEBUG(DEBUG_ERR,(__location__ " Failed to repack '%s'\n", name));
1220                 talloc_free(vdata);
1221                 return -1;
1222         }
1223         talloc_free(vdata);
1224
1225         return 0;
1226 }
1227
1228 static uint32_t get_vacuum_interval(struct ctdb_db_context *ctdb_db)
1229 {
1230         uint32_t interval = ctdb_db->ctdb->tunable.vacuum_interval;
1231
1232         return interval;
1233 }
1234
1235 static int vacuum_child_destructor(struct ctdb_vacuum_child_context *child_ctx)
1236 {
1237         double l = timeval_elapsed(&child_ctx->start_time);
1238         struct ctdb_db_context *ctdb_db = child_ctx->vacuum_handle->ctdb_db;
1239         struct ctdb_context *ctdb = ctdb_db->ctdb;
1240
1241         DEBUG(DEBUG_INFO,("Vacuuming took %.3f seconds for database %s\n", l, ctdb_db->db_name));
1242
1243         if (child_ctx->child_pid != -1) {
1244                 ctdb_kill(ctdb, child_ctx->child_pid, SIGKILL);
1245         } else {
1246                 /* Bump the number of successful fast-path runs. */
1247                 child_ctx->vacuum_handle->fast_path_count++;
1248         }
1249
1250         DLIST_REMOVE(ctdb->vacuumers, child_ctx);
1251
1252         event_add_timed(ctdb->ev, child_ctx->vacuum_handle,
1253                         timeval_current_ofs(get_vacuum_interval(ctdb_db), 0), 
1254                         ctdb_vacuum_event, child_ctx->vacuum_handle);
1255
1256         return 0;
1257 }
1258
1259 /*
1260  * this event is generated when a vacuum child process times out
1261  */
1262 static void vacuum_child_timeout(struct event_context *ev, struct timed_event *te,
1263                                          struct timeval t, void *private_data)
1264 {
1265         struct ctdb_vacuum_child_context *child_ctx = talloc_get_type(private_data, struct ctdb_vacuum_child_context);
1266
1267         DEBUG(DEBUG_ERR,("Vacuuming child process timed out for db %s\n", child_ctx->vacuum_handle->ctdb_db->db_name));
1268
1269         child_ctx->status = VACUUM_TIMEOUT;
1270
1271         talloc_free(child_ctx);
1272 }
1273
1274
1275 /*
1276  * this event is generated when a vacuum child process has completed
1277  */
1278 static void vacuum_child_handler(struct event_context *ev, struct fd_event *fde,
1279                              uint16_t flags, void *private_data)
1280 {
1281         struct ctdb_vacuum_child_context *child_ctx = talloc_get_type(private_data, struct ctdb_vacuum_child_context);
1282         char c = 0;
1283         int ret;
1284
1285         DEBUG(DEBUG_INFO,("Vacuuming child process %d finished for db %s\n", child_ctx->child_pid, child_ctx->vacuum_handle->ctdb_db->db_name));
1286         child_ctx->child_pid = -1;
1287
1288         ret = read(child_ctx->fd[0], &c, 1);
1289         if (ret != 1 || c != 0) {
1290                 child_ctx->status = VACUUM_ERROR;
1291                 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));
1292         } else {
1293                 child_ctx->status = VACUUM_OK;
1294         }
1295
1296         talloc_free(child_ctx);
1297 }
1298
1299 /*
1300  * this event is called every time we need to start a new vacuum process
1301  */
1302 static void
1303 ctdb_vacuum_event(struct event_context *ev, struct timed_event *te,
1304                                struct timeval t, void *private_data)
1305 {
1306         struct ctdb_vacuum_handle *vacuum_handle = talloc_get_type(private_data, struct ctdb_vacuum_handle);
1307         struct ctdb_db_context *ctdb_db = vacuum_handle->ctdb_db;
1308         struct ctdb_context *ctdb = ctdb_db->ctdb;
1309         struct ctdb_vacuum_child_context *child_ctx;
1310         struct tevent_fd *fde;
1311         int ret;
1312
1313         /* we dont vacuum if we are in recovery mode, or db frozen */
1314         if (ctdb->recovery_mode == CTDB_RECOVERY_ACTIVE ||
1315             ctdb->freeze_mode[ctdb_db->priority] != CTDB_FREEZE_NONE) {
1316                 DEBUG(DEBUG_INFO, ("Not vacuuming %s (%s)\n", ctdb_db->db_name,
1317                                    ctdb->recovery_mode == CTDB_RECOVERY_ACTIVE ? "in recovery"
1318                                    : ctdb->freeze_mode[ctdb_db->priority] == CTDB_FREEZE_PENDING
1319                                    ? "freeze pending"
1320                                    : "frozen"));
1321                 event_add_timed(ctdb->ev, vacuum_handle,
1322                         timeval_current_ofs(get_vacuum_interval(ctdb_db), 0),
1323                         ctdb_vacuum_event, vacuum_handle);
1324                 return;
1325         }
1326
1327         child_ctx = talloc(vacuum_handle, struct ctdb_vacuum_child_context);
1328         if (child_ctx == NULL) {
1329                 DEBUG(DEBUG_CRIT, (__location__ " Failed to allocate child context for vacuuming of %s\n", ctdb_db->db_name));
1330                 ctdb_fatal(ctdb, "Out of memory when crating vacuum child context. Shutting down\n");
1331         }
1332
1333
1334         ret = pipe(child_ctx->fd);
1335         if (ret != 0) {
1336                 talloc_free(child_ctx);
1337                 DEBUG(DEBUG_ERR, ("Failed to create pipe for vacuum child process.\n"));
1338                 event_add_timed(ctdb->ev, vacuum_handle,
1339                         timeval_current_ofs(get_vacuum_interval(ctdb_db), 0),
1340                         ctdb_vacuum_event, vacuum_handle);
1341                 return;
1342         }
1343
1344         if (vacuum_handle->fast_path_count > ctdb->tunable.vacuum_fast_path_count) {
1345                 vacuum_handle->fast_path_count = 0;
1346         }
1347
1348         child_ctx->child_pid = ctdb_fork(ctdb);
1349         if (child_ctx->child_pid == (pid_t)-1) {
1350                 close(child_ctx->fd[0]);
1351                 close(child_ctx->fd[1]);
1352                 talloc_free(child_ctx);
1353                 DEBUG(DEBUG_ERR, ("Failed to fork vacuum child process.\n"));
1354                 event_add_timed(ctdb->ev, vacuum_handle,
1355                         timeval_current_ofs(get_vacuum_interval(ctdb_db), 0),
1356                         ctdb_vacuum_event, vacuum_handle);
1357                 return;
1358         }
1359
1360
1361         if (child_ctx->child_pid == 0) {
1362                 char cc = 0;
1363                 bool full_vacuum_run = false;
1364                 close(child_ctx->fd[0]);
1365
1366                 DEBUG(DEBUG_INFO,("Vacuuming child process %d for db %s started\n", getpid(), ctdb_db->db_name));
1367         
1368                 if (switch_from_server_to_client(ctdb, "vacuum-%s", ctdb_db->db_name) != 0) {
1369                         DEBUG(DEBUG_CRIT, (__location__ "ERROR: failed to switch vacuum daemon into client mode. Shutting down.\n"));
1370                         _exit(1);
1371                 }
1372
1373                 /* 
1374                  * repack the db
1375                  */
1376                 if ((ctdb->tunable.vacuum_fast_path_count > 0) &&
1377                     (vacuum_handle->fast_path_count == 0))
1378                 {
1379                         full_vacuum_run = true;
1380                 }
1381                 cc = ctdb_vacuum_and_repack_db(ctdb_db, child_ctx,
1382                                                full_vacuum_run);
1383
1384                 write(child_ctx->fd[1], &cc, 1);
1385                 _exit(0);
1386         }
1387
1388         set_close_on_exec(child_ctx->fd[0]);
1389         close(child_ctx->fd[1]);
1390
1391         child_ctx->status = VACUUM_RUNNING;
1392         child_ctx->start_time = timeval_current();
1393
1394         DLIST_ADD(ctdb->vacuumers, child_ctx);
1395         talloc_set_destructor(child_ctx, vacuum_child_destructor);
1396
1397         /*
1398          * Clear the fastpath vacuuming list in the parent.
1399          */
1400         talloc_free(ctdb_db->delete_queue);
1401         ctdb_db->delete_queue = trbt_create(ctdb_db, 0);
1402         if (ctdb_db->delete_queue == NULL) {
1403                 /* fatal here? ... */
1404                 ctdb_fatal(ctdb, "Out of memory when re-creating vacuum tree "
1405                                  "in parent context. Shutting down\n");
1406         }
1407
1408         event_add_timed(ctdb->ev, child_ctx,
1409                 timeval_current_ofs(ctdb->tunable.vacuum_max_run_time, 0),
1410                 vacuum_child_timeout, child_ctx);
1411
1412         DEBUG(DEBUG_DEBUG, (__location__ " Created PIPE FD:%d to child vacuum process\n", child_ctx->fd[0]));
1413
1414         fde = event_add_fd(ctdb->ev, child_ctx, child_ctx->fd[0],
1415                            EVENT_FD_READ, vacuum_child_handler, child_ctx);
1416         tevent_fd_set_auto_close(fde);
1417
1418         vacuum_handle->child_ctx = child_ctx;
1419         child_ctx->vacuum_handle = vacuum_handle;
1420 }
1421
1422 void ctdb_stop_vacuuming(struct ctdb_context *ctdb)
1423 {
1424         /* Simply free them all. */
1425         while (ctdb->vacuumers) {
1426                 DEBUG(DEBUG_INFO, ("Aborting vacuuming for %s (%i)\n",
1427                            ctdb->vacuumers->vacuum_handle->ctdb_db->db_name,
1428                            (int)ctdb->vacuumers->child_pid));
1429                 /* vacuum_child_destructor kills it, removes from list */
1430                 talloc_free(ctdb->vacuumers);
1431         }
1432 }
1433
1434 /* this function initializes the vacuuming context for a database
1435  * starts the vacuuming events
1436  */
1437 int ctdb_vacuum_init(struct ctdb_db_context *ctdb_db)
1438 {
1439         if (ctdb_db->persistent != 0) {
1440                 DEBUG(DEBUG_ERR,("Vacuuming is disabled for persistent database %s\n", ctdb_db->db_name));
1441                 return 0;
1442         }
1443
1444         ctdb_db->vacuum_handle = talloc(ctdb_db, struct ctdb_vacuum_handle);
1445         CTDB_NO_MEMORY(ctdb_db->ctdb, ctdb_db->vacuum_handle);
1446
1447         ctdb_db->vacuum_handle->ctdb_db         = ctdb_db;
1448         ctdb_db->vacuum_handle->fast_path_count = 0;
1449
1450         event_add_timed(ctdb_db->ctdb->ev, ctdb_db->vacuum_handle, 
1451                         timeval_current_ofs(get_vacuum_interval(ctdb_db), 0), 
1452                         ctdb_vacuum_event, ctdb_db->vacuum_handle);
1453
1454         return 0;
1455 }
1456
1457 static void remove_record_from_delete_queue(struct ctdb_db_context *ctdb_db,
1458                                             const struct ctdb_ltdb_header *hdr,
1459                                             const TDB_DATA key)
1460 {
1461         struct delete_record_data *kd;
1462         uint32_t hash;
1463
1464         hash = (uint32_t)ctdb_hash(&key);
1465
1466         DEBUG(DEBUG_DEBUG, (__location__
1467                             " remove_record_from_delete_queue: "
1468                             "db[%s] "
1469                             "db_id[0x%08x] "
1470                             "key_hash[0x%08x] "
1471                             "lmaster[%u] "
1472                             "migrated_with_data[%s]\n",
1473                              ctdb_db->db_name, ctdb_db->db_id,
1474                              hash,
1475                              ctdb_lmaster(ctdb_db->ctdb, &key),
1476                              hdr->flags & CTDB_REC_FLAG_MIGRATED_WITH_DATA ? "yes" : "no"));
1477
1478         kd = (struct delete_record_data *)trbt_lookup32(ctdb_db->delete_queue, hash);
1479         if (kd == NULL) {
1480                 DEBUG(DEBUG_DEBUG, (__location__
1481                                     " remove_record_from_delete_queue: "
1482                                     "record not in queue (hash[0x%08x])\n.",
1483                                     hash));
1484                 return;
1485         }
1486
1487         if ((kd->key.dsize != key.dsize) ||
1488             (memcmp(kd->key.dptr, key.dptr, key.dsize) != 0))
1489         {
1490                 DEBUG(DEBUG_DEBUG, (__location__
1491                                     " remove_record_from_delete_queue: "
1492                                     "hash collision for key with hash[0x%08x] "
1493                                     "in db[%s] - skipping\n",
1494                                     hash, ctdb_db->db_name));
1495                 return;
1496         }
1497
1498         DEBUG(DEBUG_DEBUG, (__location__
1499                             " remove_record_from_delete_queue: "
1500                             "removing key with hash[0x%08x]\n",
1501                              hash));
1502
1503         talloc_free(kd);
1504
1505         return;
1506 }
1507
1508 /**
1509  * Insert a record into the ctdb_db context's delete queue,
1510  * handling hash collisions.
1511  */
1512 static int insert_record_into_delete_queue(struct ctdb_db_context *ctdb_db,
1513                                            const struct ctdb_ltdb_header *hdr,
1514                                            TDB_DATA key)
1515 {
1516         struct delete_record_data *kd;
1517         uint32_t hash;
1518         int ret;
1519
1520         hash = (uint32_t)ctdb_hash(&key);
1521
1522         DEBUG(DEBUG_INFO, (__location__ " schedule for deletion: db[%s] "
1523                            "db_id[0x%08x] "
1524                            "key_hash[0x%08x] "
1525                            "lmaster[%u] "
1526                            "migrated_with_data[%s]\n",
1527                             ctdb_db->db_name, ctdb_db->db_id,
1528                             hash,
1529                             ctdb_lmaster(ctdb_db->ctdb, &key),
1530                             hdr->flags & CTDB_REC_FLAG_MIGRATED_WITH_DATA ? "yes" : "no"));
1531
1532         kd = (struct delete_record_data *)trbt_lookup32(ctdb_db->delete_queue, hash);
1533         if (kd != NULL) {
1534                 if ((kd->key.dsize != key.dsize) ||
1535                     (memcmp(kd->key.dptr, key.dptr, key.dsize) != 0))
1536                 {
1537                         DEBUG(DEBUG_INFO,
1538                               (__location__ " schedule for deletion: "
1539                                "hash collision for key hash [0x%08x]. "
1540                                "Skipping the record.\n", hash));
1541                         return 0;
1542                 } else {
1543                         DEBUG(DEBUG_DEBUG,
1544                               (__location__ " schedule for deletion: "
1545                                "updating entry for key with hash [0x%08x].\n",
1546                                hash));
1547                 }
1548         }
1549
1550         ret = insert_delete_record_data_into_tree(ctdb_db->ctdb, ctdb_db,
1551                                                   ctdb_db->delete_queue,
1552                                                   hdr, key);
1553         if (ret != 0) {
1554                 DEBUG(DEBUG_INFO,
1555                       (__location__ " schedule for deletion: error "
1556                        "inserting key with hash [0x%08x] into delete queue\n",
1557                        hash));
1558                 return -1;
1559         }
1560
1561         return 0;
1562 }
1563
1564 /**
1565  * Schedule a record for deletetion.
1566  * Called from the parent context.
1567  */
1568 int32_t ctdb_control_schedule_for_deletion(struct ctdb_context *ctdb,
1569                                            TDB_DATA indata)
1570 {
1571         struct ctdb_control_schedule_for_deletion *dd;
1572         struct ctdb_db_context *ctdb_db;
1573         int ret;
1574         TDB_DATA key;
1575
1576         dd = (struct ctdb_control_schedule_for_deletion *)indata.dptr;
1577
1578         ctdb_db = find_ctdb_db(ctdb, dd->db_id);
1579         if (ctdb_db == NULL) {
1580                 DEBUG(DEBUG_ERR, (__location__ " Unknown db id 0x%08x\n",
1581                                   dd->db_id));
1582                 return -1;
1583         }
1584
1585         key.dsize = dd->keylen;
1586         key.dptr = dd->key;
1587
1588         ret = insert_record_into_delete_queue(ctdb_db, &dd->hdr, key);
1589
1590         return ret;
1591 }
1592
1593 int32_t ctdb_local_schedule_for_deletion(struct ctdb_db_context *ctdb_db,
1594                                          const struct ctdb_ltdb_header *hdr,
1595                                          TDB_DATA key)
1596 {
1597         int ret;
1598         struct ctdb_control_schedule_for_deletion *dd;
1599         TDB_DATA indata;
1600         int32_t status;
1601
1602         if (ctdb_db->ctdb->ctdbd_pid == getpid()) {
1603                 /* main daemon - directly queue */
1604                 ret = insert_record_into_delete_queue(ctdb_db, hdr, key);
1605
1606                 return ret;
1607         }
1608
1609         /* if we dont have a connection to the daemon we can not send
1610            a control. For example sometimes from update_record control child
1611            process.
1612         */
1613         if (!ctdb_db->ctdb->can_send_controls) {
1614                 return -1;
1615         }
1616
1617
1618         /* child process: send the main daemon a control */
1619         indata.dsize = offsetof(struct ctdb_control_schedule_for_deletion, key) + key.dsize;
1620         indata.dptr = talloc_zero_array(ctdb_db, uint8_t, indata.dsize);
1621         if (indata.dptr == NULL) {
1622                 DEBUG(DEBUG_ERR, (__location__ " out of memory\n"));
1623                 return -1;
1624         }
1625         dd = (struct ctdb_control_schedule_for_deletion *)(void *)indata.dptr;
1626         dd->db_id = ctdb_db->db_id;
1627         dd->hdr = *hdr;
1628         dd->keylen = key.dsize;
1629         memcpy(dd->key, key.dptr, key.dsize);
1630
1631         ret = ctdb_control(ctdb_db->ctdb,
1632                            CTDB_CURRENT_NODE,
1633                            ctdb_db->db_id,
1634                            CTDB_CONTROL_SCHEDULE_FOR_DELETION,
1635                            CTDB_CTRL_FLAG_NOREPLY, /* flags */
1636                            indata,
1637                            NULL, /* mem_ctx */
1638                            NULL, /* outdata */
1639                            &status,
1640                            NULL, /* timeout : NULL == wait forever */
1641                            NULL); /* error message */
1642
1643         talloc_free(indata.dptr);
1644
1645         if (ret != 0 || status != 0) {
1646                 DEBUG(DEBUG_ERR, (__location__ " Error sending "
1647                                   "SCHEDULE_FOR_DELETION "
1648                                   "control.\n"));
1649                 if (status != 0) {
1650                         ret = -1;
1651                 }
1652         }
1653
1654         return ret;
1655 }
1656
1657 void ctdb_local_remove_from_delete_queue(struct ctdb_db_context *ctdb_db,
1658                                          const struct ctdb_ltdb_header *hdr,
1659                                          const TDB_DATA key)
1660 {
1661         if (ctdb_db->ctdb->ctdbd_pid != getpid()) {
1662                 /*
1663                  * Only remove the record from the delete queue if called
1664                  * in the main daemon.
1665                  */
1666                 return;
1667         }
1668
1669         remove_record_from_delete_queue(ctdb_db, hdr, key);
1670
1671         return;
1672 }