vacuum: raise a debug level from INFO to DEBUG
[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 = ctdb_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 = ctdb_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, ctdb_hash(&reckey)));
679
680                                 rec = (struct ctdb_rec_data *)(rec->length + (uint8_t *)rec);
681                         }           
682                 }
683
684                 /* free nodemap and active_nodes */
685                 talloc_free(nodemap);
686
687                 /* 
688                  * The only records remaining in the tree would be those
689                  * records where all other nodes could successfully
690                  * delete them, so we can safely delete them on the
691                  * lmaster as well. Deletion implictely happens while
692                  * we repack the database. The repack algorithm revisits 
693                  * the tree in order to find the records that don't need
694                  * to be copied / repacked.
695                  */
696         }
697
698         /* this ensures we run our event queue */
699         ctdb_ctrl_getpnn(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE);
700
701         return 0;
702 }
703
704
705 /*
706  * traverse function for repacking
707  */
708 static int repack_traverse(struct tdb_context *tdb, TDB_DATA key, TDB_DATA data, void *private)
709 {
710         struct vacuum_data *vdata = (struct vacuum_data *)private;
711
712         if (vdata->vacuum) {
713                 uint32_t hash = ctdb_hash(&key);
714                 struct delete_record_data *kd;
715                 /*
716                  * check if we can ignore this record because it's in the delete_tree
717                  */
718                 kd = (struct delete_record_data *)trbt_lookup32(vdata->delete_tree, hash);
719                 /*
720                  * there might be hash collisions so we have to compare the keys here to be sure
721                  */
722                 if (kd && kd->key.dsize == key.dsize && memcmp(kd->key.dptr, key.dptr, key.dsize) == 0) {
723                         struct ctdb_ltdb_header *hdr = (struct ctdb_ltdb_header *)data.dptr;
724                         /*
725                          * we have to check if the record hasn't changed in the meantime in order to
726                          * savely remove it from the database
727                          */
728                         if (data.dsize == sizeof(struct ctdb_ltdb_header) &&
729                                 hdr->dmaster == kd->ctdb->pnn &&
730                                 ctdb_lmaster(kd->ctdb, &(kd->key)) == kd->ctdb->pnn &&
731                                 kd->hdr.rsn == hdr->rsn) {
732                                 vdata->vacuumed++;
733                                 return 0;
734                         }
735                 }
736         }
737         if (tdb_store(vdata->dest_db, key, data, TDB_INSERT) != 0) {
738                 vdata->traverse_error = true;
739                 return -1;
740         }
741         vdata->copied++;
742         return 0;
743 }
744
745 /*
746  * repack a tdb
747  */
748 static int ctdb_repack_tdb(struct tdb_context *tdb, TALLOC_CTX *mem_ctx, struct vacuum_data *vdata)
749 {
750         struct tdb_context *tmp_db;
751
752         if (tdb_transaction_start(tdb) != 0) {
753                 DEBUG(DEBUG_ERR,(__location__ " Failed to start transaction\n"));
754                 return -1;
755         }
756
757         tmp_db = tdb_open("tmpdb", tdb_hash_size(tdb),
758                           TDB_INTERNAL|TDB_DISALLOW_NESTING,
759                           O_RDWR|O_CREAT, 0);
760         if (tmp_db == NULL) {
761                 DEBUG(DEBUG_ERR,(__location__ " Failed to create tmp_db\n"));
762                 tdb_transaction_cancel(tdb);
763                 return -1;
764         }
765
766         vdata->traverse_error = false;
767         vdata->dest_db = tmp_db;
768         vdata->vacuum = true;
769         vdata->vacuumed = 0;
770         vdata->copied = 0;
771
772         /*
773          * repack and vacuum on-the-fly by not writing the records that are
774          * no longer needed
775          */
776         if (tdb_traverse_read(tdb, repack_traverse, vdata) == -1) {
777                 DEBUG(DEBUG_ERR,(__location__ " Failed to traverse copying out\n"));
778                 tdb_transaction_cancel(tdb);
779                 tdb_close(tmp_db);
780                 return -1;              
781         }
782
783         DEBUG(DEBUG_INFO,(__location__ " %u records vacuumed\n", vdata->vacuumed));
784         
785         if (vdata->traverse_error) {
786                 DEBUG(DEBUG_ERR,(__location__ " Error during traversal\n"));
787                 tdb_transaction_cancel(tdb);
788                 tdb_close(tmp_db);
789                 return -1;
790         }
791
792         if (tdb_wipe_all(tdb) != 0) {
793                 DEBUG(DEBUG_ERR,(__location__ " Failed to wipe database\n"));
794                 tdb_transaction_cancel(tdb);
795                 tdb_close(tmp_db);
796                 return -1;
797         }
798
799         vdata->traverse_error = false;
800         vdata->dest_db = tdb;
801         vdata->vacuum = false;
802         vdata->copied = 0;
803
804         if (tdb_traverse_read(tmp_db, repack_traverse, vdata) == -1) {
805                 DEBUG(DEBUG_ERR,(__location__ " Failed to traverse copying back\n"));
806                 tdb_transaction_cancel(tdb);
807                 tdb_close(tmp_db);
808                 return -1;              
809         }
810
811         if (vdata->traverse_error) {
812                 DEBUG(DEBUG_ERR,(__location__ " Error during second traversal\n"));
813                 tdb_transaction_cancel(tdb);
814                 tdb_close(tmp_db);
815                 return -1;
816         }
817
818         tdb_close(tmp_db);
819
820
821         if (tdb_transaction_commit(tdb) != 0) {
822                 DEBUG(DEBUG_ERR,(__location__ " Failed to commit\n"));
823                 return -1;
824         }
825         DEBUG(DEBUG_INFO,(__location__ " %u records copied\n", vdata->copied));
826
827         return 0;
828 }
829
830 static int update_tuning_db(struct ctdb_db_context *ctdb_db, struct vacuum_data *vdata, uint32_t freelist)
831 {
832         TALLOC_CTX *tmp_ctx = talloc_new(NULL);
833         TDB_CONTEXT *tune_tdb;
834         TDB_DATA key, value;
835         struct vacuum_tuning_data tdata;
836         struct vacuum_tuning_data *tptr;
837         char *vac_dbname;
838         int flags;
839
840         vac_dbname = talloc_asprintf(tmp_ctx, "%s/%s.%u",
841                                      ctdb_db->ctdb->db_directory_state,
842                                      TUNINGDBNAME, ctdb_db->ctdb->pnn);
843         if (vac_dbname == NULL) {
844                 DEBUG(DEBUG_CRIT,(__location__ " Out of memory error while allocating '%s'\n", vac_dbname));
845                 talloc_free(tmp_ctx);
846                 return -1;
847         }
848
849         flags  = ctdb_db->ctdb->valgrinding ? TDB_NOMMAP : 0;
850         flags |= TDB_DISALLOW_NESTING;
851         tune_tdb = tdb_open(vac_dbname, 0,
852                             flags,
853                             O_RDWR|O_CREAT, 0600);
854         if (tune_tdb == NULL) {
855                 DEBUG(DEBUG_ERR,(__location__ " Failed to create/open %s\n", TUNINGDBNAME));
856                 talloc_free(tmp_ctx);
857                 return -1;
858         }
859         
860         if (tdb_transaction_start(tune_tdb) != 0) {
861                 DEBUG(DEBUG_ERR,(__location__ " Failed to start transaction\n"));
862                 tdb_close(tune_tdb);
863                 return -1;
864         }
865         key.dptr = discard_const(ctdb_db->db_name);
866         key.dsize = strlen(ctdb_db->db_name);
867         value = tdb_fetch(tune_tdb, key);
868
869         if (value.dptr != NULL && value.dsize == sizeof(struct vacuum_tuning_data)) {
870                 tptr = (struct vacuum_tuning_data *)value.dptr;
871                 tdata = *tptr;
872
873                 /*
874                  * re-calc new vacuum interval:
875                  * in case no limit was reached we continously increase the interval
876                  * until vacuum_max_interval is reached
877                  * in case a limit was reached we divide the current interval by 2
878                  * unless vacuum_min_interval is reached
879                  */
880                 if (freelist < vdata->repack_limit &&
881                     vdata->delete_count < vdata->vacuum_limit) {
882                         if (tdata.last_interval < ctdb_db->ctdb->tunable.vacuum_max_interval) {
883                                 tdata.new_interval = tdata.last_interval * 110 / 100;
884                                 DEBUG(DEBUG_INFO,("Increasing vacuum interval %u -> %u for %s\n", 
885                                         tdata.last_interval, tdata.new_interval, ctdb_db->db_name));
886                         }
887                 } else {
888                         tdata.new_interval = tdata.last_interval / 2;
889                         if (tdata.new_interval < ctdb_db->ctdb->tunable.vacuum_min_interval ||
890                                 tdata.new_interval > ctdb_db->ctdb->tunable.vacuum_max_interval) {
891                                 tdata.new_interval = ctdb_db->ctdb->tunable.vacuum_min_interval;
892                         }               
893                         DEBUG(DEBUG_INFO,("Decreasing vacuum interval %u -> %u for %s\n", 
894                                          tdata.last_interval, tdata.new_interval, ctdb_db->db_name));
895                 }
896                 tdata.last_interval = tdata.new_interval;
897         } else {
898                 DEBUG(DEBUG_ERR,(__location__ " Cannot find tunedb record for %s. Using default interval\n", ctdb_db->db_name));
899                 tdata.last_num_repack = freelist;
900                 tdata.last_num_empty = vdata->delete_count;
901                 tdata.last_interval = ctdb_db->ctdb->tunable.vacuum_default_interval;
902         }
903
904         if (value.dptr != NULL) {
905                 free(value.dptr);
906         }
907
908         tdata.last_start = vdata->start;
909         tdata.last_duration = timeval_elapsed(&vdata->start);
910
911         value.dptr = (unsigned char *)&tdata;
912         value.dsize = sizeof(tdata);
913
914         if (tdb_store(tune_tdb, key, value, 0) != 0) {
915                 DEBUG(DEBUG_ERR,(__location__ " Unable to store tundb record for %s\n", ctdb_db->db_name));
916                 tdb_transaction_cancel(tune_tdb);
917                 tdb_close(tune_tdb);
918                 talloc_free(tmp_ctx);
919                 return -1;
920         }
921         tdb_transaction_commit(tune_tdb);
922         tdb_close(tune_tdb);
923         talloc_free(tmp_ctx);
924
925         return 0;
926 }
927
928 /*
929  * repack and vaccum a db
930  * called from the child context
931  */
932 static int ctdb_vacuum_and_repack_db(struct ctdb_db_context *ctdb_db,
933                                      TALLOC_CTX *mem_ctx,
934                                      bool full_vacuum_run)
935 {
936         uint32_t repack_limit = ctdb_db->ctdb->tunable.repack_limit;
937         uint32_t vacuum_limit = ctdb_db->ctdb->tunable.vacuum_limit;
938         const char *name = ctdb_db->db_name;
939         int size;
940         struct vacuum_data *vdata;
941
942         size = tdb_freelist_size(ctdb_db->ltdb->tdb);
943         if (size == -1) {
944                 DEBUG(DEBUG_ERR,(__location__ " Failed to get freelist size for '%s'\n", name));
945                 return -1;
946         }
947
948         vdata = talloc_zero(mem_ctx, struct vacuum_data);
949         if (vdata == NULL) {
950                 DEBUG(DEBUG_ERR,(__location__ " Out of memory\n"));
951                 return -1;
952         }
953
954         vdata->ctdb = ctdb_db->ctdb;
955         vdata->vacuum_limit = vacuum_limit;
956         vdata->repack_limit = repack_limit;
957         vdata->delete_tree = trbt_create(vdata, 0);
958         if (vdata->delete_tree == NULL) {
959                 DEBUG(DEBUG_ERR,(__location__ " Out of memory\n"));
960                 talloc_free(vdata);
961                 return -1;
962         }
963
964         vdata->start = timeval_current();
965  
966         /*
967          * gather all records that can be deleted in vdata
968          */
969         if (ctdb_vacuum_db(ctdb_db, vdata, full_vacuum_run) != 0) {
970                 DEBUG(DEBUG_ERR,(__location__ " Failed to vacuum '%s'\n", name));
971         }
972
973         /*
974          * decide if a repack is necessary
975          */
976         if (size < repack_limit && vdata->delete_count < vacuum_limit) {
977                 update_tuning_db(ctdb_db, vdata, size);
978                 talloc_free(vdata);
979                 return 0;
980         }
981
982         DEBUG(DEBUG_INFO,("Repacking %s with %u freelist entries and %u records to delete\n", 
983                         name, size, vdata->delete_count));
984
985         /*
986          * repack and implicitely get rid of the records we can delete
987          */
988         if (ctdb_repack_tdb(ctdb_db->ltdb->tdb, mem_ctx, vdata) != 0) {
989                 DEBUG(DEBUG_ERR,(__location__ " Failed to repack '%s'\n", name));
990                 update_tuning_db(ctdb_db, vdata, size);
991                 talloc_free(vdata);
992                 return -1;
993         }
994         update_tuning_db(ctdb_db, vdata, size);
995         talloc_free(vdata);
996
997         return 0;
998 }
999
1000 static int get_vacuum_interval(struct ctdb_db_context *ctdb_db)
1001 {
1002         TALLOC_CTX *tmp_ctx = talloc_new(NULL);
1003         TDB_CONTEXT *tdb;
1004         TDB_DATA key, value;
1005         char *vac_dbname;
1006         uint interval = ctdb_db->ctdb->tunable.vacuum_default_interval;
1007         struct ctdb_context *ctdb = ctdb_db->ctdb;
1008         int flags;
1009
1010         vac_dbname = talloc_asprintf(tmp_ctx, "%s/%s.%u", ctdb->db_directory, TUNINGDBNAME, ctdb->pnn);
1011         if (vac_dbname == NULL) {
1012                 DEBUG(DEBUG_CRIT,(__location__ " Out of memory error while allocating '%s'\n", vac_dbname));
1013                 talloc_free(tmp_ctx);
1014                 return interval;
1015         }
1016
1017         flags  = ctdb_db->ctdb->valgrinding ? TDB_NOMMAP : 0;
1018         flags |= TDB_DISALLOW_NESTING;
1019         tdb = tdb_open(vac_dbname, 0,
1020                        flags,
1021                        O_RDWR|O_CREAT, 0600);
1022         if (!tdb) {
1023                 DEBUG(DEBUG_ERR,("Unable to open/create database %s using default interval\n", vac_dbname));
1024                 talloc_free(tmp_ctx);
1025                 return interval;
1026         }
1027
1028         key.dptr = discard_const(ctdb_db->db_name);
1029         key.dsize = strlen(ctdb_db->db_name);
1030
1031         value = tdb_fetch(tdb, key);
1032
1033         if (value.dptr != NULL) {
1034                 if (value.dsize == sizeof(struct vacuum_tuning_data)) {
1035                         struct vacuum_tuning_data *tptr = (struct vacuum_tuning_data *)value.dptr;
1036
1037                         interval = tptr->new_interval;
1038
1039                         if (interval < ctdb->tunable.vacuum_min_interval) {
1040                                 interval = ctdb->tunable.vacuum_min_interval;
1041                         } 
1042                         if (interval > ctdb->tunable.vacuum_max_interval) {
1043                                 interval = ctdb->tunable.vacuum_max_interval;
1044                         }
1045                 }
1046                 free(value.dptr);
1047         }
1048         tdb_close(tdb);
1049
1050         talloc_free(tmp_ctx);
1051
1052         return interval;
1053 }
1054
1055 static int vacuum_child_destructor(struct ctdb_vacuum_child_context *child_ctx)
1056 {
1057         double l = timeval_elapsed(&child_ctx->start_time);
1058         struct ctdb_db_context *ctdb_db = child_ctx->vacuum_handle->ctdb_db;
1059         struct ctdb_context *ctdb = ctdb_db->ctdb;
1060
1061         DEBUG(DEBUG_INFO,("Vacuuming took %.3f seconds for database %s\n", l, ctdb_db->db_name));
1062
1063         if (child_ctx->child_pid != -1) {
1064                 kill(child_ctx->child_pid, SIGKILL);
1065         } else {
1066                 /* Bump the number of successful fast-path runs. */
1067                 child_ctx->vacuum_handle->fast_path_count++;
1068         }
1069
1070         event_add_timed(ctdb->ev, child_ctx->vacuum_handle,
1071                         timeval_current_ofs(get_vacuum_interval(ctdb_db), 0), 
1072                         ctdb_vacuum_event, child_ctx->vacuum_handle);
1073
1074         return 0;
1075 }
1076
1077 /*
1078  * this event is generated when a vacuum child process times out
1079  */
1080 static void vacuum_child_timeout(struct event_context *ev, struct timed_event *te,
1081                                          struct timeval t, void *private_data)
1082 {
1083         struct ctdb_vacuum_child_context *child_ctx = talloc_get_type(private_data, struct ctdb_vacuum_child_context);
1084
1085         DEBUG(DEBUG_ERR,("Vacuuming child process timed out for db %s\n", child_ctx->vacuum_handle->ctdb_db->db_name));
1086
1087         child_ctx->status = VACUUM_TIMEOUT;
1088
1089         talloc_free(child_ctx);
1090 }
1091
1092
1093 /*
1094  * this event is generated when a vacuum child process has completed
1095  */
1096 static void vacuum_child_handler(struct event_context *ev, struct fd_event *fde,
1097                              uint16_t flags, void *private_data)
1098 {
1099         struct ctdb_vacuum_child_context *child_ctx = talloc_get_type(private_data, struct ctdb_vacuum_child_context);
1100         char c = 0;
1101         int ret;
1102
1103         DEBUG(DEBUG_INFO,("Vacuuming child process %d finished for db %s\n", child_ctx->child_pid, child_ctx->vacuum_handle->ctdb_db->db_name));
1104         child_ctx->child_pid = -1;
1105
1106         ret = read(child_ctx->fd[0], &c, 1);
1107         if (ret != 1 || c != 0) {
1108                 child_ctx->status = VACUUM_ERROR;
1109                 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));
1110         } else {
1111                 child_ctx->status = VACUUM_OK;
1112         }
1113
1114         talloc_free(child_ctx);
1115 }
1116
1117 /*
1118  * this event is called every time we need to start a new vacuum process
1119  */
1120 static void
1121 ctdb_vacuum_event(struct event_context *ev, struct timed_event *te,
1122                                struct timeval t, void *private_data)
1123 {
1124         struct ctdb_vacuum_handle *vacuum_handle = talloc_get_type(private_data, struct ctdb_vacuum_handle);
1125         struct ctdb_db_context *ctdb_db = vacuum_handle->ctdb_db;
1126         struct ctdb_context *ctdb = ctdb_db->ctdb;
1127         struct ctdb_vacuum_child_context *child_ctx;
1128         int ret;
1129
1130         /* we dont vacuum if we are in recovery mode */
1131         if (ctdb->recovery_mode == CTDB_RECOVERY_ACTIVE) {
1132                 event_add_timed(ctdb->ev, vacuum_handle, timeval_current_ofs(ctdb->tunable.vacuum_default_interval, 0), ctdb_vacuum_event, vacuum_handle);
1133                 return;
1134         }
1135
1136         child_ctx = talloc(vacuum_handle, struct ctdb_vacuum_child_context);
1137         if (child_ctx == NULL) {
1138                 DEBUG(DEBUG_CRIT, (__location__ " Failed to allocate child context for vacuuming of %s\n", ctdb_db->db_name));
1139                 ctdb_fatal(ctdb, "Out of memory when crating vacuum child context. Shutting down\n");
1140         }
1141
1142
1143         ret = pipe(child_ctx->fd);
1144         if (ret != 0) {
1145                 talloc_free(child_ctx);
1146                 DEBUG(DEBUG_ERR, ("Failed to create pipe for vacuum child process.\n"));
1147                 event_add_timed(ctdb->ev, vacuum_handle, timeval_current_ofs(ctdb->tunable.vacuum_default_interval, 0), ctdb_vacuum_event, vacuum_handle);
1148                 return;
1149         }
1150
1151         if (vacuum_handle->fast_path_count > ctdb->tunable.vacuum_fast_path_count) {
1152                 vacuum_handle->fast_path_count = 0;
1153         }
1154
1155         child_ctx->child_pid = fork();
1156         if (child_ctx->child_pid == (pid_t)-1) {
1157                 close(child_ctx->fd[0]);
1158                 close(child_ctx->fd[1]);
1159                 talloc_free(child_ctx);
1160                 DEBUG(DEBUG_ERR, ("Failed to fork vacuum child process.\n"));
1161                 event_add_timed(ctdb->ev, vacuum_handle, timeval_current_ofs(ctdb->tunable.vacuum_default_interval, 0), ctdb_vacuum_event, vacuum_handle);
1162                 return;
1163         }
1164
1165
1166         if (child_ctx->child_pid == 0) {
1167                 char cc = 0;
1168                 bool full_vacuum_run = false;
1169                 close(child_ctx->fd[0]);
1170
1171                 DEBUG(DEBUG_INFO,("Vacuuming child process %d for db %s started\n", getpid(), ctdb_db->db_name));
1172         
1173                 if (switch_from_server_to_client(ctdb) != 0) {
1174                         DEBUG(DEBUG_CRIT, (__location__ "ERROR: failed to switch vacuum daemon into client mode. Shutting down.\n"));
1175                         _exit(1);
1176                 }
1177
1178                 /* 
1179                  * repack the db
1180                  */
1181                 if ((ctdb->tunable.vacuum_fast_path_count > 0) &&
1182                     (vacuum_handle->fast_path_count == 0))
1183                 {
1184                         full_vacuum_run = true;
1185                 }
1186                 cc = ctdb_vacuum_and_repack_db(ctdb_db, child_ctx,
1187                                                full_vacuum_run);
1188
1189                 write(child_ctx->fd[1], &cc, 1);
1190                 _exit(0);
1191         }
1192
1193         set_close_on_exec(child_ctx->fd[0]);
1194         close(child_ctx->fd[1]);
1195
1196         child_ctx->status = VACUUM_RUNNING;
1197         child_ctx->start_time = timeval_current();
1198
1199         talloc_set_destructor(child_ctx, vacuum_child_destructor);
1200
1201         /*
1202          * Clear the fastpath vacuuming list in the parent.
1203          */
1204         talloc_free(ctdb_db->delete_queue);
1205         ctdb_db->delete_queue = trbt_create(ctdb_db, 0);
1206         if (ctdb_db->delete_queue == NULL) {
1207                 /* fatal here? ... */
1208                 ctdb_fatal(ctdb, "Out of memory when re-creating vacuum tree "
1209                                  "in parent context. Shutting down\n");
1210         }
1211
1212         event_add_timed(ctdb->ev, child_ctx,
1213                 timeval_current_ofs(ctdb->tunable.vacuum_max_run_time, 0),
1214                 vacuum_child_timeout, child_ctx);
1215
1216         DEBUG(DEBUG_DEBUG, (__location__ " Created PIPE FD:%d to child vacuum process\n", child_ctx->fd[0]));
1217
1218         event_add_fd(ctdb->ev, child_ctx, child_ctx->fd[0],
1219                 EVENT_FD_READ|EVENT_FD_AUTOCLOSE,
1220                 vacuum_child_handler,
1221                 child_ctx);
1222
1223         vacuum_handle->child_ctx = child_ctx;
1224         child_ctx->vacuum_handle = vacuum_handle;
1225 }
1226
1227
1228 /* this function initializes the vacuuming context for a database
1229  * starts the vacuuming events
1230  */
1231 int ctdb_vacuum_init(struct ctdb_db_context *ctdb_db)
1232 {
1233         if (ctdb_db->persistent != 0) {
1234                 DEBUG(DEBUG_ERR,("Vacuuming is disabled for persistent database %s\n", ctdb_db->db_name));
1235                 return 0;
1236         }
1237
1238         ctdb_db->vacuum_handle = talloc(ctdb_db, struct ctdb_vacuum_handle);
1239         CTDB_NO_MEMORY(ctdb_db->ctdb, ctdb_db->vacuum_handle);
1240
1241         ctdb_db->vacuum_handle->ctdb_db = ctdb_db;
1242
1243         event_add_timed(ctdb_db->ctdb->ev, ctdb_db->vacuum_handle, 
1244                         timeval_current_ofs(get_vacuum_interval(ctdb_db), 0), 
1245                         ctdb_vacuum_event, ctdb_db->vacuum_handle);
1246
1247         return 0;
1248 }
1249
1250 /**
1251  * Schedule a record for deletetion.
1252  * Called from the parent context.
1253  */
1254 int32_t ctdb_control_schedule_for_deletion(struct ctdb_context *ctdb,
1255                                            TDB_DATA indata)
1256 {
1257         struct ctdb_control_schedule_for_deletion *dd;
1258         struct ctdb_db_context *ctdb_db;
1259         int ret;
1260         TDB_DATA key;
1261         uint32_t hash;
1262         struct delete_record_data *kd;
1263
1264         dd = (struct ctdb_control_schedule_for_deletion *)indata.dptr;
1265
1266         ctdb_db = find_ctdb_db(ctdb, dd->db_id);
1267         if (ctdb_db == NULL) {
1268                 DEBUG(DEBUG_ERR, (__location__ " Unknown db id 0x%08x\n",
1269                                   dd->db_id));
1270                 return -1;
1271         }
1272
1273         key.dsize = dd->keylen;
1274         key.dptr = dd->key;
1275
1276         hash = ctdb_hash(&key);
1277
1278         DEBUG(DEBUG_INFO, (__location__ " Schedule for deletion: db[%s] "
1279                            "db_id[0x%08x] "
1280                            "key_hash[0x%08x] "
1281                            "lmaster[%u] "
1282                            "migrated_with_data[%s]\n",
1283                             ctdb_db->db_name, dd->db_id,
1284                             hash,
1285                             ctdb_lmaster(ctdb_db->ctdb, &key),
1286                             dd->hdr.flags & CTDB_REC_FLAG_MIGRATED_WITH_DATA ? "yes" : "no"));
1287
1288         kd = (struct delete_record_data *)trbt_lookup32(ctdb_db->delete_queue, hash);
1289         if (kd != NULL) {
1290                 if ((kd->key.dsize != key.dsize) ||
1291                     (memcmp(kd->key.dptr, key.dptr, key.dsize) != 0))
1292                 {
1293                         DEBUG(DEBUG_INFO,
1294                               ("schedule for deletion: Hash collision (0x%08x)."
1295                                " Skipping the record.\n", hash));
1296                         return 0;
1297                 } else {
1298                         DEBUG(DEBUG_DEBUG,
1299                               ("schedule for deletetion: Overwriting entry for "
1300                                "key with hash 0x%08x.\n", hash));
1301                 }
1302         }
1303
1304         ret = insert_delete_record_data_into_tree(ctdb, ctdb_db,
1305                                                   ctdb_db->delete_queue,
1306                                                   &dd->hdr, key);
1307         if (ret != 0) {
1308                 return -1;
1309         }
1310
1311         return 0;
1312 }
1313
1314 int32_t ctdb_local_schedule_for_deletion(struct ctdb_db_context *ctdb_db,
1315                                          const struct ctdb_ltdb_header *hdr,
1316                                          TDB_DATA key)
1317 {
1318         int ret;
1319         struct ctdb_control_schedule_for_deletion *dd;
1320         TDB_DATA indata;
1321         int32_t status;
1322
1323         if (ctdb_db->ctdb->ctdbd_pid == getpid()) {
1324                 /* main daemon - directly queue */
1325                 ret = insert_delete_record_data_into_tree(ctdb_db->ctdb,
1326                                                           ctdb_db,
1327                                                           ctdb_db->delete_queue,
1328                                                           hdr, key);
1329                 if (ret != 0) {
1330                         return -1;
1331                 }
1332                 return 0;
1333         }
1334
1335         /* child process: send the main daemon a control */
1336
1337         indata.dsize = offsetof(struct ctdb_control_schedule_for_deletion, key) + key.dsize;
1338         indata.dptr = talloc_zero_array(ctdb_db, uint8_t, indata.dsize);
1339         if (indata.dptr == NULL) {
1340                 DEBUG(DEBUG_ERR, (__location__ " out of memory\n"));
1341                 return -1;
1342         }
1343         dd = (struct ctdb_control_schedule_for_deletion *)(void *)indata.dptr;
1344         dd->db_id = ctdb_db->db_id;
1345         dd->hdr = *hdr;
1346         dd->keylen = key.dsize;
1347         memcpy(dd->key, key.dptr, key.dsize);
1348
1349         ret = ctdb_control(ctdb_db->ctdb,
1350                            CTDB_CURRENT_NODE,
1351                            ctdb_db->db_id,
1352                            CTDB_CONTROL_SCHEDULE_FOR_DELETION,
1353                            CTDB_CTRL_FLAG_NOREPLY, /* flags */
1354                            indata,
1355                            NULL, /* mem_ctx */
1356                            NULL, /* outdata */
1357                            &status,
1358                            NULL, /* timeout : NULL == wait forever */
1359                            NULL); /* error message */
1360
1361         talloc_free(indata.dptr);
1362
1363         if (ret != 0 || status != 0) {
1364                 DEBUG(DEBUG_ERR, (__location__ " Error sending "
1365                                   "SCHEDULE_FOR_DELETION "
1366                                   "control.\n"));
1367                 if (status != 0) {
1368                         ret = -1;
1369                 }
1370         }
1371
1372         return ret;
1373 }