ctdb-recovery: Switch ctdb_cluster_mutex() to use helper
[obnox/samba/samba-obnox.git] / ctdb / server / ctdb_recover.c
1 /* 
2    ctdb recovery code
3
4    Copyright (C) Andrew Tridgell  2007
5    Copyright (C) Ronnie Sahlberg  2007
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11    
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16    
17    You should have received a copy of the GNU General Public License
18    along with this program; if not, see <http://www.gnu.org/licenses/>.
19 */
20 #include "replace.h"
21 #include "system/time.h"
22 #include "system/network.h"
23 #include "system/filesys.h"
24 #include "system/wait.h"
25
26 #include <talloc.h>
27 #include <tevent.h>
28 #include <tdb.h>
29
30 #include "lib/tdb_wrap/tdb_wrap.h"
31 #include "lib/util/dlinklist.h"
32 #include "lib/util/debug.h"
33 #include "lib/util/time.h"
34 #include "lib/util/util_process.h"
35
36 #include "ctdb_private.h"
37 #include "ctdb_client.h"
38
39 #include "common/system.h"
40 #include "common/common.h"
41 #include "common/logging.h"
42
43 int 
44 ctdb_control_getvnnmap(struct ctdb_context *ctdb, uint32_t opcode, TDB_DATA indata, TDB_DATA *outdata)
45 {
46         struct ctdb_vnn_map_wire *map;
47         size_t len;
48
49         CHECK_CONTROL_DATA_SIZE(0);
50
51         len = offsetof(struct ctdb_vnn_map_wire, map) + sizeof(uint32_t)*ctdb->vnn_map->size;
52         map = talloc_size(outdata, len);
53         CTDB_NO_MEMORY(ctdb, map);
54
55         map->generation = ctdb->vnn_map->generation;
56         map->size = ctdb->vnn_map->size;
57         memcpy(map->map, ctdb->vnn_map->map, sizeof(uint32_t)*map->size);
58
59         outdata->dsize = len;
60         outdata->dptr  = (uint8_t *)map;
61
62         return 0;
63 }
64
65 int
66 ctdb_control_setvnnmap(struct ctdb_context *ctdb, uint32_t opcode, TDB_DATA indata, TDB_DATA *outdata)
67 {
68         struct ctdb_vnn_map_wire *map = (struct ctdb_vnn_map_wire *)indata.dptr;
69
70         if (ctdb->recovery_mode != CTDB_RECOVERY_ACTIVE) {
71                 DEBUG(DEBUG_ERR, ("Attempt to set vnnmap when not in recovery\n"));
72                 return -1;
73         }
74
75         talloc_free(ctdb->vnn_map);
76
77         ctdb->vnn_map = talloc(ctdb, struct ctdb_vnn_map);
78         CTDB_NO_MEMORY(ctdb, ctdb->vnn_map);
79
80         ctdb->vnn_map->generation = map->generation;
81         ctdb->vnn_map->size       = map->size;
82         ctdb->vnn_map->map = talloc_array(ctdb->vnn_map, uint32_t, map->size);
83         CTDB_NO_MEMORY(ctdb, ctdb->vnn_map->map);
84
85         memcpy(ctdb->vnn_map->map, map->map, sizeof(uint32_t)*map->size);
86
87         return 0;
88 }
89
90 int 
91 ctdb_control_getdbmap(struct ctdb_context *ctdb, uint32_t opcode, TDB_DATA indata, TDB_DATA *outdata)
92 {
93         uint32_t i, len;
94         struct ctdb_db_context *ctdb_db;
95         struct ctdb_dbid_map_old *dbid_map;
96
97         CHECK_CONTROL_DATA_SIZE(0);
98
99         len = 0;
100         for(ctdb_db=ctdb->db_list;ctdb_db;ctdb_db=ctdb_db->next){
101                 len++;
102         }
103
104
105         outdata->dsize = offsetof(struct ctdb_dbid_map_old, dbs) + sizeof(dbid_map->dbs[0])*len;
106         outdata->dptr  = (unsigned char *)talloc_zero_size(outdata, outdata->dsize);
107         if (!outdata->dptr) {
108                 DEBUG(DEBUG_ALERT, (__location__ " Failed to allocate dbmap array\n"));
109                 exit(1);
110         }
111
112         dbid_map = (struct ctdb_dbid_map_old *)outdata->dptr;
113         dbid_map->num = len;
114         for (i=0,ctdb_db=ctdb->db_list;ctdb_db;i++,ctdb_db=ctdb_db->next){
115                 dbid_map->dbs[i].db_id       = ctdb_db->db_id;
116                 if (ctdb_db->persistent != 0) {
117                         dbid_map->dbs[i].flags |= CTDB_DB_FLAGS_PERSISTENT;
118                 }
119                 if (ctdb_db->readonly != 0) {
120                         dbid_map->dbs[i].flags |= CTDB_DB_FLAGS_READONLY;
121                 }
122                 if (ctdb_db->sticky != 0) {
123                         dbid_map->dbs[i].flags |= CTDB_DB_FLAGS_STICKY;
124                 }
125         }
126
127         return 0;
128 }
129
130 int
131 ctdb_control_getnodemap(struct ctdb_context *ctdb, uint32_t opcode, TDB_DATA indata, TDB_DATA *outdata)
132 {
133         CHECK_CONTROL_DATA_SIZE(0);
134
135         outdata->dptr  = (unsigned char *)ctdb_node_list_to_map(ctdb->nodes,
136                                                                 ctdb->num_nodes,
137                                                                 outdata);
138         if (outdata->dptr == NULL) {
139                 return -1;
140         }
141
142         outdata->dsize = talloc_get_size(outdata->dptr);
143
144         return 0;
145 }
146
147 /*
148   reload the nodes file
149 */
150 int
151 ctdb_control_reload_nodes_file(struct ctdb_context *ctdb, uint32_t opcode)
152 {
153         int i, num_nodes;
154         TALLOC_CTX *tmp_ctx;
155         struct ctdb_node **nodes;
156
157         tmp_ctx = talloc_new(ctdb);
158
159         /* steal the old nodes file for a while */
160         talloc_steal(tmp_ctx, ctdb->nodes);
161         nodes = ctdb->nodes;
162         ctdb->nodes = NULL;
163         num_nodes = ctdb->num_nodes;
164         ctdb->num_nodes = 0;
165
166         /* load the new nodes file */
167         ctdb_load_nodes_file(ctdb);
168
169         for (i=0; i<ctdb->num_nodes; i++) {
170                 /* keep any identical pre-existing nodes and connections */
171                 if ((i < num_nodes) && ctdb_same_address(&ctdb->nodes[i]->address, &nodes[i]->address)) {
172                         talloc_free(ctdb->nodes[i]);
173                         ctdb->nodes[i] = talloc_steal(ctdb->nodes, nodes[i]);
174                         continue;
175                 }
176
177                 if (ctdb->nodes[i]->flags & NODE_FLAGS_DELETED) {
178                         continue;
179                 }
180
181                 /* any new or different nodes must be added */
182                 if (ctdb->methods->add_node(ctdb->nodes[i]) != 0) {
183                         DEBUG(DEBUG_CRIT, (__location__ " methods->add_node failed at %d\n", i));
184                         ctdb_fatal(ctdb, "failed to add node. shutting down\n");
185                 }
186                 if (ctdb->methods->connect_node(ctdb->nodes[i]) != 0) {
187                         DEBUG(DEBUG_CRIT, (__location__ " methods->add_connect failed at %d\n", i));
188                         ctdb_fatal(ctdb, "failed to connect to node. shutting down\n");
189                 }
190         }
191
192         /* tell the recovery daemon to reaload the nodes file too */
193         ctdb_daemon_send_message(ctdb, ctdb->pnn, CTDB_SRVID_RELOAD_NODES, tdb_null);
194
195         talloc_free(tmp_ctx);
196
197         return 0;
198 }
199
200 /* 
201    a traverse function for pulling all relevent records from pulldb
202  */
203 struct pulldb_data {
204         struct ctdb_context *ctdb;
205         struct ctdb_db_context *ctdb_db;
206         struct ctdb_marshall_buffer *pulldata;
207         uint32_t len;
208         uint32_t allocated_len;
209         bool failed;
210 };
211
212 static int traverse_pulldb(struct tdb_context *tdb, TDB_DATA key, TDB_DATA data, void *p)
213 {
214         struct pulldb_data *params = (struct pulldb_data *)p;
215         struct ctdb_rec_data_old *rec;
216         struct ctdb_context *ctdb = params->ctdb;
217         struct ctdb_db_context *ctdb_db = params->ctdb_db;
218
219         /* add the record to the blob */
220         rec = ctdb_marshall_record(params->pulldata, 0, key, NULL, data);
221         if (rec == NULL) {
222                 params->failed = true;
223                 return -1;
224         }
225         if (params->len + rec->length >= params->allocated_len) {
226                 params->allocated_len = rec->length + params->len + ctdb->tunable.pulldb_preallocation_size;
227                 params->pulldata = talloc_realloc_size(NULL, params->pulldata, params->allocated_len);
228         }
229         if (params->pulldata == NULL) {
230                 DEBUG(DEBUG_CRIT,(__location__ " Failed to expand pulldb_data to %u\n", rec->length + params->len));
231                 ctdb_fatal(params->ctdb, "failed to allocate memory for recovery. shutting down\n");
232         }
233         params->pulldata->count++;
234         memcpy(params->len+(uint8_t *)params->pulldata, rec, rec->length);
235         params->len += rec->length;
236
237         if (ctdb->tunable.db_record_size_warn != 0 && rec->length > ctdb->tunable.db_record_size_warn) {
238                 DEBUG(DEBUG_ERR,("Data record in %s is big. Record size is %d bytes\n", ctdb_db->db_name, (int)rec->length));
239         }
240
241         talloc_free(rec);
242
243         return 0;
244 }
245
246 /*
247   pull a bunch of records from a ltdb, filtering by lmaster
248  */
249 int32_t ctdb_control_pull_db(struct ctdb_context *ctdb, TDB_DATA indata, TDB_DATA *outdata)
250 {
251         struct ctdb_pulldb *pull;
252         struct ctdb_db_context *ctdb_db;
253         struct pulldb_data params;
254         struct ctdb_marshall_buffer *reply;
255
256         pull = (struct ctdb_pulldb *)indata.dptr;
257
258         ctdb_db = find_ctdb_db(ctdb, pull->db_id);
259         if (!ctdb_db) {
260                 DEBUG(DEBUG_ERR,(__location__ " Unknown db 0x%08x\n", pull->db_id));
261                 return -1;
262         }
263
264         if (!ctdb_db_frozen(ctdb_db)) {
265                 DEBUG(DEBUG_ERR,
266                       ("rejecting ctdb_control_pull_db when not frozen\n"));
267                 return -1;
268         }
269
270         reply = talloc_zero(outdata, struct ctdb_marshall_buffer);
271         CTDB_NO_MEMORY(ctdb, reply);
272
273         reply->db_id = pull->db_id;
274
275         params.ctdb = ctdb;
276         params.ctdb_db = ctdb_db;
277         params.pulldata = reply;
278         params.len = offsetof(struct ctdb_marshall_buffer, data);
279         params.allocated_len = params.len;
280         params.failed = false;
281
282         if (ctdb_db->unhealthy_reason) {
283                 /* this is just a warning, as the tdb should be empty anyway */
284                 DEBUG(DEBUG_WARNING,("db(%s) unhealty in ctdb_control_pull_db: %s\n",
285                                      ctdb_db->db_name, ctdb_db->unhealthy_reason));
286         }
287
288         if (ctdb_lockdb_mark(ctdb_db) != 0) {
289                 DEBUG(DEBUG_ERR,(__location__ " Failed to get lock on entire db - failing\n"));
290                 return -1;
291         }
292
293         if (tdb_traverse_read(ctdb_db->ltdb->tdb, traverse_pulldb, &params) == -1) {
294                 DEBUG(DEBUG_ERR,(__location__ " Failed to get traverse db '%s'\n", ctdb_db->db_name));
295                 ctdb_lockdb_unmark(ctdb_db);
296                 talloc_free(params.pulldata);
297                 return -1;
298         }
299
300         ctdb_lockdb_unmark(ctdb_db);
301
302         outdata->dptr = (uint8_t *)params.pulldata;
303         outdata->dsize = params.len;
304
305         if (ctdb->tunable.db_record_count_warn != 0 && params.pulldata->count > ctdb->tunable.db_record_count_warn) {
306                 DEBUG(DEBUG_ERR,("Database %s is big. Contains %d records\n", ctdb_db->db_name, params.pulldata->count));
307         }
308         if (ctdb->tunable.db_size_warn != 0 && outdata->dsize > ctdb->tunable.db_size_warn) {
309                 DEBUG(DEBUG_ERR,("Database %s is big. Contains %d bytes\n", ctdb_db->db_name, (int)outdata->dsize));
310         }
311
312
313         return 0;
314 }
315
316 struct db_pull_state {
317         struct ctdb_context *ctdb;
318         struct ctdb_db_context *ctdb_db;
319         struct ctdb_marshall_buffer *recs;
320         uint32_t pnn;
321         uint64_t srvid;
322         uint32_t num_records;
323 };
324
325 static int traverse_db_pull(struct tdb_context *tdb, TDB_DATA key,
326                             TDB_DATA data, void *private_data)
327 {
328         struct db_pull_state *state = (struct db_pull_state *)private_data;
329         struct ctdb_marshall_buffer *recs;
330
331         recs = ctdb_marshall_add(state->ctdb, state->recs,
332                                  state->ctdb_db->db_id, 0, key, NULL, data);
333         if (recs == NULL) {
334                 TALLOC_FREE(state->recs);
335                 return -1;
336         }
337         state->recs = recs;
338
339         if (talloc_get_size(state->recs) >=
340                         state->ctdb->tunable.rec_buffer_size_limit) {
341                 TDB_DATA buffer;
342                 int ret;
343
344                 buffer = ctdb_marshall_finish(state->recs);
345                 ret = ctdb_daemon_send_message(state->ctdb, state->pnn,
346                                                state->srvid, buffer);
347                 if (ret != 0) {
348                         TALLOC_FREE(state->recs);
349                         return -1;
350                 }
351
352                 state->num_records += state->recs->count;
353                 TALLOC_FREE(state->recs);
354         }
355
356         return 0;
357 }
358
359 int32_t ctdb_control_db_pull(struct ctdb_context *ctdb,
360                              struct ctdb_req_control_old *c,
361                              TDB_DATA indata, TDB_DATA *outdata)
362 {
363         struct ctdb_pulldb_ext *pulldb_ext;
364         struct ctdb_db_context *ctdb_db;
365         struct db_pull_state state;
366         int ret;
367
368         pulldb_ext = (struct ctdb_pulldb_ext *)indata.dptr;
369
370         ctdb_db = find_ctdb_db(ctdb, pulldb_ext->db_id);
371         if (ctdb_db == NULL) {
372                 DEBUG(DEBUG_ERR,(__location__ " Unknown db 0x%08x\n",
373                                  pulldb_ext->db_id));
374                 return -1;
375         }
376
377         if (!ctdb_db_frozen(ctdb_db)) {
378                 DEBUG(DEBUG_ERR,
379                       ("rejecting ctdb_control_pull_db when not frozen\n"));
380                 return -1;
381         }
382
383         if (ctdb_db->unhealthy_reason) {
384                 /* this is just a warning, as the tdb should be empty anyway */
385                 DEBUG(DEBUG_WARNING,
386                       ("db(%s) unhealty in ctdb_control_db_pull: %s\n",
387                        ctdb_db->db_name, ctdb_db->unhealthy_reason));
388         }
389
390         state.ctdb = ctdb;
391         state.ctdb_db = ctdb_db;
392         state.recs = NULL;
393         state.pnn = c->hdr.srcnode;
394         state.srvid = pulldb_ext->srvid;
395         state.num_records = 0;
396
397         if (ctdb_lockdb_mark(ctdb_db) != 0) {
398                 DEBUG(DEBUG_ERR,
399                       (__location__ " Failed to get lock on entire db - failing\n"));
400                 return -1;
401         }
402
403         ret = tdb_traverse_read(ctdb_db->ltdb->tdb, traverse_db_pull, &state);
404         if (ret == -1) {
405                 DEBUG(DEBUG_ERR,
406                       (__location__ " Failed to get traverse db '%s'\n",
407                        ctdb_db->db_name));
408                 ctdb_lockdb_unmark(ctdb_db);
409                 return -1;
410         }
411
412         /* Last few records */
413         if (state.recs != NULL) {
414                 TDB_DATA buffer;
415
416                 buffer = ctdb_marshall_finish(state.recs);
417                 ret = ctdb_daemon_send_message(state.ctdb, state.pnn,
418                                                state.srvid, buffer);
419                 if (ret != 0) {
420                         TALLOC_FREE(state.recs);
421                         ctdb_lockdb_unmark(ctdb_db);
422                         return -1;
423                 }
424
425                 state.num_records += state.recs->count;
426                 TALLOC_FREE(state.recs);
427         }
428
429         ctdb_lockdb_unmark(ctdb_db);
430
431         outdata->dptr = talloc_size(outdata, sizeof(uint32_t));
432         if (outdata->dptr == NULL) {
433                 DEBUG(DEBUG_ERR, (__location__ " Memory allocation error\n"));
434                 return -1;
435         }
436
437         memcpy(outdata->dptr, (uint8_t *)&state.num_records, sizeof(uint32_t));
438         outdata->dsize = sizeof(uint32_t);
439
440         return 0;
441 }
442
443 /*
444   push a bunch of records into a ltdb, filtering by rsn
445  */
446 int32_t ctdb_control_push_db(struct ctdb_context *ctdb, TDB_DATA indata)
447 {
448         struct ctdb_marshall_buffer *reply = (struct ctdb_marshall_buffer *)indata.dptr;
449         struct ctdb_db_context *ctdb_db;
450         int i, ret;
451         struct ctdb_rec_data_old *rec;
452
453         if (indata.dsize < offsetof(struct ctdb_marshall_buffer, data)) {
454                 DEBUG(DEBUG_ERR,(__location__ " invalid data in pulldb reply\n"));
455                 return -1;
456         }
457
458         ctdb_db = find_ctdb_db(ctdb, reply->db_id);
459         if (!ctdb_db) {
460                 DEBUG(DEBUG_ERR,(__location__ " Unknown db 0x%08x\n", reply->db_id));
461                 return -1;
462         }
463
464         if (!ctdb_db_frozen(ctdb_db)) {
465                 DEBUG(DEBUG_ERR,
466                       ("rejecting ctdb_control_push_db when not frozen\n"));
467                 return -1;
468         }
469
470         if (ctdb_lockdb_mark(ctdb_db) != 0) {
471                 DEBUG(DEBUG_ERR,(__location__ " Failed to get lock on entire db - failing\n"));
472                 return -1;
473         }
474
475         rec = (struct ctdb_rec_data_old *)&reply->data[0];
476
477         DEBUG(DEBUG_INFO,("starting push of %u records for dbid 0x%x\n",
478                  reply->count, reply->db_id));
479
480         for (i=0;i<reply->count;i++) {
481                 TDB_DATA key, data;
482                 struct ctdb_ltdb_header *hdr;
483
484                 key.dptr = &rec->data[0];
485                 key.dsize = rec->keylen;
486                 data.dptr = &rec->data[key.dsize];
487                 data.dsize = rec->datalen;
488
489                 if (data.dsize < sizeof(struct ctdb_ltdb_header)) {
490                         DEBUG(DEBUG_CRIT,(__location__ " bad ltdb record\n"));
491                         goto failed;
492                 }
493                 hdr = (struct ctdb_ltdb_header *)data.dptr;
494                 /* strip off any read only record flags. All readonly records
495                    are revoked implicitely by a recovery
496                 */
497                 hdr->flags &= ~CTDB_REC_RO_FLAGS;
498
499                 data.dptr += sizeof(*hdr);
500                 data.dsize -= sizeof(*hdr);
501
502                 ret = ctdb_ltdb_store(ctdb_db, key, hdr, data);
503                 if (ret != 0) {
504                         DEBUG(DEBUG_CRIT, (__location__ " Unable to store record\n"));
505                         goto failed;
506                 }
507
508                 rec = (struct ctdb_rec_data_old *)(rec->length + (uint8_t *)rec);
509         }           
510
511         DEBUG(DEBUG_DEBUG,("finished push of %u records for dbid 0x%x\n",
512                  reply->count, reply->db_id));
513
514         if (ctdb_db->readonly) {
515                 DEBUG(DEBUG_CRIT,("Clearing the tracking database for dbid 0x%x\n",
516                                   ctdb_db->db_id));
517                 if (tdb_wipe_all(ctdb_db->rottdb) != 0) {
518                         DEBUG(DEBUG_ERR,("Failed to wipe tracking database for 0x%x. Dropping read-only delegation support\n", ctdb_db->db_id));
519                         ctdb_db->readonly = false;
520                         tdb_close(ctdb_db->rottdb);
521                         ctdb_db->rottdb = NULL;
522                         ctdb_db->readonly = false;
523                 }
524                 while (ctdb_db->revokechild_active != NULL) {
525                         talloc_free(ctdb_db->revokechild_active);
526                 }
527         }
528
529         ctdb_lockdb_unmark(ctdb_db);
530         return 0;
531
532 failed:
533         ctdb_lockdb_unmark(ctdb_db);
534         return -1;
535 }
536
537 struct db_push_state {
538         struct ctdb_context *ctdb;
539         struct ctdb_db_context *ctdb_db;
540         uint64_t srvid;
541         uint32_t num_records;
542         bool failed;
543 };
544
545 static void db_push_msg_handler(uint64_t srvid, TDB_DATA indata,
546                                 void *private_data)
547 {
548         struct db_push_state *state = talloc_get_type(
549                 private_data, struct db_push_state);
550         struct ctdb_marshall_buffer *recs;
551         struct ctdb_rec_data_old *rec;
552         int i, ret;
553
554         if (state->failed) {
555                 return;
556         }
557
558         recs = (struct ctdb_marshall_buffer *)indata.dptr;
559         rec = (struct ctdb_rec_data_old *)&recs->data[0];
560
561         DEBUG(DEBUG_INFO, ("starting push of %u records for dbid 0x%x\n",
562                            recs->count, recs->db_id));
563
564         for (i=0; i<recs->count; i++) {
565                 TDB_DATA key, data;
566                 struct ctdb_ltdb_header *hdr;
567
568                 key.dptr = &rec->data[0];
569                 key.dsize = rec->keylen;
570                 data.dptr = &rec->data[key.dsize];
571                 data.dsize = rec->datalen;
572
573                 if (data.dsize < sizeof(struct ctdb_ltdb_header)) {
574                         DEBUG(DEBUG_CRIT,(__location__ " bad ltdb record\n"));
575                         goto failed;
576                 }
577
578                 hdr = (struct ctdb_ltdb_header *)data.dptr;
579                 /* Strip off any read only record flags.
580                  * All readonly records are revoked implicitely by a recovery.
581                  */
582                 hdr->flags &= ~CTDB_REC_RO_FLAGS;
583
584                 data.dptr += sizeof(*hdr);
585                 data.dsize -= sizeof(*hdr);
586
587                 ret = ctdb_ltdb_store(state->ctdb_db, key, hdr, data);
588                 if (ret != 0) {
589                         DEBUG(DEBUG_ERR,
590                               (__location__ " Unable to store record\n"));
591                         goto failed;
592                 }
593
594                 rec = (struct ctdb_rec_data_old *)(rec->length + (uint8_t *)rec);
595         }
596
597         DEBUG(DEBUG_DEBUG, ("finished push of %u records for dbid 0x%x\n",
598                             recs->count, recs->db_id));
599
600         state->num_records += recs->count;
601         return;
602
603 failed:
604         state->failed = true;
605 }
606
607 int32_t ctdb_control_db_push_start(struct ctdb_context *ctdb, TDB_DATA indata)
608 {
609         struct ctdb_pulldb_ext *pulldb_ext;
610         struct ctdb_db_context *ctdb_db;
611         struct db_push_state *state;
612         int ret;
613
614         pulldb_ext = (struct ctdb_pulldb_ext *)indata.dptr;
615
616         ctdb_db = find_ctdb_db(ctdb, pulldb_ext->db_id);
617         if (ctdb_db == NULL) {
618                 DEBUG(DEBUG_ERR,
619                       (__location__ " Unknown db 0x%08x\n", pulldb_ext->db_id));
620                 return -1;
621         }
622
623         if (!ctdb_db_frozen(ctdb_db)) {
624                 DEBUG(DEBUG_ERR,
625                       ("rejecting ctdb_control_db_push_start when not frozen\n"));
626                 return -1;
627         }
628
629         if (ctdb_db->push_started) {
630                 DEBUG(DEBUG_WARNING,
631                       (__location__ " DB push already started for %s\n",
632                        ctdb_db->db_name));
633
634                 /* De-register old state */
635                 state = (struct db_push_state *)ctdb_db->push_state;
636                 if (state != NULL) {
637                         srvid_deregister(ctdb->srv, state->srvid, state);
638                         talloc_free(state);
639                         ctdb_db->push_state = NULL;
640                 }
641         }
642
643         state = talloc_zero(ctdb_db, struct db_push_state);
644         if (state == NULL) {
645                 DEBUG(DEBUG_ERR, (__location__ " Memory allocation error\n"));
646                 return -1;
647         }
648
649         state->ctdb = ctdb;
650         state->ctdb_db = ctdb_db;
651         state->srvid = pulldb_ext->srvid;
652         state->failed = false;
653
654         ret = srvid_register(ctdb->srv, state, state->srvid,
655                              db_push_msg_handler, state);
656         if (ret != 0) {
657                 DEBUG(DEBUG_ERR,
658                       (__location__ " Failed to register srvid for db push\n"));
659                 talloc_free(state);
660                 return -1;
661         }
662
663         if (ctdb_lockdb_mark(ctdb_db) != 0) {
664                 DEBUG(DEBUG_ERR,
665                       (__location__ " Failed to get lock on entire db - failing\n"));
666                 srvid_deregister(ctdb->srv, state->srvid, state);
667                 talloc_free(state);
668                 return -1;
669         }
670
671         ctdb_db->push_started = true;
672         ctdb_db->push_state = state;
673
674         return 0;
675 }
676
677 int32_t ctdb_control_db_push_confirm(struct ctdb_context *ctdb,
678                                      TDB_DATA indata, TDB_DATA *outdata)
679 {
680         uint32_t db_id;
681         struct ctdb_db_context *ctdb_db;
682         struct db_push_state *state;
683
684         db_id = *(uint32_t *)indata.dptr;
685
686         ctdb_db = find_ctdb_db(ctdb, db_id);
687         if (ctdb_db == NULL) {
688                 DEBUG(DEBUG_ERR,(__location__ " Unknown db 0x%08x\n", db_id));
689                 return -1;
690         }
691
692         if (!ctdb_db_frozen(ctdb_db)) {
693                 DEBUG(DEBUG_ERR,
694                       ("rejecting ctdb_control_db_push_confirm when not frozen\n"));
695                 return -1;
696         }
697
698         if (!ctdb_db->push_started) {
699                 DEBUG(DEBUG_ERR, (__location__ " DB push not started\n"));
700                 return -1;
701         }
702
703         if (ctdb_db->readonly) {
704                 DEBUG(DEBUG_ERR,
705                       ("Clearing the tracking database for dbid 0x%x\n",
706                        ctdb_db->db_id));
707                 if (tdb_wipe_all(ctdb_db->rottdb) != 0) {
708                         DEBUG(DEBUG_ERR,
709                               ("Failed to wipe tracking database for 0x%x."
710                                " Dropping read-only delegation support\n",
711                                ctdb_db->db_id));
712                         ctdb_db->readonly = false;
713                         tdb_close(ctdb_db->rottdb);
714                         ctdb_db->rottdb = NULL;
715                         ctdb_db->readonly = false;
716                 }
717
718                 while (ctdb_db->revokechild_active != NULL) {
719                         talloc_free(ctdb_db->revokechild_active);
720                 }
721         }
722
723         ctdb_lockdb_unmark(ctdb_db);
724
725         state = (struct db_push_state *)ctdb_db->push_state;
726         if (state == NULL) {
727                 DEBUG(DEBUG_ERR, (__location__ " Missing push db state\n"));
728                 return -1;
729         }
730
731         srvid_deregister(ctdb->srv, state->srvid, state);
732
733         outdata->dptr = talloc_size(outdata, sizeof(uint32_t));
734         if (outdata->dptr == NULL) {
735                 DEBUG(DEBUG_ERR, (__location__ " Memory allocation error\n"));
736                 talloc_free(state);
737                 ctdb_db->push_state = NULL;
738                 return -1;
739         }
740
741         memcpy(outdata->dptr, (uint8_t *)&state->num_records, sizeof(uint32_t));
742         outdata->dsize = sizeof(uint32_t);
743
744         talloc_free(state);
745         ctdb_db->push_state = NULL;
746
747         return 0;
748 }
749
750 struct ctdb_cluster_mutex_handle;
751 typedef void (*cluster_mutex_handler_t) (
752         struct ctdb_context *ctdb,
753         char status,
754         double latency,
755         struct ctdb_cluster_mutex_handle *h,
756         void *private_data);
757
758 struct ctdb_cluster_mutex_handle {
759         struct ctdb_context *ctdb;
760         cluster_mutex_handler_t handler;
761         void *private_data;
762         int fd[2];
763         struct tevent_timer *te;
764         struct tevent_fd *fde;
765         pid_t child;
766         struct timeval start_time;
767 };
768
769 static void set_recmode_handler(struct ctdb_context *ctdb,
770                                 char status,
771                                 double latency,
772                                 struct ctdb_cluster_mutex_handle *h,
773                                 void *private_data)
774 {
775         /* It would be good to use talloc_get_type() here.  However,
776          * the name of the packet is manually set - not sure why.
777          * Could use talloc_check_name() but this seems like a lot of
778          * manual overkill. */
779         struct ctdb_req_control_old *c =
780                 (struct ctdb_req_control_old *) private_data;
781         int s = 0;
782         const char *err = NULL;
783
784         switch (status) {
785         case '0':
786                 /* Mutex taken */
787                 DEBUG(DEBUG_ERR,
788                       ("ERROR: Daemon able to take recovery lock on \"%s\" during recovery\n",
789                        ctdb->recovery_lock_file));
790                 s = -1;
791                 err = "Took recovery lock from daemon during recovery - probably a cluster filesystem lock coherence problem";
792                 break;
793
794         case '1':
795                 /* Contention */
796                 DEBUG(DEBUG_DEBUG, (__location__ " Recovery lock check OK\n"));
797                 ctdb->recovery_mode = CTDB_RECOVERY_NORMAL;
798                 ctdb_process_deferred_attach(ctdb);
799
800                 s = 0;
801
802                 CTDB_UPDATE_RECLOCK_LATENCY(ctdb, "daemon reclock",
803                                             reclock.ctdbd, latency);
804                 break;
805
806         case '2':
807                 /* Timeout.  Consider this a success, not a failure,
808                  * as we failed to set the recovery lock which is what
809                  * we wanted.  This can be caused by the cluster
810                  * filesystem being very slow to arbitrate locks
811                  * immediately after a node failure. */
812                 DEBUG(DEBUG_WARNING,
813                       (__location__
814                        "Time out getting recovery lock, allowing recmode set anyway\n"));
815                 ctdb->recovery_mode = CTDB_RECOVERY_NORMAL;
816                 ctdb_process_deferred_attach(ctdb);
817
818                 s = 0;
819                 break;
820
821         default:
822                 DEBUG(DEBUG_ERR,
823                       ("Unexpected error when testing recovery lock\n"));
824                 s = -1;
825                 err = "Unexpected error when testing recovery lock";
826         }
827
828         ctdb_request_control_reply(ctdb, c, NULL, s, err);
829         talloc_free(h);
830 }
831
832 /*
833   called if our set_recmode child times out. this would happen if
834   ctdb_recovery_lock() would block.
835  */
836 static void cluster_mutex_timeout(struct tevent_context *ev,
837                                   struct tevent_timer *te,
838                                   struct timeval t, void *private_data)
839 {
840         struct ctdb_cluster_mutex_handle *h =
841                 talloc_get_type(private_data, struct ctdb_cluster_mutex_handle);
842         double latency = timeval_elapsed(&h->start_time);
843
844         if (h->handler != NULL) {
845                 h->handler(h->ctdb, '2', latency, h, h->private_data);
846         }
847 }
848
849
850 /* When the handle is freed it causes any child holding the mutex to
851  * be killed, thus freeing the mutex */
852 static int cluster_mutex_destructor(struct ctdb_cluster_mutex_handle *h)
853 {
854         if (h->fd[0] != -1) {
855                 h->fd[0] = -1;
856         }
857         ctdb_kill(h->ctdb, h->child, SIGKILL);
858         return 0;
859 }
860
861 /* this is called when the client process has completed ctdb_recovery_lock()
862    and has written data back to us through the pipe.
863 */
864 static void cluster_mutex_handler(struct tevent_context *ev,
865                                   struct tevent_fd *fde,
866                                   uint16_t flags, void *private_data)
867 {
868         struct ctdb_cluster_mutex_handle *h=
869                 talloc_get_type(private_data, struct ctdb_cluster_mutex_handle);
870         double latency = timeval_elapsed(&h->start_time);
871         char c = '0';
872         int ret;
873
874         /* Got response from child process so abort timeout */
875         TALLOC_FREE(h->te);
876
877         ret = sys_read(h->fd[0], &c, 1);
878
879         /* If the child wrote status then just pass it to the handler.
880          * If no status was written then this is an unexpected error
881          * so pass generic error code to handler. */
882         if (h->handler != NULL) {
883                 h->handler(h->ctdb, ret == 1 ? c : '3', latency,
884                            h, h->private_data);
885         }
886 }
887
888 static void
889 ctdb_drop_all_ips_event(struct tevent_context *ev, struct tevent_timer *te,
890                         struct timeval t, void *private_data)
891 {
892         struct ctdb_context *ctdb = talloc_get_type(private_data, struct ctdb_context);
893
894         DEBUG(DEBUG_ERR,(__location__ " Been in recovery mode for too long. Dropping all IPS\n"));
895         talloc_free(ctdb->release_ips_ctx);
896         ctdb->release_ips_ctx = NULL;
897
898         ctdb_release_all_ips(ctdb);
899 }
900
901 static char cluster_mutex_helper[PATH_MAX+1] = "";
902
903 static bool cluster_mutex_helper_args(TALLOC_CTX *mem_ctx,
904                                       const char *lockfile, char ***argv)
905 {
906         int nargs;
907         char **args = NULL;
908
909         /* Anticipate the size of the array.  Given that lock file is
910          * really now some arbitrary arguments to a configuration
911          * helper, it really needs to be parsed... but not yet. */
912         args = talloc_array(mem_ctx, char *, 3);
913         if (args == NULL) {
914                 DEBUG(DEBUG_ERR,(__location__ " out of memory\n"));
915                 return false;
916         }
917
918         nargs = 0;
919
920         if (!ctdb_set_helper("cluster mutex helper",
921                              cluster_mutex_helper,
922                              sizeof(cluster_mutex_helper),
923                              "CTDB_CLUSTER_MUTEX_HELPER",
924                              CTDB_HELPER_BINDIR, "ctdb_mutex_fcntl_helper")) {
925                 DEBUG(DEBUG_ERR,("ctdb exiting with error: %s\n",
926                                  __location__
927                                  " Unable to set cluster mutex helper\n"));
928                 exit(1);
929         }
930         args[nargs++] = cluster_mutex_helper;
931
932         args[nargs] = talloc_strdup(args, lockfile);
933         if (args[nargs] == NULL) {
934                 talloc_free(args);
935                 DEBUG(DEBUG_ERR,(__location__ " out of memory\n"));
936                 return false;
937         }
938         nargs++;
939
940         /* Make sure last argument is NULL */
941         args[nargs] = NULL;
942
943         *argv = args;
944         return true;
945 }
946
947 static struct ctdb_cluster_mutex_handle *
948 ctdb_cluster_mutex(struct ctdb_context *ctdb, int timeout)
949 {
950         struct ctdb_cluster_mutex_handle *h;
951         char **args;
952         int ret;
953
954         h = talloc(ctdb, struct ctdb_cluster_mutex_handle);
955         if (h == NULL) {
956                 DEBUG(DEBUG_ERR, (__location__ " out of memory\n"));
957                 return NULL;
958         }
959
960         h->start_time = timeval_current();
961         h->fd[0] = -1;
962         h->fd[1] = -1;
963
964         ret = pipe(h->fd);
965         if (ret != 0) {
966                 talloc_free(h);
967                 DEBUG(DEBUG_ERR, (__location__ " Failed to open pipe\n"));
968                 return NULL;
969         }
970         set_close_on_exec(h->fd[0]);
971
972         /* Create arguments for lock helper */
973         if (!cluster_mutex_helper_args(h, ctdb->recovery_lock_file, &args)) {
974                 close(h->fd[0]);
975                 close(h->fd[1]);
976                 talloc_free(h);
977                 return NULL;
978         }
979
980         h->child = ctdb_fork(ctdb);
981         if (h->child == (pid_t)-1) {
982                 close(h->fd[0]);
983                 close(h->fd[1]);
984                 talloc_free(h);
985                 return NULL;
986         }
987
988         if (h->child == 0) {
989                 /* Make stdout point to the pipe */
990                 close(STDOUT_FILENO);
991                 dup2(h->fd[1], STDOUT_FILENO);
992                 close(h->fd[1]);
993
994                 execv(args[0], args);
995
996                 /* Only happens on error */
997                 DEBUG(DEBUG_ERR, (__location__ "execv() failed\n"));
998                 _exit(1);
999         }
1000
1001         /* Parent */
1002
1003         DEBUG(DEBUG_DEBUG, (__location__ " Created PIPE FD:%d\n", h->fd[0]));
1004         set_close_on_exec(h->fd[0]);
1005
1006         close(h->fd[1]);
1007         h->fd[1] = -1;
1008
1009         talloc_set_destructor(h, cluster_mutex_destructor);
1010
1011         if (timeout != 0) {
1012                 h->te = tevent_add_timer(ctdb->ev, h,
1013                                          timeval_current_ofs(timeout, 0),
1014                                          cluster_mutex_timeout, h);
1015         } else {
1016                 h->te = NULL;
1017         }
1018
1019         h->fde = tevent_add_fd(ctdb->ev, h, h->fd[0], TEVENT_FD_READ,
1020                                cluster_mutex_handler, (void *)h);
1021
1022         if (h->fde == NULL) {
1023                 talloc_free(h);
1024                 return NULL;
1025         }
1026         tevent_fd_set_auto_close(h->fde);
1027
1028         h->ctdb = ctdb;
1029         h->handler = NULL;
1030         h->private_data = NULL;
1031
1032         return h;
1033 }
1034
1035
1036 /*
1037  * Set up an event to drop all public ips if we remain in recovery for too
1038  * long
1039  */
1040 int ctdb_deferred_drop_all_ips(struct ctdb_context *ctdb)
1041 {
1042         if (ctdb->release_ips_ctx != NULL) {
1043                 talloc_free(ctdb->release_ips_ctx);
1044         }
1045         ctdb->release_ips_ctx = talloc_new(ctdb);
1046         CTDB_NO_MEMORY(ctdb, ctdb->release_ips_ctx);
1047
1048         tevent_add_timer(ctdb->ev, ctdb->release_ips_ctx,
1049                          timeval_current_ofs(ctdb->tunable.recovery_drop_all_ips, 0),
1050                          ctdb_drop_all_ips_event, ctdb);
1051         return 0;
1052 }
1053
1054 /*
1055   set the recovery mode
1056  */
1057 int32_t ctdb_control_set_recmode(struct ctdb_context *ctdb, 
1058                                  struct ctdb_req_control_old *c,
1059                                  TDB_DATA indata, bool *async_reply,
1060                                  const char **errormsg)
1061 {
1062         uint32_t recmode = *(uint32_t *)indata.dptr;
1063         int i;
1064         struct ctdb_db_context *ctdb_db;
1065         struct ctdb_cluster_mutex_handle *h;
1066
1067         /* if we enter recovery but stay in recovery for too long
1068            we will eventually drop all our ip addresses
1069         */
1070         if (recmode == CTDB_RECOVERY_NORMAL) {
1071                 talloc_free(ctdb->release_ips_ctx);
1072                 ctdb->release_ips_ctx = NULL;
1073         } else {
1074                 if (ctdb_deferred_drop_all_ips(ctdb) != 0) {
1075                         DEBUG(DEBUG_ERR,("Failed to set up deferred drop all ips\n"));
1076                 }
1077         }
1078
1079         if (recmode != ctdb->recovery_mode) {
1080                 DEBUG(DEBUG_NOTICE,(__location__ " Recovery mode set to %s\n", 
1081                          recmode==CTDB_RECOVERY_NORMAL?"NORMAL":"ACTIVE"));
1082         }
1083
1084         if (recmode != CTDB_RECOVERY_NORMAL ||
1085             ctdb->recovery_mode != CTDB_RECOVERY_ACTIVE) {
1086                 ctdb->recovery_mode = recmode;
1087                 return 0;
1088         }
1089
1090         /* From this point: recmode == CTDB_RECOVERY_NORMAL
1091          *
1092          * Therefore, what follows is special handling when setting
1093          * recovery mode back to normal */
1094
1095         for (ctdb_db = ctdb->db_list; ctdb_db != NULL; ctdb_db = ctdb_db->next) {
1096                 if (ctdb_db->generation != ctdb->vnn_map->generation) {
1097                         DEBUG(DEBUG_ERR,
1098                               ("Inconsistent DB generation %u for %s\n",
1099                                ctdb_db->generation, ctdb_db->db_name));
1100                         DEBUG(DEBUG_ERR, ("Recovery mode set to ACTIVE\n"));
1101                         return -1;
1102                 }
1103         }
1104
1105         /* force the databases to thaw */
1106         for (i=1; i<=NUM_DB_PRIORITIES; i++) {
1107                 if (ctdb_db_prio_frozen(ctdb, i)) {
1108                         ctdb_control_thaw(ctdb, i, false);
1109                 }
1110         }
1111
1112         /* release any deferred attach calls from clients */
1113         if (recmode == CTDB_RECOVERY_NORMAL) {
1114                 ctdb_process_deferred_attach(ctdb);
1115         }
1116
1117         if (ctdb->recovery_lock_file == NULL) {
1118                 /* Not using recovery lock file */
1119                 ctdb->recovery_mode = recmode;
1120                 return 0;
1121         }
1122
1123         h = ctdb_cluster_mutex(ctdb, 5);
1124         if (h == NULL) {
1125                 return -1;
1126         }
1127
1128         /* set_recmode_handler() frees h */
1129         h->handler = set_recmode_handler;
1130         h->private_data = talloc_steal(h, c);
1131
1132         *async_reply = true;
1133
1134         return 0;
1135 }
1136
1137
1138 bool ctdb_recovery_have_lock(struct ctdb_context *ctdb)
1139 {
1140         return ctdb->recovery_lock_fd != -1;
1141 }
1142
1143 /*
1144   try and get the recovery lock in shared storage - should only work
1145   on the recovery master recovery daemon. Anywhere else is a bug
1146  */
1147 bool ctdb_recovery_lock(struct ctdb_context *ctdb)
1148 {
1149         struct flock lock;
1150
1151         ctdb->recovery_lock_fd = open(ctdb->recovery_lock_file,
1152                                       O_RDWR|O_CREAT, 0600);
1153         if (ctdb->recovery_lock_fd == -1) {
1154                 DEBUG(DEBUG_ERR,
1155                       ("ctdb_recovery_lock: Unable to open %s - (%s)\n",
1156                        ctdb->recovery_lock_file, strerror(errno)));
1157                 return false;
1158         }
1159
1160         set_close_on_exec(ctdb->recovery_lock_fd);
1161
1162         lock.l_type = F_WRLCK;
1163         lock.l_whence = SEEK_SET;
1164         lock.l_start = 0;
1165         lock.l_len = 1;
1166         lock.l_pid = 0;
1167
1168         if (fcntl(ctdb->recovery_lock_fd, F_SETLK, &lock) != 0) {
1169                 int saved_errno = errno;
1170                 close(ctdb->recovery_lock_fd);
1171                 ctdb->recovery_lock_fd = -1;
1172                 /* Fail silently on these errors, since they indicate
1173                  * lock contention, but log an error for any other
1174                  * failure. */
1175                 if (saved_errno != EACCES &&
1176                     saved_errno != EAGAIN) {
1177                         DEBUG(DEBUG_ERR,("ctdb_recovery_lock: Failed to get "
1178                                          "recovery lock on '%s' - (%s)\n",
1179                                          ctdb->recovery_lock_file,
1180                                          strerror(saved_errno)));
1181                 }
1182                 return false;
1183         }
1184
1185         return true;
1186 }
1187
1188 void ctdb_recovery_unlock(struct ctdb_context *ctdb)
1189 {
1190         if (ctdb->recovery_lock_fd != -1) {
1191                 DEBUG(DEBUG_NOTICE, ("Releasing recovery lock\n"));
1192                 close(ctdb->recovery_lock_fd);
1193                 ctdb->recovery_lock_fd = -1;
1194         }
1195 }
1196
1197 /*
1198   delete a record as part of the vacuum process
1199   only delete if we are not lmaster or dmaster, and our rsn is <= the provided rsn
1200   use non-blocking locks
1201
1202   return 0 if the record was successfully deleted (i.e. it does not exist
1203   when the function returns)
1204   or !0 is the record still exists in the tdb after returning.
1205  */
1206 static int delete_tdb_record(struct ctdb_context *ctdb, struct ctdb_db_context *ctdb_db, struct ctdb_rec_data_old *rec)
1207 {
1208         TDB_DATA key, data, data2;
1209         struct ctdb_ltdb_header *hdr, *hdr2;
1210         
1211         /* these are really internal tdb functions - but we need them here for
1212            non-blocking lock of the freelist */
1213         int tdb_lock_nonblock(struct tdb_context *tdb, int list, int ltype);
1214         int tdb_unlock(struct tdb_context *tdb, int list, int ltype);
1215
1216
1217         key.dsize = rec->keylen;
1218         key.dptr  = &rec->data[0];
1219         data.dsize = rec->datalen;
1220         data.dptr = &rec->data[rec->keylen];
1221
1222         if (ctdb_lmaster(ctdb, &key) == ctdb->pnn) {
1223                 DEBUG(DEBUG_INFO,(__location__ " Called delete on record where we are lmaster\n"));
1224                 return -1;
1225         }
1226
1227         if (data.dsize != sizeof(struct ctdb_ltdb_header)) {
1228                 DEBUG(DEBUG_ERR,(__location__ " Bad record size\n"));
1229                 return -1;
1230         }
1231
1232         hdr = (struct ctdb_ltdb_header *)data.dptr;
1233
1234         /* use a non-blocking lock */
1235         if (tdb_chainlock_nonblock(ctdb_db->ltdb->tdb, key) != 0) {
1236                 return -1;
1237         }
1238
1239         data2 = tdb_fetch(ctdb_db->ltdb->tdb, key);
1240         if (data2.dptr == NULL) {
1241                 tdb_chainunlock(ctdb_db->ltdb->tdb, key);
1242                 return 0;
1243         }
1244
1245         if (data2.dsize < sizeof(struct ctdb_ltdb_header)) {
1246                 if (tdb_lock_nonblock(ctdb_db->ltdb->tdb, -1, F_WRLCK) == 0) {
1247                         if (tdb_delete(ctdb_db->ltdb->tdb, key) != 0) {
1248                                 DEBUG(DEBUG_CRIT,(__location__ " Failed to delete corrupt record\n"));
1249                         }
1250                         tdb_unlock(ctdb_db->ltdb->tdb, -1, F_WRLCK);
1251                         DEBUG(DEBUG_CRIT,(__location__ " Deleted corrupt record\n"));
1252                 }
1253                 tdb_chainunlock(ctdb_db->ltdb->tdb, key);
1254                 free(data2.dptr);
1255                 return 0;
1256         }
1257         
1258         hdr2 = (struct ctdb_ltdb_header *)data2.dptr;
1259
1260         if (hdr2->rsn > hdr->rsn) {
1261                 tdb_chainunlock(ctdb_db->ltdb->tdb, key);
1262                 DEBUG(DEBUG_INFO,(__location__ " Skipping record with rsn=%llu - called with rsn=%llu\n",
1263                          (unsigned long long)hdr2->rsn, (unsigned long long)hdr->rsn));
1264                 free(data2.dptr);
1265                 return -1;
1266         }
1267
1268         /* do not allow deleting record that have readonly flags set. */
1269         if (hdr->flags & CTDB_REC_RO_FLAGS) {
1270                 tdb_chainunlock(ctdb_db->ltdb->tdb, key);
1271                 DEBUG(DEBUG_INFO,(__location__ " Skipping record with readonly flags set\n"));
1272                 free(data2.dptr);
1273                 return -1;
1274         }
1275         if (hdr2->flags & CTDB_REC_RO_FLAGS) {
1276                 tdb_chainunlock(ctdb_db->ltdb->tdb, key);
1277                 DEBUG(DEBUG_INFO,(__location__ " Skipping record with readonly flags set\n"));
1278                 free(data2.dptr);
1279                 return -1;
1280         }
1281
1282         if (hdr2->dmaster == ctdb->pnn) {
1283                 tdb_chainunlock(ctdb_db->ltdb->tdb, key);
1284                 DEBUG(DEBUG_INFO,(__location__ " Attempted delete record where we are the dmaster\n"));
1285                 free(data2.dptr);
1286                 return -1;
1287         }
1288
1289         if (tdb_lock_nonblock(ctdb_db->ltdb->tdb, -1, F_WRLCK) != 0) {
1290                 tdb_chainunlock(ctdb_db->ltdb->tdb, key);
1291                 free(data2.dptr);
1292                 return -1;
1293         }
1294
1295         if (tdb_delete(ctdb_db->ltdb->tdb, key) != 0) {
1296                 tdb_unlock(ctdb_db->ltdb->tdb, -1, F_WRLCK);
1297                 tdb_chainunlock(ctdb_db->ltdb->tdb, key);
1298                 DEBUG(DEBUG_INFO,(__location__ " Failed to delete record\n"));
1299                 free(data2.dptr);
1300                 return -1;
1301         }
1302
1303         tdb_unlock(ctdb_db->ltdb->tdb, -1, F_WRLCK);
1304         tdb_chainunlock(ctdb_db->ltdb->tdb, key);
1305         free(data2.dptr);
1306         return 0;
1307 }
1308
1309
1310
1311 struct recovery_callback_state {
1312         struct ctdb_req_control_old *c;
1313 };
1314
1315
1316 /*
1317   called when the 'recovered' event script has finished
1318  */
1319 static void ctdb_end_recovery_callback(struct ctdb_context *ctdb, int status, void *p)
1320 {
1321         struct recovery_callback_state *state = talloc_get_type(p, struct recovery_callback_state);
1322
1323         ctdb_enable_monitoring(ctdb);
1324         CTDB_INCREMENT_STAT(ctdb, num_recoveries);
1325
1326         if (status != 0) {
1327                 DEBUG(DEBUG_ERR,(__location__ " recovered event script failed (status %d)\n", status));
1328                 if (status == -ETIME) {
1329                         ctdb_ban_self(ctdb);
1330                 }
1331         }
1332
1333         ctdb_request_control_reply(ctdb, state->c, NULL, status, NULL);
1334         talloc_free(state);
1335
1336         gettimeofday(&ctdb->last_recovery_finished, NULL);
1337
1338         if (ctdb->runstate == CTDB_RUNSTATE_FIRST_RECOVERY) {
1339                 ctdb_set_runstate(ctdb, CTDB_RUNSTATE_STARTUP);
1340         }
1341 }
1342
1343 /*
1344   recovery has finished
1345  */
1346 int32_t ctdb_control_end_recovery(struct ctdb_context *ctdb, 
1347                                 struct ctdb_req_control_old *c,
1348                                 bool *async_reply)
1349 {
1350         int ret;
1351         struct recovery_callback_state *state;
1352
1353         DEBUG(DEBUG_NOTICE,("Recovery has finished\n"));
1354
1355         ctdb_persistent_finish_trans3_commits(ctdb);
1356
1357         state = talloc(ctdb, struct recovery_callback_state);
1358         CTDB_NO_MEMORY(ctdb, state);
1359
1360         state->c    = c;
1361
1362         ctdb_disable_monitoring(ctdb);
1363
1364         ret = ctdb_event_script_callback(ctdb, state,
1365                                          ctdb_end_recovery_callback, 
1366                                          state, 
1367                                          CTDB_EVENT_RECOVERED, "%s", "");
1368
1369         if (ret != 0) {
1370                 ctdb_enable_monitoring(ctdb);
1371
1372                 DEBUG(DEBUG_ERR,(__location__ " Failed to end recovery\n"));
1373                 talloc_free(state);
1374                 return -1;
1375         }
1376
1377         /* tell the control that we will be reply asynchronously */
1378         state->c    = talloc_steal(state, c);
1379         *async_reply = true;
1380         return 0;
1381 }
1382
1383 /*
1384   called when the 'startrecovery' event script has finished
1385  */
1386 static void ctdb_start_recovery_callback(struct ctdb_context *ctdb, int status, void *p)
1387 {
1388         struct recovery_callback_state *state = talloc_get_type(p, struct recovery_callback_state);
1389
1390         if (status != 0) {
1391                 DEBUG(DEBUG_ERR,(__location__ " startrecovery event script failed (status %d)\n", status));
1392         }
1393
1394         ctdb_request_control_reply(ctdb, state->c, NULL, status, NULL);
1395         talloc_free(state);
1396 }
1397
1398 /*
1399   run the startrecovery eventscript
1400  */
1401 int32_t ctdb_control_start_recovery(struct ctdb_context *ctdb, 
1402                                 struct ctdb_req_control_old *c,
1403                                 bool *async_reply)
1404 {
1405         int ret;
1406         struct recovery_callback_state *state;
1407
1408         DEBUG(DEBUG_NOTICE,(__location__ " startrecovery eventscript has been invoked\n"));
1409         gettimeofday(&ctdb->last_recovery_started, NULL);
1410
1411         state = talloc(ctdb, struct recovery_callback_state);
1412         CTDB_NO_MEMORY(ctdb, state);
1413
1414         state->c    = talloc_steal(state, c);
1415
1416         ctdb_disable_monitoring(ctdb);
1417
1418         ret = ctdb_event_script_callback(ctdb, state,
1419                                          ctdb_start_recovery_callback, 
1420                                          state,
1421                                          CTDB_EVENT_START_RECOVERY,
1422                                          "%s", "");
1423
1424         if (ret != 0) {
1425                 DEBUG(DEBUG_ERR,(__location__ " Failed to start recovery\n"));
1426                 talloc_free(state);
1427                 return -1;
1428         }
1429
1430         /* tell the control that we will be reply asynchronously */
1431         *async_reply = true;
1432         return 0;
1433 }
1434
1435 /*
1436  try to delete all these records as part of the vacuuming process
1437  and return the records we failed to delete
1438 */
1439 int32_t ctdb_control_try_delete_records(struct ctdb_context *ctdb, TDB_DATA indata, TDB_DATA *outdata)
1440 {
1441         struct ctdb_marshall_buffer *reply = (struct ctdb_marshall_buffer *)indata.dptr;
1442         struct ctdb_db_context *ctdb_db;
1443         int i;
1444         struct ctdb_rec_data_old *rec;
1445         struct ctdb_marshall_buffer *records;
1446
1447         if (indata.dsize < offsetof(struct ctdb_marshall_buffer, data)) {
1448                 DEBUG(DEBUG_ERR,(__location__ " invalid data in try_delete_records\n"));
1449                 return -1;
1450         }
1451
1452         ctdb_db = find_ctdb_db(ctdb, reply->db_id);
1453         if (!ctdb_db) {
1454                 DEBUG(DEBUG_ERR,(__location__ " Unknown db 0x%08x\n", reply->db_id));
1455                 return -1;
1456         }
1457
1458
1459         DEBUG(DEBUG_DEBUG,("starting try_delete_records of %u records for dbid 0x%x\n",
1460                  reply->count, reply->db_id));
1461
1462
1463         /* create a blob to send back the records we couldnt delete */  
1464         records = (struct ctdb_marshall_buffer *)
1465                         talloc_zero_size(outdata, 
1466                                     offsetof(struct ctdb_marshall_buffer, data));
1467         if (records == NULL) {
1468                 DEBUG(DEBUG_ERR,(__location__ " Out of memory\n"));
1469                 return -1;
1470         }
1471         records->db_id = ctdb_db->db_id;
1472
1473
1474         rec = (struct ctdb_rec_data_old *)&reply->data[0];
1475         for (i=0;i<reply->count;i++) {
1476                 TDB_DATA key, data;
1477
1478                 key.dptr = &rec->data[0];
1479                 key.dsize = rec->keylen;
1480                 data.dptr = &rec->data[key.dsize];
1481                 data.dsize = rec->datalen;
1482
1483                 if (data.dsize < sizeof(struct ctdb_ltdb_header)) {
1484                         DEBUG(DEBUG_CRIT,(__location__ " bad ltdb record in indata\n"));
1485                         return -1;
1486                 }
1487
1488                 /* If we cant delete the record we must add it to the reply
1489                    so the lmaster knows it may not purge this record
1490                 */
1491                 if (delete_tdb_record(ctdb, ctdb_db, rec) != 0) {
1492                         size_t old_size;
1493                         struct ctdb_ltdb_header *hdr;
1494
1495                         hdr = (struct ctdb_ltdb_header *)data.dptr;
1496                         data.dptr += sizeof(*hdr);
1497                         data.dsize -= sizeof(*hdr);
1498
1499                         DEBUG(DEBUG_INFO, (__location__ " Failed to vacuum delete record with hash 0x%08x\n", ctdb_hash(&key)));
1500
1501                         old_size = talloc_get_size(records);
1502                         records = talloc_realloc_size(outdata, records, old_size + rec->length);
1503                         if (records == NULL) {
1504                                 DEBUG(DEBUG_ERR,(__location__ " Failed to expand\n"));
1505                                 return -1;
1506                         }
1507                         records->count++;
1508                         memcpy(old_size+(uint8_t *)records, rec, rec->length);
1509                 } 
1510
1511                 rec = (struct ctdb_rec_data_old *)(rec->length + (uint8_t *)rec);
1512         }           
1513
1514
1515         *outdata = ctdb_marshall_finish(records);
1516
1517         return 0;
1518 }
1519
1520 /**
1521  * Store a record as part of the vacuum process:
1522  * This is called from the RECEIVE_RECORD control which
1523  * the lmaster uses to send the current empty copy
1524  * to all nodes for storing, before it lets the other
1525  * nodes delete the records in the second phase with
1526  * the TRY_DELETE_RECORDS control.
1527  *
1528  * Only store if we are not lmaster or dmaster, and our
1529  * rsn is <= the provided rsn. Use non-blocking locks.
1530  *
1531  * return 0 if the record was successfully stored.
1532  * return !0 if the record still exists in the tdb after returning.
1533  */
1534 static int store_tdb_record(struct ctdb_context *ctdb,
1535                             struct ctdb_db_context *ctdb_db,
1536                             struct ctdb_rec_data_old *rec)
1537 {
1538         TDB_DATA key, data, data2;
1539         struct ctdb_ltdb_header *hdr, *hdr2;
1540         int ret;
1541
1542         key.dsize = rec->keylen;
1543         key.dptr = &rec->data[0];
1544         data.dsize = rec->datalen;
1545         data.dptr = &rec->data[rec->keylen];
1546
1547         if (ctdb_lmaster(ctdb, &key) == ctdb->pnn) {
1548                 DEBUG(DEBUG_INFO, (__location__ " Called store_tdb_record "
1549                                    "where we are lmaster\n"));
1550                 return -1;
1551         }
1552
1553         if (data.dsize != sizeof(struct ctdb_ltdb_header)) {
1554                 DEBUG(DEBUG_ERR, (__location__ " Bad record size\n"));
1555                 return -1;
1556         }
1557
1558         hdr = (struct ctdb_ltdb_header *)data.dptr;
1559
1560         /* use a non-blocking lock */
1561         if (tdb_chainlock_nonblock(ctdb_db->ltdb->tdb, key) != 0) {
1562                 DEBUG(DEBUG_INFO, (__location__ " Failed to lock chain in non-blocking mode\n"));
1563                 return -1;
1564         }
1565
1566         data2 = tdb_fetch(ctdb_db->ltdb->tdb, key);
1567         if (data2.dptr == NULL || data2.dsize < sizeof(struct ctdb_ltdb_header)) {
1568                 if (tdb_store(ctdb_db->ltdb->tdb, key, data, 0) == -1) {
1569                         DEBUG(DEBUG_ERR, (__location__ "Failed to store record\n"));
1570                         ret = -1;
1571                         goto done;
1572                 }
1573                 DEBUG(DEBUG_INFO, (__location__ " Stored record\n"));
1574                 ret = 0;
1575                 goto done;
1576         }
1577
1578         hdr2 = (struct ctdb_ltdb_header *)data2.dptr;
1579
1580         if (hdr2->rsn > hdr->rsn) {
1581                 DEBUG(DEBUG_INFO, (__location__ " Skipping record with "
1582                                    "rsn=%llu - called with rsn=%llu\n",
1583                                    (unsigned long long)hdr2->rsn,
1584                                    (unsigned long long)hdr->rsn));
1585                 ret = -1;
1586                 goto done;
1587         }
1588
1589         /* do not allow vacuuming of records that have readonly flags set. */
1590         if (hdr->flags & CTDB_REC_RO_FLAGS) {
1591                 DEBUG(DEBUG_INFO,(__location__ " Skipping record with readonly "
1592                                   "flags set\n"));
1593                 ret = -1;
1594                 goto done;
1595         }
1596         if (hdr2->flags & CTDB_REC_RO_FLAGS) {
1597                 DEBUG(DEBUG_INFO,(__location__ " Skipping record with readonly "
1598                                   "flags set\n"));
1599                 ret = -1;
1600                 goto done;
1601         }
1602
1603         if (hdr2->dmaster == ctdb->pnn) {
1604                 DEBUG(DEBUG_INFO, (__location__ " Attempted to store record "
1605                                    "where we are the dmaster\n"));
1606                 ret = -1;
1607                 goto done;
1608         }
1609
1610         if (tdb_store(ctdb_db->ltdb->tdb, key, data, 0) != 0) {
1611                 DEBUG(DEBUG_INFO,(__location__ " Failed to store record\n"));
1612                 ret = -1;
1613                 goto done;
1614         }
1615
1616         ret = 0;
1617
1618 done:
1619         tdb_chainunlock(ctdb_db->ltdb->tdb, key);
1620         free(data2.dptr);
1621         return  ret;
1622 }
1623
1624
1625
1626 /**
1627  * Try to store all these records as part of the vacuuming process
1628  * and return the records we failed to store.
1629  */
1630 int32_t ctdb_control_receive_records(struct ctdb_context *ctdb,
1631                                      TDB_DATA indata, TDB_DATA *outdata)
1632 {
1633         struct ctdb_marshall_buffer *reply = (struct ctdb_marshall_buffer *)indata.dptr;
1634         struct ctdb_db_context *ctdb_db;
1635         int i;
1636         struct ctdb_rec_data_old *rec;
1637         struct ctdb_marshall_buffer *records;
1638
1639         if (indata.dsize < offsetof(struct ctdb_marshall_buffer, data)) {
1640                 DEBUG(DEBUG_ERR,
1641                       (__location__ " invalid data in receive_records\n"));
1642                 return -1;
1643         }
1644
1645         ctdb_db = find_ctdb_db(ctdb, reply->db_id);
1646         if (!ctdb_db) {
1647                 DEBUG(DEBUG_ERR, (__location__ " Unknown db 0x%08x\n",
1648                                   reply->db_id));
1649                 return -1;
1650         }
1651
1652         DEBUG(DEBUG_DEBUG, ("starting receive_records of %u records for "
1653                             "dbid 0x%x\n", reply->count, reply->db_id));
1654
1655         /* create a blob to send back the records we could not store */
1656         records = (struct ctdb_marshall_buffer *)
1657                         talloc_zero_size(outdata,
1658                                 offsetof(struct ctdb_marshall_buffer, data));
1659         if (records == NULL) {
1660                 DEBUG(DEBUG_ERR, (__location__ " Out of memory\n"));
1661                 return -1;
1662         }
1663         records->db_id = ctdb_db->db_id;
1664
1665         rec = (struct ctdb_rec_data_old *)&reply->data[0];
1666         for (i=0; i<reply->count; i++) {
1667                 TDB_DATA key, data;
1668
1669                 key.dptr = &rec->data[0];
1670                 key.dsize = rec->keylen;
1671                 data.dptr = &rec->data[key.dsize];
1672                 data.dsize = rec->datalen;
1673
1674                 if (data.dsize < sizeof(struct ctdb_ltdb_header)) {
1675                         DEBUG(DEBUG_CRIT, (__location__ " bad ltdb record "
1676                                            "in indata\n"));
1677                         return -1;
1678                 }
1679
1680                 /*
1681                  * If we can not store the record we must add it to the reply
1682                  * so the lmaster knows it may not purge this record.
1683                  */
1684                 if (store_tdb_record(ctdb, ctdb_db, rec) != 0) {
1685                         size_t old_size;
1686                         struct ctdb_ltdb_header *hdr;
1687
1688                         hdr = (struct ctdb_ltdb_header *)data.dptr;
1689                         data.dptr += sizeof(*hdr);
1690                         data.dsize -= sizeof(*hdr);
1691
1692                         DEBUG(DEBUG_INFO, (__location__ " Failed to store "
1693                                            "record with hash 0x%08x in vacuum "
1694                                            "via RECEIVE_RECORDS\n",
1695                                            ctdb_hash(&key)));
1696
1697                         old_size = talloc_get_size(records);
1698                         records = talloc_realloc_size(outdata, records,
1699                                                       old_size + rec->length);
1700                         if (records == NULL) {
1701                                 DEBUG(DEBUG_ERR, (__location__ " Failed to "
1702                                                   "expand\n"));
1703                                 return -1;
1704                         }
1705                         records->count++;
1706                         memcpy(old_size+(uint8_t *)records, rec, rec->length);
1707                 }
1708
1709                 rec = (struct ctdb_rec_data_old *)(rec->length + (uint8_t *)rec);
1710         }
1711
1712         *outdata = ctdb_marshall_finish(records);
1713
1714         return 0;
1715 }
1716
1717
1718 /*
1719   report capabilities
1720  */
1721 int32_t ctdb_control_get_capabilities(struct ctdb_context *ctdb, TDB_DATA *outdata)
1722 {
1723         uint32_t *capabilities = NULL;
1724
1725         capabilities = talloc(outdata, uint32_t);
1726         CTDB_NO_MEMORY(ctdb, capabilities);
1727         *capabilities = ctdb->capabilities;
1728
1729         outdata->dsize = sizeof(uint32_t);
1730         outdata->dptr = (uint8_t *)capabilities;
1731
1732         return 0;       
1733 }
1734
1735 /* The recovery daemon will ping us at regular intervals.
1736    If we havent been pinged for a while we assume the recovery
1737    daemon is inoperable and we restart.
1738 */
1739 static void ctdb_recd_ping_timeout(struct tevent_context *ev,
1740                                    struct tevent_timer *te,
1741                                    struct timeval t, void *p)
1742 {
1743         struct ctdb_context *ctdb = talloc_get_type(p, struct ctdb_context);
1744         uint32_t *count = talloc_get_type(ctdb->recd_ping_count, uint32_t);
1745
1746         DEBUG(DEBUG_ERR, ("Recovery daemon ping timeout. Count : %u\n", *count));
1747
1748         if (*count < ctdb->tunable.recd_ping_failcount) {
1749                 (*count)++;
1750                 tevent_add_timer(ctdb->ev, ctdb->recd_ping_count,
1751                                  timeval_current_ofs(ctdb->tunable.recd_ping_timeout, 0),
1752                                  ctdb_recd_ping_timeout, ctdb);
1753                 return;
1754         }
1755
1756         DEBUG(DEBUG_ERR, ("Final timeout for recovery daemon ping. Restarting recovery daemon. (This can be caused if the cluster filesystem has hung)\n"));
1757
1758         ctdb_stop_recoverd(ctdb);
1759         ctdb_start_recoverd(ctdb);
1760 }
1761
1762 int32_t ctdb_control_recd_ping(struct ctdb_context *ctdb)
1763 {
1764         talloc_free(ctdb->recd_ping_count);
1765
1766         ctdb->recd_ping_count = talloc_zero(ctdb, uint32_t);
1767         CTDB_NO_MEMORY(ctdb, ctdb->recd_ping_count);
1768
1769         if (ctdb->tunable.recd_ping_timeout != 0) {
1770                 tevent_add_timer(ctdb->ev, ctdb->recd_ping_count,
1771                                  timeval_current_ofs(ctdb->tunable.recd_ping_timeout, 0),
1772                                  ctdb_recd_ping_timeout, ctdb);
1773         }
1774
1775         return 0;
1776 }
1777
1778
1779
1780 int32_t ctdb_control_set_recmaster(struct ctdb_context *ctdb, uint32_t opcode, TDB_DATA indata)
1781 {
1782         uint32_t new_recmaster;
1783
1784         CHECK_CONTROL_DATA_SIZE(sizeof(uint32_t));
1785         new_recmaster = ((uint32_t *)(&indata.dptr[0]))[0];
1786
1787         if (ctdb->pnn != new_recmaster && ctdb->recovery_master == ctdb->pnn) {
1788                 DEBUG(DEBUG_NOTICE,
1789                       ("This node (%u) is no longer the recovery master\n", ctdb->pnn));
1790         }
1791
1792         if (ctdb->pnn == new_recmaster && ctdb->recovery_master != new_recmaster) {
1793                 DEBUG(DEBUG_NOTICE,
1794                       ("This node (%u) is now the recovery master\n", ctdb->pnn));
1795         }
1796
1797         ctdb->recovery_master = new_recmaster;
1798         return 0;
1799 }
1800
1801
1802 int32_t ctdb_control_stop_node(struct ctdb_context *ctdb)
1803 {
1804         DEBUG(DEBUG_NOTICE, ("Stopping node\n"));
1805         ctdb_disable_monitoring(ctdb);
1806         ctdb->nodes[ctdb->pnn]->flags |= NODE_FLAGS_STOPPED;
1807
1808         return 0;
1809 }
1810
1811 int32_t ctdb_control_continue_node(struct ctdb_context *ctdb)
1812 {
1813         DEBUG(DEBUG_NOTICE, ("Continue node\n"));
1814         ctdb->nodes[ctdb->pnn]->flags &= ~NODE_FLAGS_STOPPED;
1815
1816         return 0;
1817 }
1818