vacuum: add delete_queue_traverse() for traversal of the delete_queue.
[garming/samba-autobuild/.git] / ctdb / 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/tevent/tevent.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/tevent/tevent.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_child_context *next, *prev;
40         struct ctdb_vacuum_handle *vacuum_handle;
41         /* fd child writes status to */
42         int fd[2];
43         pid_t child_pid;
44         enum vacuum_child_status status;
45         struct timeval start_time;
46 };
47
48 struct ctdb_vacuum_handle {
49         struct ctdb_db_context *ctdb_db;
50         struct ctdb_vacuum_child_context *child_ctx;
51 };
52
53
54 /*  a list of records to possibly delete */
55 struct vacuum_data {
56         uint32_t vacuum_limit;
57         uint32_t repack_limit;
58         struct ctdb_context *ctdb;
59         struct ctdb_db_context *ctdb_db;
60         struct tdb_context *dest_db;
61         trbt_tree_t *delete_tree;
62         uint32_t delete_count;
63         struct ctdb_marshall_buffer **list;
64         struct timeval start;
65         bool traverse_error;
66         bool vacuum;
67         uint32_t total;
68         uint32_t vacuumed;
69         uint32_t copied;
70 };
71
72 /* tuning information stored for every db */
73 struct vacuum_tuning_data {
74         uint32_t last_num_repack;
75         uint32_t last_num_empty;
76         uint32_t last_interval;
77         uint32_t new_interval;
78         struct timeval last_start;
79         double   last_duration;
80 };
81
82 /* this structure contains the information for one record to be deleted */
83 struct delete_record_data {
84         struct ctdb_context *ctdb;
85         struct ctdb_db_context *ctdb_db;
86         struct ctdb_ltdb_header hdr;
87         TDB_DATA key;
88 };
89
90 struct delete_records_list {
91         struct ctdb_marshall_buffer *records;
92 };
93
94
95 static int add_record_to_delete_tree(struct vacuum_data *vdata, TDB_DATA key,
96                                      struct ctdb_ltdb_header *hdr)
97 {
98         struct ctdb_context *ctdb = vdata->ctdb;
99         struct ctdb_db_context *ctdb_db = vdata->ctdb_db;
100         uint32_t hash;
101         struct delete_record_data *dd;
102
103         hash = ctdb_hash(&key);
104
105         if (trbt_lookup32(vdata->delete_tree, hash)) {
106                 DEBUG(DEBUG_DEBUG, (__location__ " Hash collission when vacuuming, skipping this record.\n"));
107                 return 0;
108         }
109
110         /* store key and header indexed by the key hash */
111         dd = talloc_zero(vdata->delete_tree, struct delete_record_data);
112         if (dd == NULL) {
113                 DEBUG(DEBUG_ERR,(__location__ " Out of memory\n"));
114                 return -1;
115         }
116         dd->ctdb      = ctdb;
117         dd->ctdb_db   = ctdb_db;
118         dd->key.dsize = key.dsize;
119         dd->key.dptr  = talloc_memdup(dd, key.dptr, key.dsize);
120         if (dd->key.dptr == NULL) {
121                 DEBUG(DEBUG_ERR,(__location__ " Out of memory\n"));
122                 return -1;
123         }
124
125         dd->hdr = *hdr;
126
127         trbt_insert32(vdata->delete_tree, hash, dd);
128
129         vdata->delete_count++;
130
131         return 0;
132 }
133
134 /**
135  * Add a record to the list of records to be sent
136  * to their lmaster with VACUUM_FETCH.
137  */
138 static int add_record_to_vacuum_fetch_list(struct vacuum_data *vdata,
139                                            TDB_DATA key)
140 {
141         struct ctdb_context *ctdb = vdata->ctdb;
142         struct ctdb_rec_data *rec;
143         uint32_t lmaster;
144         size_t old_size;
145
146         lmaster = ctdb_lmaster(ctdb, &key);
147
148         rec = ctdb_marshall_record(vdata->list[lmaster], ctdb->pnn, key, NULL, tdb_null);
149         if (rec == NULL) {
150                 DEBUG(DEBUG_ERR,(__location__ " Out of memory\n"));
151                 vdata->traverse_error = true;
152                 return -1;
153         }
154
155         old_size = talloc_get_size(vdata->list[lmaster]);
156         vdata->list[lmaster] = talloc_realloc_size(NULL, vdata->list[lmaster],
157                                                    old_size + rec->length);
158         if (vdata->list[lmaster] == NULL) {
159                 DEBUG(DEBUG_ERR,(__location__ " Failed to expand\n"));
160                 vdata->traverse_error = true;
161                 return -1;
162         }
163
164         vdata->list[lmaster]->count++;
165         memcpy(old_size+(uint8_t *)vdata->list[lmaster], rec, rec->length);
166         talloc_free(rec);
167
168         vdata->total++;
169
170         return 0;
171 }
172
173
174 static void ctdb_vacuum_event(struct event_context *ev, struct timed_event *te, 
175                                                           struct timeval t, void *private_data);
176
177
178 /*
179  * traverse function for gathering the records that can be deleted
180  */
181 static int vacuum_traverse(struct tdb_context *tdb, TDB_DATA key, TDB_DATA data, void *private)
182 {
183         struct vacuum_data *vdata = talloc_get_type(private, struct vacuum_data);
184         struct ctdb_context *ctdb = vdata->ctdb;
185         uint32_t lmaster;
186         struct ctdb_ltdb_header *hdr;
187         int res = 0;
188
189         lmaster = ctdb_lmaster(ctdb, &key);
190         if (lmaster >= ctdb->num_nodes) {
191                 DEBUG(DEBUG_CRIT, (__location__
192                                    " lmaster[%u] >= ctdb->num_nodes[%u] for key"
193                                    " with hash[%u]!\n",
194                                    (unsigned)lmaster,
195                                    (unsigned)ctdb->num_nodes,
196                                    (unsigned)ctdb_hash(&key)));
197                 return -1;
198         }
199
200         if (data.dsize != sizeof(struct ctdb_ltdb_header)) {
201                 /* its not a deleted record */
202                 return 0;
203         }
204
205         hdr = (struct ctdb_ltdb_header *)data.dptr;
206
207         if (hdr->dmaster != ctdb->pnn) {
208                 return 0;
209         }
210
211         if (lmaster == ctdb->pnn) {
212                 /*
213                  * We are both lmaster and dmaster, and the record * is empty.
214                  * So we should be able to delete it.
215                  */
216                 res = add_record_to_delete_tree(vdata, key, hdr);
217         } else {
218                 /*
219                  * We are not lmaster.
220                  * Add the record to the blob ready to send to the nodes.
221                  */
222                 res = add_record_to_vacuum_fetch_list(vdata, key);
223         }
224
225         return res;
226 }
227
228 /*
229  * traverse the tree of records to delete and marshall them into
230  * a blob
231  */
232 static void delete_traverse(void *param, void *data)
233 {
234         struct delete_record_data *dd = talloc_get_type(data, struct delete_record_data);
235         struct delete_records_list *recs = talloc_get_type(param, struct delete_records_list);
236         struct ctdb_rec_data *rec;
237         size_t old_size;
238
239         rec = ctdb_marshall_record(dd, recs->records->db_id, dd->key, &dd->hdr, tdb_null);
240         if (rec == NULL) {
241                 DEBUG(DEBUG_ERR, (__location__ " failed to marshall record\n"));
242                 return;
243         }
244
245         old_size = talloc_get_size(recs->records);
246         recs->records = talloc_realloc_size(NULL, recs->records, old_size + rec->length);
247         if (recs->records == NULL) {
248                 DEBUG(DEBUG_ERR,(__location__ " Failed to expand\n"));
249                 return;
250         }
251         recs->records->count++;
252         memcpy(old_size+(uint8_t *)(recs->records), rec, rec->length);
253 }
254
255 /**
256  * traverse function for the traversal of the delete_queue,
257  * the fast-path vacuuming list.
258  *
259  *  - If the record has been migrated off the node
260  *    or has been revived (filled with data) on the node,
261  *    then skip the record.
262  *
263  *  - If the current node is the record's lmaster and it is
264  *    a record that has never been migrated with data, then
265  *    delete the record from the local tdb.
266  *
267  *  - If the current node is the record's lmaster and it has
268  *    been migrated with data, then schedule it for the normal
269  *    vacuuming procedure (i.e. add it to the delete_list).
270  *
271  *  - If the current node is NOT the record's lmaster then
272  *    add it to the list of records that are to be sent to
273  *    the lmaster with the VACUUM_FETCH message.
274  */
275 static void delete_queue_traverse(void *param, void *data)
276 {
277         struct delete_record_data *dd =
278                 talloc_get_type(data, struct delete_record_data);
279         struct vacuum_data *vdata = talloc_get_type(param, struct vacuum_data);
280         struct ctdb_db_context *ctdb_db = dd->ctdb_db;
281         struct ctdb_context *ctdb = ctdb_db->ctdb; /* or dd->ctdb ??? */
282         int res;
283         struct ctdb_ltdb_header *header;
284         TDB_DATA tdb_data;
285         uint32_t lmaster;
286
287         res = tdb_chainlock(ctdb_db->ltdb->tdb, dd->key);
288         if (res != 0) {
289                 DEBUG(DEBUG_ERR, (__location__ " Error getting chainlock.\n"));
290                 return;
291         }
292
293         tdb_data = tdb_fetch(ctdb_db->ltdb->tdb, dd->key);
294         if (tdb_data.dsize < sizeof(struct ctdb_ltdb_header)) {
295                 /* Does not exist or not a ctdb record. Skip. */
296                 goto done;
297         }
298
299         if (tdb_data.dsize > sizeof(struct ctdb_ltdb_header)) {
300                 /* The record has been recycled (filled with data). Skip. */
301                 goto done;
302         }
303
304         header = (struct ctdb_ltdb_header *)tdb_data.dptr;
305
306         if (header->dmaster != ctdb->pnn) {
307                 /* The record has been migrated off the node. Skip. */
308                 goto done;
309         }
310
311
312         if (header->rsn != dd->hdr.rsn) {
313                 /*
314                  * The record has been migrated off the node and back again.
315                  * But not requeued for deletion. Skip it.
316                  */
317                 goto done;
318         }
319
320         /*
321          * We are dmaster, and the record has no data, and it has
322          * not been migrated after it has been queued for deletion.
323          *
324          * At this stage, the record could still have been revived locally
325          * and last been written with empty data. This can only be
326          * fixed with the addition of an active or delete flag. (TODO)
327          */
328
329         lmaster = ctdb_lmaster(ctdb_db->ctdb, &dd->key);
330
331         if (lmaster != ctdb->pnn) {
332                 res = add_record_to_vacuum_fetch_list(vdata, dd->key);
333
334                 if (res != 0) {
335                         DEBUG(DEBUG_ERR,
336                               (__location__ " Error adding record to list "
337                                "of records to send to lmaster.\n"));
338                 }
339
340                 goto done;
341         }
342
343         /* use header->flags or dd->hdr.flags ?? */
344         if (dd->hdr.flags & CTDB_REC_FLAG_MIGRATED_WITH_DATA) {
345                 res = add_record_to_delete_tree(vdata, dd->key, &dd->hdr);
346
347                 if (res != 0) {
348                         DEBUG(DEBUG_ERR,
349                               (__location__ " Error adding record to list "
350                                "of records for deletion on lmaster.\n"));
351                 }
352         } else {
353                 res = tdb_delete(ctdb_db->ltdb->tdb, dd->key);
354
355                 if (res != 0) {
356                         DEBUG(DEBUG_ERR,
357                               (__location__ " Error deleting record from local "
358                                "data base.\n"));
359                 }
360         }
361
362 done:
363         if (tdb_data.dptr != NULL) {
364                 free(tdb_data.dptr);
365         }
366         tdb_chainunlock(ctdb_db->ltdb->tdb, dd->key);
367
368         return;
369 }
370
371 /* 
372  * read-only traverse the database in order to find
373  * records that can be deleted and try to delete these
374  * records on the other nodes
375  * this executes in the child context
376  */
377 static int ctdb_vacuum_db(struct ctdb_db_context *ctdb_db, struct vacuum_data *vdata)
378 {
379         struct ctdb_context *ctdb = ctdb_db->ctdb;
380         const char *name = ctdb_db->db_name;
381         int ret, i, pnn;
382
383         ret = ctdb_ctrl_getvnnmap(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE, ctdb, &ctdb->vnn_map);
384         if (ret != 0) {
385                 DEBUG(DEBUG_ERR, ("Unable to get vnnmap from local node\n"));
386                 return ret;
387         }
388
389         pnn = ctdb_ctrl_getpnn(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE);
390         if (pnn == -1) {
391                 DEBUG(DEBUG_ERR, ("Unable to get pnn from local node\n"));
392                 return -1;
393         }
394
395         ctdb->pnn = pnn;
396         /* the list needs to be of length num_nodes */
397         vdata->list = talloc_array(vdata, struct ctdb_marshall_buffer *, ctdb->num_nodes);
398         if (vdata->list == NULL) {
399                 DEBUG(DEBUG_ERR,(__location__ " Out of memory\n"));
400                 return -1;
401         }
402         for (i = 0; i < ctdb->num_nodes; i++) {
403                 vdata->list[i] = (struct ctdb_marshall_buffer *)
404                         talloc_zero_size(vdata->list, 
405                                                          offsetof(struct ctdb_marshall_buffer, data));
406                 if (vdata->list[i] == NULL) {
407                         DEBUG(DEBUG_ERR,(__location__ " Out of memory\n"));
408                         return -1;
409                 }
410                 vdata->list[i]->db_id = ctdb_db->db_id;
411         }
412
413         /* read-only traverse, looking for records that might be able to be vacuumed */
414         if (tdb_traverse_read(ctdb_db->ltdb->tdb, vacuum_traverse, vdata) == -1 ||
415             vdata->traverse_error) {
416                 DEBUG(DEBUG_ERR,(__location__ " Traverse error in vacuuming '%s'\n", name));
417                 return -1;              
418         }
419
420         /*
421          * For records where we are not the lmaster,
422          * tell the lmaster to fetch the record.
423          */
424         for (i = 0; i < ctdb->num_nodes; i++) {
425                 TDB_DATA data;
426
427                 if (ctdb->nodes[i]->pnn == ctdb->pnn) {
428                         continue;
429                 }
430
431                 if (vdata->list[i]->count == 0) {
432                         continue;
433                 }
434
435                 DEBUG(DEBUG_INFO, ("Found %u records for lmaster %u in '%s'\n",
436                                    vdata->list[i]->count, ctdb->nodes[i]->pnn,
437                                    name));
438
439                 data.dsize = talloc_get_size(vdata->list[i]);
440                 data.dptr  = (void *)vdata->list[i];
441                 if (ctdb_client_send_message(ctdb, ctdb->nodes[i]->pnn, CTDB_SRVID_VACUUM_FETCH, data) != 0) {
442                         DEBUG(DEBUG_ERR, (__location__ " Failed to send vacuum "
443                                           "fetch message to %u\n",
444                                           ctdb->nodes[i]->pnn));
445                         return -1;
446                 }
447         }       
448
449         /* Process all records we can delete (if any) */
450         if (vdata->delete_count > 0) {
451                 struct delete_records_list *recs;
452                 TDB_DATA indata, outdata;
453                 int32_t res;
454                 struct ctdb_node_map *nodemap;
455                 uint32_t *active_nodes;
456                 int num_active_nodes;
457
458                 recs = talloc_zero(vdata, struct delete_records_list);
459                 if (recs == NULL) {
460                         DEBUG(DEBUG_ERR,(__location__ " Out of memory\n"));
461                         return -1;
462                 }
463                 recs->records = (struct ctdb_marshall_buffer *)
464                         talloc_zero_size(vdata, 
465                                     offsetof(struct ctdb_marshall_buffer, data));
466                 if (recs->records == NULL) {
467                         DEBUG(DEBUG_ERR,(__location__ " Out of memory\n"));
468                         return -1;
469                 }
470                 recs->records->db_id = ctdb_db->db_id;
471
472                 /* 
473                  * traverse the tree of all records we want to delete and
474                  * create a blob we can send to the other nodes.
475                  */
476                 trbt_traversearray32(vdata->delete_tree, 1, delete_traverse, recs);
477
478                 indata.dsize = talloc_get_size(recs->records);
479                 indata.dptr  = (void *)recs->records;
480
481                 /* 
482                  * now tell all the active nodes to delete all these records
483                  * (if possible)
484                  */
485
486                 ret = ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(),
487                                            CTDB_CURRENT_NODE,
488                                            recs, /* talloc context */
489                                            &nodemap);
490                 if (ret != 0) {
491                         DEBUG(DEBUG_ERR,(__location__ " unable to get node map\n"));
492                         return -1;
493                 }
494
495                 active_nodes = list_of_active_nodes(ctdb, nodemap,
496                                                     nodemap, /* talloc context */
497                                                     false /* include self */);
498                 /* yuck! ;-) */
499                 num_active_nodes = talloc_get_size(active_nodes)/sizeof(*active_nodes);
500
501                 for (i = 0; i < num_active_nodes; i++) {
502                         struct ctdb_marshall_buffer *records;
503                         struct ctdb_rec_data *rec;
504
505                         ret = ctdb_control(ctdb, active_nodes[i], 0,
506                                         CTDB_CONTROL_TRY_DELETE_RECORDS, 0,
507                                         indata, recs, &outdata, &res,
508                                         NULL, NULL);
509                         if (ret != 0 || res != 0) {
510                                 DEBUG(DEBUG_ERR, ("Failed to delete records on "
511                                                   "node %u: ret[%d] res[%d]\n",
512                                                   active_nodes[i], ret, res));
513                                 return -1;
514                         }
515
516                         /* 
517                          * outdata countains the list of records coming back
518                          * from the node which the node could not delete
519                          */
520                         records = (struct ctdb_marshall_buffer *)outdata.dptr;
521                         rec = (struct ctdb_rec_data *)&records->data[0];
522                         while (records->count-- > 1) {
523                                 TDB_DATA reckey, recdata;
524                                 struct ctdb_ltdb_header *rechdr;
525
526                                 reckey.dptr = &rec->data[0];
527                                 reckey.dsize = rec->keylen;
528                                 recdata.dptr = &rec->data[reckey.dsize];
529                                 recdata.dsize = rec->datalen;
530
531                                 if (recdata.dsize < sizeof(struct ctdb_ltdb_header)) {
532                                         DEBUG(DEBUG_CRIT,(__location__ " bad ltdb record\n"));
533                                         return -1;
534                                 }
535                                 rechdr = (struct ctdb_ltdb_header *)recdata.dptr;
536                                 recdata.dptr += sizeof(*rechdr);
537                                 recdata.dsize -= sizeof(*rechdr);
538
539                                 /* 
540                                  * that other node couldnt delete the record
541                                  * so we should delete it and thereby remove it from the tree
542                                  */
543                                 talloc_free(trbt_lookup32(vdata->delete_tree, ctdb_hash(&reckey)));
544
545                                 rec = (struct ctdb_rec_data *)(rec->length + (uint8_t *)rec);
546                         }           
547                 }
548
549                 /* free nodemap and active_nodes */
550                 talloc_free(nodemap);
551
552                 /* 
553                  * The only records remaining in the tree would be those
554                  * records where all other nodes could successfully
555                  * delete them, so we can safely delete them on the
556                  * lmaster as well. Deletion implictely happens while
557                  * we repack the database. The repack algorithm revisits 
558                  * the tree in order to find the records that don't need
559                  * to be copied / repacked.
560                  */
561         }
562
563         /* this ensures we run our event queue */
564         ctdb_ctrl_getpnn(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE);
565
566         return 0;
567 }
568
569
570 /*
571  * traverse function for repacking
572  */
573 static int repack_traverse(struct tdb_context *tdb, TDB_DATA key, TDB_DATA data, void *private)
574 {
575         struct vacuum_data *vdata = (struct vacuum_data *)private;
576
577         if (vdata->vacuum) {
578                 uint32_t hash = ctdb_hash(&key);
579                 struct delete_record_data *kd;
580                 /*
581                  * check if we can ignore this record because it's in the delete_tree
582                  */
583                 kd = (struct delete_record_data *)trbt_lookup32(vdata->delete_tree, hash);
584                 /*
585                  * there might be hash collisions so we have to compare the keys here to be sure
586                  */
587                 if (kd && kd->key.dsize == key.dsize && memcmp(kd->key.dptr, key.dptr, key.dsize) == 0) {
588                         struct ctdb_ltdb_header *hdr = (struct ctdb_ltdb_header *)data.dptr;
589                         /*
590                          * we have to check if the record hasn't changed in the meantime in order to
591                          * savely remove it from the database
592                          */
593                         if (data.dsize == sizeof(struct ctdb_ltdb_header) &&
594                                 hdr->dmaster == kd->ctdb->pnn &&
595                                 ctdb_lmaster(kd->ctdb, &(kd->key)) == kd->ctdb->pnn &&
596                                 kd->hdr.rsn == hdr->rsn) {
597                                 vdata->vacuumed++;
598                                 return 0;
599                         }
600                 }
601         }
602         if (tdb_store(vdata->dest_db, key, data, TDB_INSERT) != 0) {
603                 vdata->traverse_error = true;
604                 return -1;
605         }
606         vdata->copied++;
607         return 0;
608 }
609
610 /*
611  * repack a tdb
612  */
613 static int ctdb_repack_tdb(struct tdb_context *tdb, TALLOC_CTX *mem_ctx, struct vacuum_data *vdata)
614 {
615         struct tdb_context *tmp_db;
616
617         if (tdb_transaction_start(tdb) != 0) {
618                 DEBUG(DEBUG_ERR,(__location__ " Failed to start transaction\n"));
619                 return -1;
620         }
621
622         tmp_db = tdb_open("tmpdb", tdb_hash_size(tdb),
623                           TDB_INTERNAL|TDB_DISALLOW_NESTING,
624                           O_RDWR|O_CREAT, 0);
625         if (tmp_db == NULL) {
626                 DEBUG(DEBUG_ERR,(__location__ " Failed to create tmp_db\n"));
627                 tdb_transaction_cancel(tdb);
628                 return -1;
629         }
630
631         vdata->traverse_error = false;
632         vdata->dest_db = tmp_db;
633         vdata->vacuum = true;
634         vdata->vacuumed = 0;
635         vdata->copied = 0;
636
637         /*
638          * repack and vacuum on-the-fly by not writing the records that are
639          * no longer needed
640          */
641         if (tdb_traverse_read(tdb, repack_traverse, vdata) == -1) {
642                 DEBUG(DEBUG_ERR,(__location__ " Failed to traverse copying out\n"));
643                 tdb_transaction_cancel(tdb);
644                 tdb_close(tmp_db);
645                 return -1;              
646         }
647
648         DEBUG(DEBUG_INFO,(__location__ " %u records vacuumed\n", vdata->vacuumed));
649         
650         if (vdata->traverse_error) {
651                 DEBUG(DEBUG_ERR,(__location__ " Error during traversal\n"));
652                 tdb_transaction_cancel(tdb);
653                 tdb_close(tmp_db);
654                 return -1;
655         }
656
657         if (tdb_wipe_all(tdb) != 0) {
658                 DEBUG(DEBUG_ERR,(__location__ " Failed to wipe database\n"));
659                 tdb_transaction_cancel(tdb);
660                 tdb_close(tmp_db);
661                 return -1;
662         }
663
664         vdata->traverse_error = false;
665         vdata->dest_db = tdb;
666         vdata->vacuum = false;
667         vdata->copied = 0;
668
669         if (tdb_traverse_read(tmp_db, repack_traverse, vdata) == -1) {
670                 DEBUG(DEBUG_ERR,(__location__ " Failed to traverse copying back\n"));
671                 tdb_transaction_cancel(tdb);
672                 tdb_close(tmp_db);
673                 return -1;              
674         }
675
676         if (vdata->traverse_error) {
677                 DEBUG(DEBUG_ERR,(__location__ " Error during second traversal\n"));
678                 tdb_transaction_cancel(tdb);
679                 tdb_close(tmp_db);
680                 return -1;
681         }
682
683         tdb_close(tmp_db);
684
685
686         if (tdb_transaction_commit(tdb) != 0) {
687                 DEBUG(DEBUG_ERR,(__location__ " Failed to commit\n"));
688                 return -1;
689         }
690         DEBUG(DEBUG_INFO,(__location__ " %u records copied\n", vdata->copied));
691
692         return 0;
693 }
694
695 static int update_tuning_db(struct ctdb_db_context *ctdb_db, struct vacuum_data *vdata, uint32_t freelist)
696 {
697         TALLOC_CTX *tmp_ctx = talloc_new(NULL);
698         TDB_CONTEXT *tune_tdb;
699         TDB_DATA key, value;
700         struct vacuum_tuning_data tdata;
701         struct vacuum_tuning_data *tptr;
702         char *vac_dbname;
703         int flags;
704
705         vac_dbname = talloc_asprintf(tmp_ctx, "%s/%s.%u",
706                                      ctdb_db->ctdb->db_directory_state,
707                                      TUNINGDBNAME, ctdb_db->ctdb->pnn);
708         if (vac_dbname == NULL) {
709                 DEBUG(DEBUG_CRIT,(__location__ " Out of memory error while allocating '%s'\n", vac_dbname));
710                 talloc_free(tmp_ctx);
711                 return -1;
712         }
713
714         flags  = ctdb_db->ctdb->valgrinding ? TDB_NOMMAP : 0;
715         flags |= TDB_DISALLOW_NESTING;
716         tune_tdb = tdb_open(vac_dbname, 0,
717                             flags,
718                             O_RDWR|O_CREAT, 0600);
719         if (tune_tdb == NULL) {
720                 DEBUG(DEBUG_ERR,(__location__ " Failed to create/open %s\n", TUNINGDBNAME));
721                 talloc_free(tmp_ctx);
722                 return -1;
723         }
724         
725         if (tdb_transaction_start(tune_tdb) != 0) {
726                 DEBUG(DEBUG_ERR,(__location__ " Failed to start transaction\n"));
727                 tdb_close(tune_tdb);
728                 return -1;
729         }
730         key.dptr = discard_const(ctdb_db->db_name);
731         key.dsize = strlen(ctdb_db->db_name);
732         value = tdb_fetch(tune_tdb, key);
733
734         if (value.dptr != NULL && value.dsize == sizeof(struct vacuum_tuning_data)) {
735                 tptr = (struct vacuum_tuning_data *)value.dptr;
736                 tdata = *tptr;
737
738                 /*
739                  * re-calc new vacuum interval:
740                  * in case no limit was reached we continously increase the interval
741                  * until vacuum_max_interval is reached
742                  * in case a limit was reached we divide the current interval by 2
743                  * unless vacuum_min_interval is reached
744                  */
745                 if (freelist < vdata->repack_limit &&
746                     vdata->delete_count < vdata->vacuum_limit) {
747                         if (tdata.last_interval < ctdb_db->ctdb->tunable.vacuum_max_interval) {
748                                 tdata.new_interval = tdata.last_interval * 110 / 100;
749                                 DEBUG(DEBUG_INFO,("Increasing vacuum interval %u -> %u for %s\n", 
750                                         tdata.last_interval, tdata.new_interval, ctdb_db->db_name));
751                         }
752                 } else {
753                         tdata.new_interval = tdata.last_interval / 2;
754                         if (tdata.new_interval < ctdb_db->ctdb->tunable.vacuum_min_interval ||
755                                 tdata.new_interval > ctdb_db->ctdb->tunable.vacuum_max_interval) {
756                                 tdata.new_interval = ctdb_db->ctdb->tunable.vacuum_min_interval;
757                         }               
758                         DEBUG(DEBUG_INFO,("Decreasing vacuum interval %u -> %u for %s\n", 
759                                          tdata.last_interval, tdata.new_interval, ctdb_db->db_name));
760                 }
761                 tdata.last_interval = tdata.new_interval;
762         } else {
763                 DEBUG(DEBUG_DEBUG,(__location__ " Cannot find tunedb record for %s. Using default interval\n", ctdb_db->db_name));
764                 tdata.last_num_repack = freelist;
765                 tdata.last_num_empty = vdata->delete_count;
766                 tdata.last_interval = ctdb_db->ctdb->tunable.vacuum_default_interval;
767         }
768
769         if (value.dptr != NULL) {
770                 free(value.dptr);
771         }
772
773         tdata.last_start = vdata->start;
774         tdata.last_duration = timeval_elapsed(&vdata->start);
775
776         value.dptr = (unsigned char *)&tdata;
777         value.dsize = sizeof(tdata);
778
779         if (tdb_store(tune_tdb, key, value, 0) != 0) {
780                 DEBUG(DEBUG_ERR,(__location__ " Unable to store tundb record for %s\n", ctdb_db->db_name));
781                 tdb_transaction_cancel(tune_tdb);
782                 tdb_close(tune_tdb);
783                 talloc_free(tmp_ctx);
784                 return -1;
785         }
786         tdb_transaction_commit(tune_tdb);
787         tdb_close(tune_tdb);
788         talloc_free(tmp_ctx);
789
790         return 0;
791 }
792
793 /*
794  * repack and vaccum a db
795  * called from the child context
796  */
797 static int ctdb_vacuum_and_repack_db(struct ctdb_db_context *ctdb_db,
798                                      TALLOC_CTX *mem_ctx)
799 {
800         uint32_t repack_limit = ctdb_db->ctdb->tunable.repack_limit;
801         uint32_t vacuum_limit = ctdb_db->ctdb->tunable.vacuum_limit;
802         const char *name = ctdb_db->db_name;
803         int size;
804         struct vacuum_data *vdata;
805
806         size = tdb_freelist_size(ctdb_db->ltdb->tdb);
807         if (size == -1) {
808                 DEBUG(DEBUG_ERR,(__location__ " Failed to get freelist size for '%s'\n", name));
809                 return -1;
810         }
811
812         vdata = talloc_zero(mem_ctx, struct vacuum_data);
813         if (vdata == NULL) {
814                 DEBUG(DEBUG_ERR,(__location__ " Out of memory\n"));
815                 return -1;
816         }
817
818         vdata->ctdb = ctdb_db->ctdb;
819         vdata->vacuum_limit = vacuum_limit;
820         vdata->repack_limit = repack_limit;
821         vdata->delete_tree = trbt_create(vdata, 0);
822         vdata->ctdb_db = ctdb_db;
823         if (vdata->delete_tree == NULL) {
824                 DEBUG(DEBUG_ERR,(__location__ " Out of memory\n"));
825                 talloc_free(vdata);
826                 return -1;
827         }
828
829         vdata->start = timeval_current();
830  
831         /*
832          * gather all records that can be deleted in vdata
833          */
834         if (ctdb_vacuum_db(ctdb_db, vdata) != 0) {
835                 DEBUG(DEBUG_ERR,(__location__ " Failed to vacuum '%s'\n", name));
836         }
837
838         /*
839          * decide if a repack is necessary
840          */
841         if (size < repack_limit && vdata->delete_count < vacuum_limit) {
842                 update_tuning_db(ctdb_db, vdata, size);
843                 talloc_free(vdata);
844                 return 0;
845         }
846
847         DEBUG(DEBUG_INFO,("Repacking %s with %u freelist entries and %u records to delete\n", 
848                         name, size, vdata->delete_count));
849
850         /*
851          * repack and implicitely get rid of the records we can delete
852          */
853         if (ctdb_repack_tdb(ctdb_db->ltdb->tdb, mem_ctx, vdata) != 0) {
854                 DEBUG(DEBUG_ERR,(__location__ " Failed to repack '%s'\n", name));
855                 update_tuning_db(ctdb_db, vdata, size);
856                 talloc_free(vdata);
857                 return -1;
858         }
859         update_tuning_db(ctdb_db, vdata, size);
860         talloc_free(vdata);
861
862         return 0;
863 }
864
865 static int get_vacuum_interval(struct ctdb_db_context *ctdb_db)
866 {
867         TALLOC_CTX *tmp_ctx = talloc_new(NULL);
868         TDB_CONTEXT *tdb;
869         TDB_DATA key, value;
870         char *vac_dbname;
871         uint interval = ctdb_db->ctdb->tunable.vacuum_default_interval;
872         struct ctdb_context *ctdb = ctdb_db->ctdb;
873         int flags;
874
875         vac_dbname = talloc_asprintf(tmp_ctx, "%s/%s.%u", ctdb->db_directory, TUNINGDBNAME, ctdb->pnn);
876         if (vac_dbname == NULL) {
877                 DEBUG(DEBUG_CRIT,(__location__ " Out of memory error while allocating '%s'\n", vac_dbname));
878                 talloc_free(tmp_ctx);
879                 return interval;
880         }
881
882         flags  = ctdb_db->ctdb->valgrinding ? TDB_NOMMAP : 0;
883         flags |= TDB_DISALLOW_NESTING;
884         tdb = tdb_open(vac_dbname, 0,
885                        flags,
886                        O_RDWR|O_CREAT, 0600);
887         if (!tdb) {
888                 DEBUG(DEBUG_ERR,("Unable to open/create database %s using default interval. Errno : %s (%d)\n", vac_dbname, strerror(errno), errno));
889                 talloc_free(tmp_ctx);
890                 return interval;
891         }
892
893         key.dptr = discard_const(ctdb_db->db_name);
894         key.dsize = strlen(ctdb_db->db_name);
895
896         value = tdb_fetch(tdb, key);
897
898         if (value.dptr != NULL) {
899                 if (value.dsize == sizeof(struct vacuum_tuning_data)) {
900                         struct vacuum_tuning_data *tptr = (struct vacuum_tuning_data *)value.dptr;
901
902                         interval = tptr->new_interval;
903
904                         if (interval < ctdb->tunable.vacuum_min_interval) {
905                                 interval = ctdb->tunable.vacuum_min_interval;
906                         } 
907                         if (interval > ctdb->tunable.vacuum_max_interval) {
908                                 interval = ctdb->tunable.vacuum_max_interval;
909                         }
910                 }
911                 free(value.dptr);
912         }
913         tdb_close(tdb);
914
915         talloc_free(tmp_ctx);
916
917         return interval;
918 }
919
920 static int vacuum_child_destructor(struct ctdb_vacuum_child_context *child_ctx)
921 {
922         double l = timeval_elapsed(&child_ctx->start_time);
923         struct ctdb_db_context *ctdb_db = child_ctx->vacuum_handle->ctdb_db;
924         struct ctdb_context *ctdb = ctdb_db->ctdb;
925
926         DEBUG(DEBUG_INFO,("Vacuuming took %.3f seconds for database %s\n", l, ctdb_db->db_name));
927
928         if (child_ctx->child_pid != -1) {
929                 kill(child_ctx->child_pid, SIGKILL);
930         }
931
932         DLIST_REMOVE(ctdb->vacuumers, child_ctx);
933
934         event_add_timed(ctdb->ev, child_ctx->vacuum_handle,
935                         timeval_current_ofs(get_vacuum_interval(ctdb_db), 0), 
936                         ctdb_vacuum_event, child_ctx->vacuum_handle);
937
938         return 0;
939 }
940
941 /*
942  * this event is generated when a vacuum child process times out
943  */
944 static void vacuum_child_timeout(struct event_context *ev, struct timed_event *te,
945                                          struct timeval t, void *private_data)
946 {
947         struct ctdb_vacuum_child_context *child_ctx = talloc_get_type(private_data, struct ctdb_vacuum_child_context);
948
949         DEBUG(DEBUG_ERR,("Vacuuming child process timed out for db %s\n", child_ctx->vacuum_handle->ctdb_db->db_name));
950
951         child_ctx->status = VACUUM_TIMEOUT;
952
953         talloc_free(child_ctx);
954 }
955
956
957 /*
958  * this event is generated when a vacuum child process has completed
959  */
960 static void vacuum_child_handler(struct event_context *ev, struct fd_event *fde,
961                              uint16_t flags, void *private_data)
962 {
963         struct ctdb_vacuum_child_context *child_ctx = talloc_get_type(private_data, struct ctdb_vacuum_child_context);
964         char c = 0;
965         int ret;
966
967         DEBUG(DEBUG_INFO,("Vacuuming child process %d finished for db %s\n", child_ctx->child_pid, child_ctx->vacuum_handle->ctdb_db->db_name));
968         child_ctx->child_pid = -1;
969
970         ret = read(child_ctx->fd[0], &c, 1);
971         if (ret != 1 || c != 0) {
972                 child_ctx->status = VACUUM_ERROR;
973                 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));
974         } else {
975                 child_ctx->status = VACUUM_OK;
976         }
977
978         talloc_free(child_ctx);
979 }
980
981 /*
982  * this event is called every time we need to start a new vacuum process
983  */
984 static void
985 ctdb_vacuum_event(struct event_context *ev, struct timed_event *te,
986                                struct timeval t, void *private_data)
987 {
988         struct ctdb_vacuum_handle *vacuum_handle = talloc_get_type(private_data, struct ctdb_vacuum_handle);
989         struct ctdb_db_context *ctdb_db = vacuum_handle->ctdb_db;
990         struct ctdb_context *ctdb = ctdb_db->ctdb;
991         struct ctdb_vacuum_child_context *child_ctx;
992         struct tevent_fd *fde;
993         int ret;
994
995         /* we dont vacuum if we are in recovery mode, or db frozen */
996         if (ctdb->recovery_mode == CTDB_RECOVERY_ACTIVE ||
997             ctdb->freeze_mode[ctdb_db->priority] != CTDB_FREEZE_NONE) {
998                 DEBUG(DEBUG_INFO, ("Not vacuuming %s (%s)\n", ctdb_db->db_name,
999                                    ctdb->recovery_mode == CTDB_RECOVERY_ACTIVE ? "in recovery"
1000                                    : ctdb->freeze_mode[ctdb_db->priority] == CTDB_FREEZE_PENDING
1001                                    ? "freeze pending"
1002                                    : "frozen"));
1003                 event_add_timed(ctdb->ev, vacuum_handle, timeval_current_ofs(ctdb->tunable.vacuum_default_interval, 0), ctdb_vacuum_event, vacuum_handle);
1004                 return;
1005         }
1006
1007         child_ctx = talloc(vacuum_handle, struct ctdb_vacuum_child_context);
1008         if (child_ctx == NULL) {
1009                 DEBUG(DEBUG_CRIT, (__location__ " Failed to allocate child context for vacuuming of %s\n", ctdb_db->db_name));
1010                 ctdb_fatal(ctdb, "Out of memory when crating vacuum child context. Shutting down\n");
1011         }
1012
1013
1014         ret = pipe(child_ctx->fd);
1015         if (ret != 0) {
1016                 talloc_free(child_ctx);
1017                 DEBUG(DEBUG_ERR, ("Failed to create pipe for vacuum child process.\n"));
1018                 event_add_timed(ctdb->ev, vacuum_handle, timeval_current_ofs(ctdb->tunable.vacuum_default_interval, 0), ctdb_vacuum_event, vacuum_handle);
1019                 return;
1020         }
1021
1022         child_ctx->child_pid = ctdb_fork(ctdb);
1023         if (child_ctx->child_pid == (pid_t)-1) {
1024                 close(child_ctx->fd[0]);
1025                 close(child_ctx->fd[1]);
1026                 talloc_free(child_ctx);
1027                 DEBUG(DEBUG_ERR, ("Failed to fork vacuum child process.\n"));
1028                 event_add_timed(ctdb->ev, vacuum_handle, timeval_current_ofs(ctdb->tunable.vacuum_default_interval, 0), ctdb_vacuum_event, vacuum_handle);
1029                 return;
1030         }
1031
1032
1033         if (child_ctx->child_pid == 0) {
1034                 char cc = 0;
1035                 close(child_ctx->fd[0]);
1036
1037                 DEBUG(DEBUG_INFO,("Vacuuming child process %d for db %s started\n", getpid(), ctdb_db->db_name));
1038         
1039                 if (switch_from_server_to_client(ctdb, "vacuum-%s", ctdb_db->db_name) != 0) {
1040                         DEBUG(DEBUG_CRIT, (__location__ "ERROR: failed to switch vacuum daemon into client mode. Shutting down.\n"));
1041                         _exit(1);
1042                 }
1043
1044                 /* 
1045                  * repack the db
1046                  */
1047                 cc = ctdb_vacuum_and_repack_db(ctdb_db, child_ctx);
1048
1049                 write(child_ctx->fd[1], &cc, 1);
1050                 _exit(0);
1051         }
1052
1053         set_close_on_exec(child_ctx->fd[0]);
1054         close(child_ctx->fd[1]);
1055
1056         child_ctx->status = VACUUM_RUNNING;
1057         child_ctx->start_time = timeval_current();
1058
1059         DLIST_ADD(ctdb->vacuumers, child_ctx);
1060         talloc_set_destructor(child_ctx, vacuum_child_destructor);
1061
1062         /*
1063          * Clear the fastpath vacuuming list in the parent.
1064          */
1065         talloc_free(ctdb_db->delete_queue);
1066         ctdb_db->delete_queue = trbt_create(ctdb_db, 0);
1067         if (ctdb_db->delete_queue == NULL) {
1068                 /* fatal here? ... */
1069                 ctdb_fatal(ctdb, "Out of memory when re-creating vacuum tree "
1070                                  "in parent context. Shutting down\n");
1071         }
1072
1073         event_add_timed(ctdb->ev, child_ctx,
1074                 timeval_current_ofs(ctdb->tunable.vacuum_max_run_time, 0),
1075                 vacuum_child_timeout, child_ctx);
1076
1077         DEBUG(DEBUG_DEBUG, (__location__ " Created PIPE FD:%d to child vacuum process\n", child_ctx->fd[0]));
1078
1079         fde = event_add_fd(ctdb->ev, child_ctx, child_ctx->fd[0],
1080                            EVENT_FD_READ, vacuum_child_handler, child_ctx);
1081         tevent_fd_set_auto_close(fde);
1082
1083         vacuum_handle->child_ctx = child_ctx;
1084         child_ctx->vacuum_handle = vacuum_handle;
1085 }
1086
1087 void ctdb_stop_vacuuming(struct ctdb_context *ctdb)
1088 {
1089         /* Simply free them all. */
1090         while (ctdb->vacuumers) {
1091                 DEBUG(DEBUG_INFO, ("Aborting vacuuming for %s (%i)\n",
1092                            ctdb->vacuumers->vacuum_handle->ctdb_db->db_name,
1093                            (int)ctdb->vacuumers->child_pid));
1094                 /* vacuum_child_destructor kills it, removes from list */
1095                 talloc_free(ctdb->vacuumers);
1096         }
1097 }
1098
1099 /* this function initializes the vacuuming context for a database
1100  * starts the vacuuming events
1101  */
1102 int ctdb_vacuum_init(struct ctdb_db_context *ctdb_db)
1103 {
1104         if (ctdb_db->persistent != 0) {
1105                 DEBUG(DEBUG_ERR,("Vacuuming is disabled for persistent database %s\n", ctdb_db->db_name));
1106                 return 0;
1107         }
1108
1109         ctdb_db->vacuum_handle = talloc(ctdb_db, struct ctdb_vacuum_handle);
1110         CTDB_NO_MEMORY(ctdb_db->ctdb, ctdb_db->vacuum_handle);
1111
1112         ctdb_db->vacuum_handle->ctdb_db = ctdb_db;
1113
1114         event_add_timed(ctdb_db->ctdb->ev, ctdb_db->vacuum_handle, 
1115                         timeval_current_ofs(get_vacuum_interval(ctdb_db), 0), 
1116                         ctdb_vacuum_event, ctdb_db->vacuum_handle);
1117
1118         return 0;
1119 }