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