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