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