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