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