add a context and a timed event so that once we have been in recovery
[sahlberg/ctdb.git] / 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 "includes.h"
21 #include "lib/events/events.h"
22 #include "lib/tdb/include/tdb.h"
23 #include "system/time.h"
24 #include "system/network.h"
25 #include "system/filesys.h"
26 #include "system/wait.h"
27 #include "../include/ctdb_private.h"
28 #include "lib/util/dlinklist.h"
29 #include "db_wrap.h"
30
31 /*
32   lock all databases - mark only
33  */
34 static int ctdb_lock_all_databases_mark(struct ctdb_context *ctdb)
35 {
36         struct ctdb_db_context *ctdb_db;
37         if (ctdb->freeze_mode != CTDB_FREEZE_FROZEN) {
38                 DEBUG(DEBUG_ERR,("Attempt to mark all databases locked when not frozen\n"));
39                 return -1;
40         }
41         for (ctdb_db=ctdb->db_list;ctdb_db;ctdb_db=ctdb_db->next) {
42                 if (tdb_lockall_mark(ctdb_db->ltdb->tdb) != 0) {
43                         return -1;
44                 }
45         }
46         return 0;
47 }
48
49 /*
50   lock all databases - unmark only
51  */
52 static int ctdb_lock_all_databases_unmark(struct ctdb_context *ctdb)
53 {
54         struct ctdb_db_context *ctdb_db;
55         if (ctdb->freeze_mode != CTDB_FREEZE_FROZEN) {
56                 DEBUG(DEBUG_ERR,("Attempt to unmark all databases locked when not frozen\n"));
57                 return -1;
58         }
59         for (ctdb_db=ctdb->db_list;ctdb_db;ctdb_db=ctdb_db->next) {
60                 if (tdb_lockall_unmark(ctdb_db->ltdb->tdb) != 0) {
61                         return -1;
62                 }
63         }
64         return 0;
65 }
66
67
68 int 
69 ctdb_control_getvnnmap(struct ctdb_context *ctdb, uint32_t opcode, TDB_DATA indata, TDB_DATA *outdata)
70 {
71         CHECK_CONTROL_DATA_SIZE(0);
72         struct ctdb_vnn_map_wire *map;
73         size_t len;
74
75         len = offsetof(struct ctdb_vnn_map_wire, map) + sizeof(uint32_t)*ctdb->vnn_map->size;
76         map = talloc_size(outdata, len);
77         CTDB_NO_MEMORY(ctdb, map);
78
79         map->generation = ctdb->vnn_map->generation;
80         map->size = ctdb->vnn_map->size;
81         memcpy(map->map, ctdb->vnn_map->map, sizeof(uint32_t)*map->size);
82
83         outdata->dsize = len;
84         outdata->dptr  = (uint8_t *)map;
85
86         return 0;
87 }
88
89 int 
90 ctdb_control_setvnnmap(struct ctdb_context *ctdb, uint32_t opcode, TDB_DATA indata, TDB_DATA *outdata)
91 {
92         struct ctdb_vnn_map_wire *map = (struct ctdb_vnn_map_wire *)indata.dptr;
93
94         if (ctdb->freeze_mode != CTDB_FREEZE_FROZEN) {
95                 DEBUG(DEBUG_ERR,("Attempt to set vnnmap when not frozen\n"));
96                 return -1;
97         }
98
99         talloc_free(ctdb->vnn_map);
100
101         ctdb->vnn_map = talloc(ctdb, struct ctdb_vnn_map);
102         CTDB_NO_MEMORY(ctdb, ctdb->vnn_map);
103
104         ctdb->vnn_map->generation = map->generation;
105         ctdb->vnn_map->size       = map->size;
106         ctdb->vnn_map->map = talloc_array(ctdb->vnn_map, uint32_t, map->size);
107         CTDB_NO_MEMORY(ctdb, ctdb->vnn_map->map);
108
109         memcpy(ctdb->vnn_map->map, map->map, sizeof(uint32_t)*map->size);
110
111         return 0;
112 }
113
114 int 
115 ctdb_control_getdbmap(struct ctdb_context *ctdb, uint32_t opcode, TDB_DATA indata, TDB_DATA *outdata)
116 {
117         uint32_t i, len;
118         struct ctdb_db_context *ctdb_db;
119         struct ctdb_dbid_map *dbid_map;
120
121         CHECK_CONTROL_DATA_SIZE(0);
122
123         len = 0;
124         for(ctdb_db=ctdb->db_list;ctdb_db;ctdb_db=ctdb_db->next){
125                 len++;
126         }
127
128
129         outdata->dsize = offsetof(struct ctdb_dbid_map, dbs) + sizeof(dbid_map->dbs[0])*len;
130         outdata->dptr  = (unsigned char *)talloc_zero_size(outdata, outdata->dsize);
131         if (!outdata->dptr) {
132                 DEBUG(DEBUG_ALERT, (__location__ " Failed to allocate dbmap array\n"));
133                 exit(1);
134         }
135
136         dbid_map = (struct ctdb_dbid_map *)outdata->dptr;
137         dbid_map->num = len;
138         for (i=0,ctdb_db=ctdb->db_list;ctdb_db;i++,ctdb_db=ctdb_db->next){
139                 dbid_map->dbs[i].dbid       = ctdb_db->db_id;
140                 dbid_map->dbs[i].persistent = ctdb_db->persistent;
141         }
142
143         return 0;
144 }
145
146 int 
147 ctdb_control_getnodemap(struct ctdb_context *ctdb, uint32_t opcode, TDB_DATA indata, TDB_DATA *outdata)
148 {
149         uint32_t i, num_nodes;
150         struct ctdb_node_map *node_map;
151
152         CHECK_CONTROL_DATA_SIZE(0);
153
154         num_nodes = ctdb->num_nodes;
155
156         outdata->dsize = offsetof(struct ctdb_node_map, nodes) + num_nodes*sizeof(struct ctdb_node_and_flags);
157         outdata->dptr  = (unsigned char *)talloc_zero_size(outdata, outdata->dsize);
158         if (!outdata->dptr) {
159                 DEBUG(DEBUG_ALERT, (__location__ " Failed to allocate nodemap array\n"));
160                 exit(1);
161         }
162
163         node_map = (struct ctdb_node_map *)outdata->dptr;
164         node_map->num = num_nodes;
165         for (i=0; i<num_nodes; i++) {
166                 if (parse_ip(ctdb->nodes[i]->address.address, &node_map->nodes[i].addr) == 0) {
167                         DEBUG(DEBUG_ERR, (__location__ " Failed to parse %s into a sockaddr\n", ctdb->nodes[i]->address.address));
168                 }
169
170                 node_map->nodes[i].pnn   = ctdb->nodes[i]->pnn;
171                 node_map->nodes[i].flags = ctdb->nodes[i]->flags;
172         }
173
174         return 0;
175 }
176
177 /*
178    get an old style ipv4-only nodemap
179 */
180 int 
181 ctdb_control_getnodemapv4(struct ctdb_context *ctdb, uint32_t opcode, TDB_DATA indata, TDB_DATA *outdata)
182 {
183         uint32_t i, num_nodes;
184         struct ctdb_node_mapv4 *node_map;
185
186         CHECK_CONTROL_DATA_SIZE(0);
187
188         num_nodes = ctdb->num_nodes;
189
190         outdata->dsize = offsetof(struct ctdb_node_mapv4, nodes) + num_nodes*sizeof(struct ctdb_node_and_flagsv4);
191         outdata->dptr  = (unsigned char *)talloc_zero_size(outdata, outdata->dsize);
192         if (!outdata->dptr) {
193                 DEBUG(DEBUG_ALERT, (__location__ " Failed to allocate nodemap array\n"));
194                 exit(1);
195         }
196
197         node_map = (struct ctdb_node_mapv4 *)outdata->dptr;
198         node_map->num = num_nodes;
199         for (i=0; i<num_nodes; i++) {
200                 if (parse_ipv4(ctdb->nodes[i]->address.address, 0, &node_map->nodes[i].sin) == 0) {
201                         DEBUG(DEBUG_ERR, (__location__ " Failed to parse %s into a sockaddr\n", ctdb->nodes[i]->address.address));
202                         return -1;
203                 }
204
205                 node_map->nodes[i].pnn   = ctdb->nodes[i]->pnn;
206                 node_map->nodes[i].flags = ctdb->nodes[i]->flags;
207         }
208
209         return 0;
210 }
211
212 static void
213 ctdb_reload_nodes_event(struct event_context *ev, struct timed_event *te, 
214                                struct timeval t, void *private_data)
215 {
216         int i;
217
218         struct ctdb_context *ctdb = talloc_get_type(private_data, struct ctdb_context);
219
220         ctdb_load_nodes_file(ctdb);
221
222         for (i=0; i<ctdb->num_nodes; i++) {
223                 if (ctdb->methods->add_node(ctdb->nodes[i]) != 0) {
224                         DEBUG(DEBUG_CRIT, (__location__ " methods->add_node failed at %d\n", i));
225                         ctdb_fatal(ctdb, "failed to add node. shutting down\n");
226                 }
227         }
228         ctdb->methods->start(ctdb);
229
230         return;
231 }
232
233 /*
234   reload the nodes file after a short delay (so that we can send the response
235   back first
236 */
237 int 
238 ctdb_control_reload_nodes_file(struct ctdb_context *ctdb, uint32_t opcode)
239 {
240         event_add_timed(ctdb->ev, ctdb, timeval_current_ofs(1,0), ctdb_reload_nodes_event, ctdb);
241
242         return 0;
243 }
244
245 /* 
246    a traverse function for pulling all relevent records from pulldb
247  */
248 struct pulldb_data {
249         struct ctdb_context *ctdb;
250         struct ctdb_marshall_buffer *pulldata;
251         uint32_t len;
252         bool failed;
253 };
254
255 static int traverse_pulldb(struct tdb_context *tdb, TDB_DATA key, TDB_DATA data, void *p)
256 {
257         struct pulldb_data *params = (struct pulldb_data *)p;
258         struct ctdb_rec_data *rec;
259
260         /* add the record to the blob */
261         rec = ctdb_marshall_record(params->pulldata, 0, key, NULL, data);
262         if (rec == NULL) {
263                 params->failed = true;
264                 return -1;
265         }
266         params->pulldata = talloc_realloc_size(NULL, params->pulldata, rec->length + params->len);
267         if (params->pulldata == NULL) {
268                 DEBUG(DEBUG_ERR,(__location__ " Failed to expand pulldb_data to %u (%u records)\n", 
269                          rec->length + params->len, params->pulldata->count));
270                 params->failed = true;
271                 return -1;
272         }
273         params->pulldata->count++;
274         memcpy(params->len+(uint8_t *)params->pulldata, rec, rec->length);
275         params->len += rec->length;
276         talloc_free(rec);
277
278         return 0;
279 }
280
281 /*
282   pul a bunch of records from a ltdb, filtering by lmaster
283  */
284 int32_t ctdb_control_pull_db(struct ctdb_context *ctdb, TDB_DATA indata, TDB_DATA *outdata)
285 {
286         struct ctdb_control_pulldb *pull;
287         struct ctdb_db_context *ctdb_db;
288         struct pulldb_data params;
289         struct ctdb_marshall_buffer *reply;
290
291         if (ctdb->freeze_mode != CTDB_FREEZE_FROZEN) {
292                 DEBUG(DEBUG_DEBUG,("rejecting ctdb_control_pull_db when not frozen\n"));
293                 return -1;
294         }
295
296         pull = (struct ctdb_control_pulldb *)indata.dptr;
297         
298         ctdb_db = find_ctdb_db(ctdb, pull->db_id);
299         if (!ctdb_db) {
300                 DEBUG(DEBUG_ERR,(__location__ " Unknown db 0x%08x\n", pull->db_id));
301                 return -1;
302         }
303
304         reply = talloc_zero(outdata, struct ctdb_marshall_buffer);
305         CTDB_NO_MEMORY(ctdb, reply);
306
307         reply->db_id = pull->db_id;
308
309         params.ctdb = ctdb;
310         params.pulldata = reply;
311         params.len = offsetof(struct ctdb_marshall_buffer, data);
312         params.failed = false;
313
314         if (ctdb_lock_all_databases_mark(ctdb) != 0) {
315                 DEBUG(DEBUG_ERR,(__location__ " Failed to get lock on entired db - failing\n"));
316                 return -1;
317         }
318
319         if (tdb_traverse_read(ctdb_db->ltdb->tdb, traverse_pulldb, &params) == -1) {
320                 DEBUG(DEBUG_ERR,(__location__ " Failed to get traverse db '%s'\n", ctdb_db->db_name));
321                 ctdb_lock_all_databases_unmark(ctdb);
322                 talloc_free(params.pulldata);
323                 return -1;
324         }
325
326         ctdb_lock_all_databases_unmark(ctdb);
327
328         outdata->dptr = (uint8_t *)params.pulldata;
329         outdata->dsize = params.len;
330
331         return 0;
332 }
333
334 /*
335   push a bunch of records into a ltdb, filtering by rsn
336  */
337 int32_t ctdb_control_push_db(struct ctdb_context *ctdb, TDB_DATA indata)
338 {
339         struct ctdb_marshall_buffer *reply = (struct ctdb_marshall_buffer *)indata.dptr;
340         struct ctdb_db_context *ctdb_db;
341         int i, ret;
342         struct ctdb_rec_data *rec;
343
344         if (ctdb->freeze_mode != CTDB_FREEZE_FROZEN) {
345                 DEBUG(DEBUG_DEBUG,("rejecting ctdb_control_push_db when not frozen\n"));
346                 return -1;
347         }
348
349         if (indata.dsize < offsetof(struct ctdb_marshall_buffer, data)) {
350                 DEBUG(DEBUG_ERR,(__location__ " invalid data in pulldb reply\n"));
351                 return -1;
352         }
353
354         ctdb_db = find_ctdb_db(ctdb, reply->db_id);
355         if (!ctdb_db) {
356                 DEBUG(DEBUG_ERR,(__location__ " Unknown db 0x%08x\n", reply->db_id));
357                 return -1;
358         }
359
360         if (ctdb_lock_all_databases_mark(ctdb) != 0) {
361                 DEBUG(DEBUG_ERR,(__location__ " Failed to get lock on entired db - failing\n"));
362                 return -1;
363         }
364
365         rec = (struct ctdb_rec_data *)&reply->data[0];
366
367         DEBUG(DEBUG_INFO,("starting push of %u records for dbid 0x%x\n",
368                  reply->count, reply->db_id));
369
370         for (i=0;i<reply->count;i++) {
371                 TDB_DATA key, data;
372                 struct ctdb_ltdb_header *hdr;
373
374                 key.dptr = &rec->data[0];
375                 key.dsize = rec->keylen;
376                 data.dptr = &rec->data[key.dsize];
377                 data.dsize = rec->datalen;
378
379                 if (data.dsize < sizeof(struct ctdb_ltdb_header)) {
380                         DEBUG(DEBUG_CRIT,(__location__ " bad ltdb record\n"));
381                         goto failed;
382                 }
383                 hdr = (struct ctdb_ltdb_header *)data.dptr;
384                 data.dptr += sizeof(*hdr);
385                 data.dsize -= sizeof(*hdr);
386
387                 ret = ctdb_ltdb_store(ctdb_db, key, hdr, data);
388                 if (ret != 0) {
389                         DEBUG(DEBUG_CRIT, (__location__ " Unable to store record\n"));
390                         goto failed;
391                 }
392
393                 rec = (struct ctdb_rec_data *)(rec->length + (uint8_t *)rec);
394         }           
395
396         DEBUG(DEBUG_DEBUG,("finished push of %u records for dbid 0x%x\n",
397                  reply->count, reply->db_id));
398
399         ctdb_lock_all_databases_unmark(ctdb);
400         return 0;
401
402 failed:
403         ctdb_lock_all_databases_unmark(ctdb);
404         return -1;
405 }
406
407
408 static int traverse_setdmaster(struct tdb_context *tdb, TDB_DATA key, TDB_DATA data, void *p)
409 {
410         uint32_t *dmaster = (uint32_t *)p;
411         struct ctdb_ltdb_header *header = (struct ctdb_ltdb_header *)data.dptr;
412         int ret;
413
414         /* skip if already correct */
415         if (header->dmaster == *dmaster) {
416                 return 0;
417         }
418
419         header->dmaster = *dmaster;
420
421         ret = tdb_store(tdb, key, data, TDB_REPLACE);
422         if (ret) {
423                 DEBUG(DEBUG_CRIT,(__location__ " failed to write tdb data back  ret:%d\n",ret));
424                 return ret;
425         }
426
427         /* TODO: add error checking here */
428
429         return 0;
430 }
431
432 int32_t ctdb_control_set_dmaster(struct ctdb_context *ctdb, TDB_DATA indata)
433 {
434         struct ctdb_control_set_dmaster *p = (struct ctdb_control_set_dmaster *)indata.dptr;
435         struct ctdb_db_context *ctdb_db;
436
437         if (ctdb->freeze_mode != CTDB_FREEZE_FROZEN) {
438                 DEBUG(DEBUG_DEBUG,("rejecting ctdb_control_set_dmaster when not frozen\n"));
439                 return -1;
440         }
441
442         ctdb_db = find_ctdb_db(ctdb, p->db_id);
443         if (!ctdb_db) {
444                 DEBUG(DEBUG_ERR,(__location__ " Unknown db 0x%08x\n", p->db_id));
445                 return -1;
446         }
447
448         if (ctdb_lock_all_databases_mark(ctdb) != 0) {
449                 DEBUG(DEBUG_ERR,(__location__ " Failed to get lock on entired db - failing\n"));
450                 return -1;
451         }
452
453         tdb_traverse(ctdb_db->ltdb->tdb, traverse_setdmaster, &p->dmaster);
454
455         ctdb_lock_all_databases_unmark(ctdb);
456         
457         return 0;
458 }
459
460 struct ctdb_set_recmode_state {
461         struct ctdb_context *ctdb;
462         struct ctdb_req_control *c;
463         uint32_t recmode;
464         int fd[2];
465         struct timed_event *te;
466         struct fd_event *fde;
467         pid_t child;
468 };
469
470 /*
471   called if our set_recmode child times out. this would happen if
472   ctdb_recovery_lock() would block.
473  */
474 static void ctdb_set_recmode_timeout(struct event_context *ev, struct timed_event *te, 
475                                          struct timeval t, void *private_data)
476 {
477         struct ctdb_set_recmode_state *state = talloc_get_type(private_data, 
478                                            struct ctdb_set_recmode_state);
479
480         ctdb_request_control_reply(state->ctdb, state->c, NULL, -1, "timeout in ctdb_set_recmode");
481         talloc_free(state);
482 }
483
484
485 /* when we free the recmode state we must kill any child process.
486 */
487 static int set_recmode_destructor(struct ctdb_set_recmode_state *state)
488 {
489         kill(state->child, SIGKILL);
490         return 0;
491 }
492
493 /* this is called when the client process has completed ctdb_recovery_lock()
494    and has written data back to us through the pipe.
495 */
496 static void set_recmode_handler(struct event_context *ev, struct fd_event *fde, 
497                              uint16_t flags, void *private_data)
498 {
499         struct ctdb_set_recmode_state *state= talloc_get_type(private_data, 
500                                              struct ctdb_set_recmode_state);
501         char c = 0;
502         int ret;
503
504         /* we got a response from our child process so we can abort the
505            timeout.
506         */
507         talloc_free(state->te);
508         state->te = NULL;
509
510
511         /* read the childs status when trying to lock the reclock file.
512            child wrote 0 if everything is fine and 1 if it did manage
513            to lock the file, which would be a problem since that means
514            we got a request to exit from recovery but we could still lock
515            the file   which at this time SHOULD be locked by the recovery
516            daemon on the recmaster
517         */              
518         ret = read(state->fd[0], &c, 1);
519         if (ret != 1 || c != 0) {
520                 ctdb_request_control_reply(state->ctdb, state->c, NULL, -1, "managed to lock reclock file from inside daemon");
521                 talloc_free(state);
522                 return;
523         }
524
525         state->ctdb->recovery_mode = state->recmode;
526
527         ctdb_request_control_reply(state->ctdb, state->c, NULL, 0, NULL);
528         talloc_free(state);
529         return;
530 }
531
532 static void
533 ctdb_drop_all_ips_event(struct event_context *ev, struct timed_event *te, 
534                                struct timeval t, void *private_data)
535 {
536         struct ctdb_context *ctdb = talloc_get_type(private_data, struct ctdb_context);
537
538         DEBUG(DEBUG_INFO,(__location__ " Been in recovery mode for too long. Dropping all IPS\n"));
539         talloc_free(ctdb->release_ips_ctx);
540         ctdb->release_ips_ctx = NULL;
541
542         ctdb_release_all_ips(ctdb);
543 }
544
545 /*
546   set the recovery mode
547  */
548 int32_t ctdb_control_set_recmode(struct ctdb_context *ctdb, 
549                                  struct ctdb_req_control *c,
550                                  TDB_DATA indata, bool *async_reply,
551                                  const char **errormsg)
552 {
553         uint32_t recmode = *(uint32_t *)indata.dptr;
554         int ret;
555         struct ctdb_set_recmode_state *state;
556         pid_t parent = getpid();
557
558         /* if we enter recovery but stay in recovery for too long
559            we will eventually drop all our ip addresses
560         */
561         if (recmode == CTDB_RECOVERY_NORMAL) {
562                 talloc_free(ctdb->release_ips_ctx);
563                 ctdb->release_ips_ctx = NULL;
564         } else {
565                 talloc_free(ctdb->release_ips_ctx);
566                 ctdb->release_ips_ctx = talloc_new(ctdb);
567                 CTDB_NO_MEMORY(ctdb, ctdb->release_ips_ctx);
568
569                 event_add_timed(ctdb->ev, ctdb->release_ips_ctx, timeval_current_ofs(5,0), ctdb_drop_all_ips_event, ctdb);
570         }
571
572
573         if (ctdb->freeze_mode != CTDB_FREEZE_FROZEN) {
574                 DEBUG(DEBUG_ERR,("Attempt to change recovery mode to %u when not frozen\n", 
575                          recmode));
576                 (*errormsg) = "Cannot change recovery mode while not frozen";
577                 return -1;
578         }
579
580         if (recmode != ctdb->recovery_mode) {
581                 DEBUG(DEBUG_NOTICE,(__location__ " Recovery mode set to %s\n", 
582                          recmode==CTDB_RECOVERY_NORMAL?"NORMAL":"ACTIVE"));
583         }
584
585         if (recmode != CTDB_RECOVERY_NORMAL ||
586             ctdb->recovery_mode != CTDB_RECOVERY_ACTIVE) {
587                 ctdb->recovery_mode = recmode;
588                 return 0;
589         }
590
591         /* some special handling when ending recovery mode */
592
593         /* force the databased to thaw */
594         if (ctdb->freeze_handle) {
595                 ctdb_control_thaw(ctdb);
596         }
597
598         state = talloc(ctdb, struct ctdb_set_recmode_state);
599         CTDB_NO_MEMORY(ctdb, state);
600
601         /* For the rest of what needs to be done, we need to do this in
602            a child process since 
603            1, the call to ctdb_recovery_lock() can block if the cluster
604               filesystem is in the process of recovery.
605            2, running of the script may take a while.
606         */
607         ret = pipe(state->fd);
608         if (ret != 0) {
609                 talloc_free(state);
610                 DEBUG(DEBUG_CRIT,(__location__ " Failed to open pipe for set_recmode child\n"));
611                 return -1;
612         }
613
614         state->child = fork();
615         if (state->child == (pid_t)-1) {
616                 close(state->fd[0]);
617                 close(state->fd[1]);
618                 talloc_free(state);
619                 return -1;
620         }
621
622         if (state->child == 0) {
623                 char cc = 0;
624                 close(state->fd[0]);
625
626                 /* we should not be able to get the lock on the nodes list, 
627                   as it should  be held by the recovery master 
628                 */
629                 if (ctdb_recovery_lock(ctdb, false)) {
630                         DEBUG(DEBUG_CRIT,("ERROR: recovery lock file %s not locked when recovering!\n", ctdb->recovery_lock_file));
631                         cc = 1;
632                 }
633
634                 write(state->fd[1], &cc, 1);
635                 /* make sure we die when our parent dies */
636                 while (kill(parent, 0) == 0 || errno != ESRCH) {
637                         sleep(5);
638                 }
639                 _exit(0);
640         }
641         close(state->fd[1]);
642
643         talloc_set_destructor(state, set_recmode_destructor);
644
645         state->te = event_add_timed(ctdb->ev, state, timeval_current_ofs(3, 0),
646                         ctdb_set_recmode_timeout, state);
647
648         state->fde = event_add_fd(ctdb->ev, state, state->fd[0],
649                                 EVENT_FD_READ|EVENT_FD_AUTOCLOSE,
650                                 set_recmode_handler,
651                                 (void *)state);
652         if (state->fde == NULL) {
653                 talloc_free(state);
654                 return -1;
655         }
656
657         state->ctdb    = ctdb;
658         state->recmode = recmode;
659         state->c       = talloc_steal(state, c);
660
661         *async_reply = true;
662
663         return 0;
664 }
665
666
667 /*
668   try and get the recovery lock in shared storage - should only work
669   on the recovery master recovery daemon. Anywhere else is a bug
670  */
671 bool ctdb_recovery_lock(struct ctdb_context *ctdb, bool keep)
672 {
673         struct flock lock;
674
675         if (ctdb->recovery_lock_fd != -1) {
676                 close(ctdb->recovery_lock_fd);
677         }
678         ctdb->recovery_lock_fd = open(ctdb->recovery_lock_file, O_RDWR|O_CREAT, 0600);
679         if (ctdb->recovery_lock_fd == -1) {
680                 DEBUG(DEBUG_ERR,("ctdb_recovery_lock: Unable to open %s - (%s)\n", 
681                          ctdb->recovery_lock_file, strerror(errno)));
682                 return false;
683         }
684
685         set_close_on_exec(ctdb->recovery_lock_fd);
686
687         lock.l_type = F_WRLCK;
688         lock.l_whence = SEEK_SET;
689         lock.l_start = 0;
690         lock.l_len = 1;
691         lock.l_pid = 0;
692
693         if (fcntl(ctdb->recovery_lock_fd, F_SETLK, &lock) != 0) {
694                 close(ctdb->recovery_lock_fd);
695                 ctdb->recovery_lock_fd = -1;
696                 if (keep) {
697                         DEBUG(DEBUG_CRIT,("ctdb_recovery_lock: Failed to get recovery lock on '%s'\n", ctdb->recovery_lock_file));
698                 }
699                 return false;
700         }
701
702         if (!keep) {
703                 close(ctdb->recovery_lock_fd);
704                 ctdb->recovery_lock_fd = -1;
705         }
706
707         DEBUG(DEBUG_NOTICE,("ctdb_recovery_lock: Got recovery lock on '%s'\n", ctdb->recovery_lock_file));
708
709         return true;
710 }
711
712 /*
713   delete a record as part of the vacuum process
714   only delete if we are not lmaster or dmaster, and our rsn is <= the provided rsn
715   use non-blocking locks
716
717   return 0 if the record was successfully deleted (i.e. it does not exist
718   when the function returns)
719   or !0 is the record still exists in the tdb after returning.
720  */
721 static int delete_tdb_record(struct ctdb_context *ctdb, struct ctdb_db_context *ctdb_db, struct ctdb_rec_data *rec)
722 {
723         TDB_DATA key, data;
724         struct ctdb_ltdb_header *hdr, *hdr2;
725         
726         /* these are really internal tdb functions - but we need them here for
727            non-blocking lock of the freelist */
728         int tdb_lock_nonblock(struct tdb_context *tdb, int list, int ltype);
729         int tdb_unlock(struct tdb_context *tdb, int list, int ltype);
730
731
732         key.dsize = rec->keylen;
733         key.dptr  = &rec->data[0];
734         data.dsize = rec->datalen;
735         data.dptr = &rec->data[rec->keylen];
736
737         if (ctdb_lmaster(ctdb, &key) == ctdb->pnn) {
738                 DEBUG(DEBUG_INFO,(__location__ " Called delete on record where we are lmaster\n"));
739                 return -1;
740         }
741
742         if (data.dsize != sizeof(struct ctdb_ltdb_header)) {
743                 DEBUG(DEBUG_ERR,(__location__ " Bad record size\n"));
744                 return -1;
745         }
746
747         hdr = (struct ctdb_ltdb_header *)data.dptr;
748
749         /* use a non-blocking lock */
750         if (tdb_chainlock_nonblock(ctdb_db->ltdb->tdb, key) != 0) {
751                 return -1;
752         }
753
754         data = tdb_fetch(ctdb_db->ltdb->tdb, key);
755         if (data.dptr == NULL) {
756                 tdb_chainunlock(ctdb_db->ltdb->tdb, key);
757                 return 0;
758         }
759
760         if (data.dsize < sizeof(struct ctdb_ltdb_header)) {
761                 if (tdb_lock_nonblock(ctdb_db->ltdb->tdb, -1, F_WRLCK) == 0) {
762                         tdb_delete(ctdb_db->ltdb->tdb, key);
763                         tdb_unlock(ctdb_db->ltdb->tdb, -1, F_WRLCK);
764                         DEBUG(DEBUG_CRIT,(__location__ " Deleted corrupt record\n"));
765                 }
766                 tdb_chainunlock(ctdb_db->ltdb->tdb, key);
767                 free(data.dptr);
768                 return 0;
769         }
770         
771         hdr2 = (struct ctdb_ltdb_header *)data.dptr;
772
773         if (hdr2->rsn > hdr->rsn) {
774                 tdb_chainunlock(ctdb_db->ltdb->tdb, key);
775                 DEBUG(DEBUG_INFO,(__location__ " Skipping record with rsn=%llu - called with rsn=%llu\n",
776                          (unsigned long long)hdr2->rsn, (unsigned long long)hdr->rsn));
777                 free(data.dptr);
778                 return -1;              
779         }
780
781         if (hdr2->dmaster == ctdb->pnn) {
782                 tdb_chainunlock(ctdb_db->ltdb->tdb, key);
783                 DEBUG(DEBUG_INFO,(__location__ " Attempted delete record where we are the dmaster\n"));
784                 free(data.dptr);
785                 return -1;                              
786         }
787
788         if (tdb_lock_nonblock(ctdb_db->ltdb->tdb, -1, F_WRLCK) != 0) {
789                 tdb_chainunlock(ctdb_db->ltdb->tdb, key);
790                 free(data.dptr);
791                 return -1;                              
792         }
793
794         if (tdb_delete(ctdb_db->ltdb->tdb, key) != 0) {
795                 tdb_unlock(ctdb_db->ltdb->tdb, -1, F_WRLCK);
796                 tdb_chainunlock(ctdb_db->ltdb->tdb, key);
797                 DEBUG(DEBUG_INFO,(__location__ " Failed to delete record\n"));
798                 free(data.dptr);
799                 return -1;                                              
800         }
801
802         tdb_unlock(ctdb_db->ltdb->tdb, -1, F_WRLCK);
803         tdb_chainunlock(ctdb_db->ltdb->tdb, key);
804         free(data.dptr);
805         return 0;       
806 }
807
808
809
810 struct recovery_callback_state {
811         struct ctdb_req_control *c;
812 };
813
814
815 /*
816   called when the 'recovered' event script has finished
817  */
818 static void ctdb_end_recovery_callback(struct ctdb_context *ctdb, int status, void *p)
819 {
820         struct recovery_callback_state *state = talloc_get_type(p, struct recovery_callback_state);
821
822         ctdb_enable_monitoring(ctdb);
823
824         if (status != 0) {
825                 DEBUG(DEBUG_ERR,(__location__ " recovered event script failed (status %d)\n", status));
826         }
827
828         ctdb_request_control_reply(ctdb, state->c, NULL, status, NULL);
829         talloc_free(state);
830
831         gettimeofday(&ctdb->last_recovery_finished, NULL);
832 }
833
834 /*
835   recovery has finished
836  */
837 int32_t ctdb_control_end_recovery(struct ctdb_context *ctdb, 
838                                 struct ctdb_req_control *c,
839                                 bool *async_reply)
840 {
841         int ret;
842         struct recovery_callback_state *state;
843
844         DEBUG(DEBUG_NOTICE,("Recovery has finished\n"));
845
846         state = talloc(ctdb, struct recovery_callback_state);
847         CTDB_NO_MEMORY(ctdb, state);
848
849         state->c    = talloc_steal(state, c);
850
851         ctdb_disable_monitoring(ctdb);
852
853         ret = ctdb_event_script_callback(ctdb, 
854                                          timeval_current_ofs(ctdb->tunable.script_timeout, 0),
855                                          state, 
856                                          ctdb_end_recovery_callback, 
857                                          state, "recovered");
858
859         if (ret != 0) {
860                 ctdb_enable_monitoring(ctdb);
861
862                 DEBUG(DEBUG_ERR,(__location__ " Failed to end recovery\n"));
863                 talloc_free(state);
864                 return -1;
865         }
866
867         /* tell the control that we will be reply asynchronously */
868         *async_reply = true;
869         return 0;
870 }
871
872 /*
873   called when the 'startrecovery' event script has finished
874  */
875 static void ctdb_start_recovery_callback(struct ctdb_context *ctdb, int status, void *p)
876 {
877         struct recovery_callback_state *state = talloc_get_type(p, struct recovery_callback_state);
878
879         if (status != 0) {
880                 DEBUG(DEBUG_ERR,(__location__ " startrecovery event script failed (status %d)\n", status));
881         }
882
883         ctdb_request_control_reply(ctdb, state->c, NULL, status, NULL);
884         talloc_free(state);
885 }
886
887 /*
888   run the startrecovery eventscript
889  */
890 int32_t ctdb_control_start_recovery(struct ctdb_context *ctdb, 
891                                 struct ctdb_req_control *c,
892                                 bool *async_reply)
893 {
894         int ret;
895         struct recovery_callback_state *state;
896
897         DEBUG(DEBUG_NOTICE,(__location__ " startrecovery eventscript has been invoked\n"));
898         gettimeofday(&ctdb->last_recovery_started, NULL);
899
900         state = talloc(ctdb, struct recovery_callback_state);
901         CTDB_NO_MEMORY(ctdb, state);
902
903         state->c    = talloc_steal(state, c);
904
905         ctdb_disable_monitoring(ctdb);
906
907         ret = ctdb_event_script_callback(ctdb, 
908                                          timeval_current_ofs(ctdb->tunable.script_timeout, 0),
909                                          state, 
910                                          ctdb_start_recovery_callback, 
911                                          state, "startrecovery");
912
913         if (ret != 0) {
914                 DEBUG(DEBUG_ERR,(__location__ " Failed to start recovery\n"));
915                 talloc_free(state);
916                 return -1;
917         }
918
919         /* tell the control that we will be reply asynchronously */
920         *async_reply = true;
921         return 0;
922 }
923
924 /*
925  try to delete all these records as part of the vacuuming process
926  and return the records we failed to delete
927 */
928 int32_t ctdb_control_try_delete_records(struct ctdb_context *ctdb, TDB_DATA indata, TDB_DATA *outdata)
929 {
930         struct ctdb_marshall_buffer *reply = (struct ctdb_marshall_buffer *)indata.dptr;
931         struct ctdb_db_context *ctdb_db;
932         int i;
933         struct ctdb_rec_data *rec;
934         struct ctdb_marshall_buffer *records;
935
936         if (indata.dsize < offsetof(struct ctdb_marshall_buffer, data)) {
937                 DEBUG(DEBUG_ERR,(__location__ " invalid data in try_delete_records\n"));
938                 return -1;
939         }
940
941         ctdb_db = find_ctdb_db(ctdb, reply->db_id);
942         if (!ctdb_db) {
943                 DEBUG(DEBUG_ERR,(__location__ " Unknown db 0x%08x\n", reply->db_id));
944                 return -1;
945         }
946
947
948         DEBUG(DEBUG_DEBUG,("starting try_delete_records of %u records for dbid 0x%x\n",
949                  reply->count, reply->db_id));
950
951
952         /* create a blob to send back the records we couldnt delete */  
953         records = (struct ctdb_marshall_buffer *)
954                         talloc_zero_size(outdata, 
955                                     offsetof(struct ctdb_marshall_buffer, data));
956         if (records == NULL) {
957                 DEBUG(DEBUG_ERR,(__location__ " Out of memory\n"));
958                 return -1;
959         }
960         records->db_id = ctdb_db->db_id;
961
962
963         rec = (struct ctdb_rec_data *)&reply->data[0];
964         for (i=0;i<reply->count;i++) {
965                 TDB_DATA key, data;
966
967                 key.dptr = &rec->data[0];
968                 key.dsize = rec->keylen;
969                 data.dptr = &rec->data[key.dsize];
970                 data.dsize = rec->datalen;
971
972                 if (data.dsize < sizeof(struct ctdb_ltdb_header)) {
973                         DEBUG(DEBUG_CRIT,(__location__ " bad ltdb record in indata\n"));
974                         return -1;
975                 }
976
977                 /* If we cant delete the record we must add it to the reply
978                    so the lmaster knows it may not purge this record
979                 */
980                 if (delete_tdb_record(ctdb, ctdb_db, rec) != 0) {
981                         size_t old_size;
982                         struct ctdb_ltdb_header *hdr;
983
984                         hdr = (struct ctdb_ltdb_header *)data.dptr;
985                         data.dptr += sizeof(*hdr);
986                         data.dsize -= sizeof(*hdr);
987
988                         DEBUG(DEBUG_INFO, (__location__ " Failed to vacuum delete record with hash 0x%08x\n", ctdb_hash(&key)));
989
990                         old_size = talloc_get_size(records);
991                         records = talloc_realloc_size(outdata, records, old_size + rec->length);
992                         if (records == NULL) {
993                                 DEBUG(DEBUG_ERR,(__location__ " Failed to expand\n"));
994                                 return -1;
995                         }
996                         records->count++;
997                         memcpy(old_size+(uint8_t *)records, rec, rec->length);
998                 } 
999
1000                 rec = (struct ctdb_rec_data *)(rec->length + (uint8_t *)rec);
1001         }           
1002
1003
1004         outdata->dptr = (uint8_t *)records;
1005         outdata->dsize = talloc_get_size(records);
1006
1007         return 0;
1008 }
1009
1010 /*
1011   report capabilities
1012  */
1013 int32_t ctdb_control_get_capabilities(struct ctdb_context *ctdb, TDB_DATA *outdata)
1014 {
1015         uint32_t *capabilities = NULL;
1016
1017         capabilities = talloc(outdata, uint32_t);
1018         CTDB_NO_MEMORY(ctdb, capabilities);
1019         *capabilities = ctdb->capabilities;
1020
1021         outdata->dsize = sizeof(uint32_t);
1022         outdata->dptr = (uint8_t *)capabilities;
1023
1024         return 0;       
1025 }
1026
1027 static void ctdb_recd_ping_timeout(struct event_context *ev, struct timed_event *te, struct timeval t, void *p)
1028 {
1029         struct ctdb_context *ctdb = talloc_get_type(p, struct ctdb_context);
1030         uint32_t *count = talloc_get_type(ctdb->recd_ping_count, uint32_t);
1031
1032         DEBUG(DEBUG_ERR, (__location__ " Recovery daemon ping timeout. Count : %u\n", *count));
1033
1034         if (*count < ctdb->tunable.recd_ping_failcount) {
1035                 (*count)++;
1036                 event_add_timed(ctdb->ev, ctdb->recd_ping_count, 
1037                         timeval_current_ofs(ctdb->tunable.recd_ping_timeout, 0),
1038                         ctdb_recd_ping_timeout, ctdb);
1039                 return;
1040         }
1041
1042         DEBUG(DEBUG_ERR, (__location__ " Final timeout for recovery daemon ping. Shutting down ctdb daemon\n"));
1043
1044         ctdb_stop_recoverd(ctdb);
1045         ctdb_stop_keepalive(ctdb);
1046         ctdb_stop_monitoring(ctdb);
1047         ctdb_release_all_ips(ctdb);
1048         if (ctdb->methods != NULL) {
1049                 ctdb->methods->shutdown(ctdb);
1050         }
1051         ctdb_event_script(ctdb, "shutdown");
1052         DEBUG(DEBUG_ERR, (__location__ " Recovery daemon ping timeout. Daemon has been shut down.\n"));
1053         exit(0);
1054 }
1055
1056 /* The recovery daemon will ping us at regular intervals.
1057    If we havent been pinged for a while we assume the recovery
1058    daemon is inoperable and we shut down.
1059 */
1060 int32_t ctdb_control_recd_ping(struct ctdb_context *ctdb)
1061 {
1062         talloc_free(ctdb->recd_ping_count);
1063
1064         ctdb->recd_ping_count = talloc_zero(ctdb, uint32_t);
1065         CTDB_NO_MEMORY(ctdb, ctdb->recd_ping_count);
1066
1067         if (ctdb->tunable.recd_ping_timeout != 0) {
1068                 event_add_timed(ctdb->ev, ctdb->recd_ping_count, 
1069                         timeval_current_ofs(ctdb->tunable.recd_ping_timeout, 0),
1070                         ctdb_recd_ping_timeout, ctdb);
1071         }
1072
1073         return 0;
1074 }
1075
1076
1077
1078 int32_t ctdb_control_set_recmaster(struct ctdb_context *ctdb, uint32_t opcode, TDB_DATA indata)
1079 {
1080         CHECK_CONTROL_DATA_SIZE(sizeof(uint32_t));
1081         if (ctdb->freeze_mode != CTDB_FREEZE_FROZEN) {
1082                 DEBUG(DEBUG_NOTICE,("Attempt to set recmaster when not frozen\n"));
1083                 return -1;
1084         }
1085         ctdb->recovery_master = ((uint32_t *)(&indata.dptr[0]))[0];
1086         return 0;
1087 }