ctdb-daemon: Do not run monitor event if any other event is already running
[metze/samba/wip.git] / ctdb / server / eventscript.c
1 /* 
2    event script handling
3
4    Copyright (C) Andrew Tridgell  2007
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3 of the License, or
9    (at your option) any later version.
10    
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15    
16    You should have received a copy of the GNU General Public License
17    along with this program; if not, see <http://www.gnu.org/licenses/>.
18 */
19
20 #include "includes.h"
21 #include <time.h>
22 #include "system/filesys.h"
23 #include "system/wait.h"
24 #include "system/dir.h"
25 #include "system/locale.h"
26 #include "../include/ctdb_private.h"
27 #include "../common/rb_tree.h"
28 #include "lib/util/dlinklist.h"
29
30 static void ctdb_event_script_timeout(struct event_context *ev, struct timed_event *te, struct timeval t, void *p);
31
32 /* This is attached to the event script state. */
33 struct event_script_callback {
34         struct event_script_callback *next, *prev;
35         struct ctdb_context *ctdb;
36
37         /* Warning: this can free us! */
38         void (*fn)(struct ctdb_context *, int, void *);
39         void *private_data;
40 };
41         
42
43 struct ctdb_event_script_state {
44         struct ctdb_context *ctdb;
45         struct event_script_callback *callback;
46         pid_t child;
47         int fd[2];
48         enum ctdb_eventscript_call call;
49         const char *options;
50         struct timeval timeout;
51         
52         unsigned int current;
53         struct ctdb_scripts_wire *scripts;
54 };
55
56 static struct ctdb_script_wire *get_current_script(struct ctdb_event_script_state *state)
57 {
58         return &state->scripts->scripts[state->current];
59 }
60
61 /* called from ctdb_logging when we have received output on STDERR from
62  * one of the eventscripts
63  */
64 static void log_event_script_output(const char *str, uint16_t len, void *p)
65 {
66         struct ctdb_event_script_state *state
67                 = talloc_get_type(p, struct ctdb_event_script_state);
68         struct ctdb_script_wire *current;
69         unsigned int slen, min;
70
71         /* We may have been aborted to run something else.  Discard */
72         if (state->scripts == NULL) {
73                 return;
74         }
75
76         current = get_current_script(state);
77
78         /* Append, but don't overfill buffer.  It starts zero-filled. */
79         slen = strlen(current->output);
80         min = MIN(len, sizeof(current->output) - slen - 1);
81
82         memcpy(current->output + slen, str, min);
83 }
84
85 int32_t ctdb_control_get_event_script_status(struct ctdb_context *ctdb,
86                                              uint32_t call_type,
87                                              TDB_DATA *outdata)
88 {
89         if (call_type >= CTDB_EVENT_MAX) {
90                 return -1;
91         }
92
93         if (ctdb->last_status[call_type] == NULL) {
94                 /* If it's never been run, return nothing so they can tell. */
95                 outdata->dsize = 0;
96         } else {
97                 outdata->dsize = talloc_get_size(ctdb->last_status[call_type]);
98                 outdata->dptr  = (uint8_t *)ctdb->last_status[call_type];
99         }
100         return 0;
101 }
102
103 struct ctdb_script_tree_item {
104         const char *name;
105         int error;
106 };
107
108 /* Return true if OK, otherwise set errno. */
109 static bool check_executable(const char *dir, const char *name)
110 {
111         char *full;
112         struct stat st;
113
114         full = talloc_asprintf(NULL, "%s/%s", dir, name);
115         if (!full)
116                 return false;
117
118         if (stat(full, &st) != 0) {
119                 DEBUG(DEBUG_ERR,("Could not stat event script %s: %s\n",
120                                  full, strerror(errno)));
121                 talloc_free(full);
122                 return false;
123         }
124
125         if (!(st.st_mode & S_IXUSR)) {
126                 DEBUG(DEBUG_DEBUG,("Event script %s is not executable. Ignoring this event script\n", full));
127                 errno = ENOEXEC;
128                 talloc_free(full);
129                 return false;
130         }
131
132         talloc_free(full);
133         return true;
134 }
135
136 static struct ctdb_scripts_wire *ctdb_get_script_list(struct ctdb_context *ctdb, TALLOC_CTX *mem_ctx)
137 {
138         DIR *dir;
139         struct dirent *de;
140         struct stat st;
141         trbt_tree_t *tree;
142         struct ctdb_scripts_wire *scripts;
143         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
144         struct ctdb_script_tree_item *tree_item;
145         int count;
146
147         /*
148           the service specific event scripts 
149         */
150         if (stat(ctdb->event_script_dir, &st) != 0 && 
151             errno == ENOENT) {
152                 DEBUG(DEBUG_CRIT,("No event script directory found at '%s'\n", ctdb->event_script_dir));
153                 talloc_free(tmp_ctx);
154                 return NULL;
155         }
156
157         /* create a tree to store all the script names in */
158         tree = trbt_create(tmp_ctx, 0);
159
160         /* scan all directory entries and insert all valid scripts into the 
161            tree
162         */
163         dir = opendir(ctdb->event_script_dir);
164         if (dir == NULL) {
165                 DEBUG(DEBUG_CRIT,("Failed to open event script directory '%s'\n", ctdb->event_script_dir));
166                 talloc_free(tmp_ctx);
167                 return NULL;
168         }
169
170         count = 0;
171         while ((de=readdir(dir)) != NULL) {
172                 int namlen;
173                 unsigned num;
174
175                 namlen = strlen(de->d_name);
176
177                 if (namlen < 3) {
178                         continue;
179                 }
180
181                 if (de->d_name[namlen-1] == '~') {
182                         /* skip files emacs left behind */
183                         continue;
184                 }
185
186                 if (de->d_name[2] != '.') {
187                         continue;
188                 }
189
190                 if (sscanf(de->d_name, "%02u.", &num) != 1) {
191                         continue;
192                 }
193
194                 if (strlen(de->d_name) > MAX_SCRIPT_NAME) {
195                         DEBUG(DEBUG_ERR,("Script name %s too long! %u chars max",
196                                          de->d_name, MAX_SCRIPT_NAME));
197                         continue;
198                 }
199
200                 tree_item = talloc(tree, struct ctdb_script_tree_item);
201                 if (tree_item == NULL) {
202                         DEBUG(DEBUG_ERR, (__location__ " Failed to allocate new tree item\n"));
203                         closedir(dir);
204                         talloc_free(tmp_ctx);
205                         return NULL;
206                 }
207         
208                 tree_item->error = 0;
209                 if (!check_executable(ctdb->event_script_dir, de->d_name)) {
210                         tree_item->error = errno;
211                 }
212
213                 tree_item->name = talloc_strdup(tree_item, de->d_name);
214                 if (tree_item->name == NULL) {
215                         DEBUG(DEBUG_ERR,(__location__ " Failed to allocate script name.\n"));
216                         closedir(dir);
217                         talloc_free(tmp_ctx);
218                         return NULL;
219                 }
220
221                 /* store the event script in the tree */
222                 trbt_insert32(tree, (num<<16)|count++, tree_item);
223         }
224         closedir(dir);
225
226         /* Overallocates by one, but that's OK */
227         scripts = talloc_zero_size(tmp_ctx,
228                                    sizeof(*scripts)
229                                    + sizeof(scripts->scripts[0]) * count);
230         if (scripts == NULL) {
231                 DEBUG(DEBUG_ERR, (__location__ " Failed to allocate scripts\n"));
232                 talloc_free(tmp_ctx);
233                 return NULL;
234         }
235         scripts->num_scripts = count;
236
237         for (count = 0; count < scripts->num_scripts; count++) {
238                 tree_item = trbt_findfirstarray32(tree, 1);
239
240                 strcpy(scripts->scripts[count].name, tree_item->name);
241                 scripts->scripts[count].status = -tree_item->error;
242
243                 /* remove this script from the tree */
244                 talloc_free(tree_item);
245         }
246
247         talloc_steal(mem_ctx, scripts);
248         talloc_free(tmp_ctx);
249         return scripts;
250 }
251
252
253 /* There cannot be more than 10 arguments to command helper. */
254 #define MAX_HELPER_ARGS         (10)
255
256 static bool child_helper_args(TALLOC_CTX *mem_ctx, struct ctdb_context *ctdb,
257                               enum ctdb_eventscript_call call,
258                               const char *options,
259                               struct ctdb_script_wire *current, int fd,
260                               int *argc, const char ***argv)
261 {
262         const char **tmp;
263         int n, i;
264         char *t, *saveptr, *opt;
265
266         tmp = talloc_array(mem_ctx, const char *, 10+1);
267         if (tmp == NULL)  goto failed;
268
269         tmp[0] = talloc_asprintf(tmp, "%d", fd);
270         tmp[1] = talloc_asprintf(tmp, "%s/%s", ctdb->event_script_dir, current->name);
271         tmp[2] = talloc_asprintf(tmp, "%s", ctdb_eventscript_call_names[call]);
272         n = 3;
273
274         /* Split options into individual arguments */
275         opt = talloc_strdup(mem_ctx, options);
276         if (opt == NULL) {
277                 goto failed;
278         }
279
280         t = strtok_r(opt, " ", &saveptr);
281         while (t != NULL) {
282                 tmp[n++] = talloc_strdup(tmp, t);
283                 if (n > MAX_HELPER_ARGS) {
284                         goto args_failed;
285                 }
286                 t = strtok_r(NULL, " ", &saveptr);
287         }
288
289         for (i=0; i<n; i++) {
290                 if (tmp[i] == NULL) {
291                         goto failed;
292                 }
293         }
294
295         /* Last argument should be NULL */
296         tmp[n++] = NULL;
297
298         *argc = n;
299         *argv = tmp;
300         return true;
301
302
303 args_failed:
304         DEBUG(DEBUG_ERR, (__location__ " too many arguments '%s' to eventscript '%s'\n",
305                           options, ctdb_eventscript_call_names[call]));
306
307 failed:
308         if (tmp) {
309                 talloc_free(tmp);
310         }
311         return false;
312
313 }
314
315 static void ctdb_event_script_handler(struct event_context *ev, struct fd_event *fde,
316                                       uint16_t flags, void *p);
317
318 static const char *helper_prog = NULL;
319
320 static int fork_child_for_script(struct ctdb_context *ctdb,
321                                  struct ctdb_event_script_state *state)
322 {
323         int r;
324         struct tevent_fd *fde;
325         struct ctdb_script_wire *current = get_current_script(state);
326         int argc;
327         const char **argv;
328         static const char *helper = BINDIR "/ctdb_event_helper";
329
330         if (helper_prog == NULL) {
331                 const char *t = getenv("CTDB_EVENT_HELPER");
332                 if (t != NULL) {
333                         helper_prog = t;
334                 } else {
335                         helper_prog = helper;
336                 }
337         }
338
339         current->start = timeval_current();
340
341         r = pipe(state->fd);
342         if (r != 0) {
343                 DEBUG(DEBUG_ERR, (__location__ " pipe failed for child eventscript process\n"));
344                 return -errno;
345         }
346
347         /* Arguments for helper */
348         if (!child_helper_args(state, ctdb, state->call, state->options, current,
349                                state->fd[1], &argc, &argv)) {
350                 DEBUG(DEBUG_ERR, (__location__ " failed to create arguments for eventscript helper\n"));
351                 r = -ENOMEM;
352                 close(state->fd[0]);
353                 close(state->fd[1]);
354                 return r;
355         }
356
357         if (!ctdb_vfork_with_logging(state, ctdb, current->name,
358                                      helper_prog, argc, argv,
359                                      log_event_script_output,
360                                      state, &state->child)) {
361                 talloc_free(argv);
362                 r = -errno;
363                 close(state->fd[0]);
364                 close(state->fd[1]);
365                 return r;
366         }
367
368         talloc_free(argv);
369
370         close(state->fd[1]);
371         set_close_on_exec(state->fd[0]);
372
373         /* Set ourselves up to be called when that's done. */
374         fde = event_add_fd(ctdb->ev, state, state->fd[0], EVENT_FD_READ,
375                            ctdb_event_script_handler, state);
376         tevent_fd_set_auto_close(fde);
377
378         return 0;
379 }
380
381 /*
382  Summarize status of this run of scripts.
383  */
384 static int script_status(struct ctdb_scripts_wire *scripts)
385 {
386         unsigned int i;
387
388         for (i = 0; i < scripts->num_scripts; i++) {
389                 switch (scripts->scripts[i].status) {
390                 case -ENOENT:
391                 case -ENOEXEC:
392                         /* Disabled or missing; that's OK. */
393                         break;
394                 case 0:
395                         /* No problem. */
396                         break;
397                 default:
398                         return scripts->scripts[i].status;
399                 }
400         }
401
402         /* All OK! */
403         return 0;
404 }
405
406 /* called when child is finished */
407 static void ctdb_event_script_handler(struct event_context *ev, struct fd_event *fde, 
408                                       uint16_t flags, void *p)
409 {
410         struct ctdb_event_script_state *state = 
411                 talloc_get_type(p, struct ctdb_event_script_state);
412         struct ctdb_script_wire *current = get_current_script(state);
413         struct ctdb_context *ctdb = state->ctdb;
414         int r, status;
415
416         if (ctdb == NULL) {
417                 DEBUG(DEBUG_ERR,("Eventscript finished but ctdb is NULL\n"));
418                 return;
419         }
420
421         r = read(state->fd[0], &current->status, sizeof(current->status));
422         if (r < 0) {
423                 current->status = -errno;
424         } else if (r != sizeof(current->status)) {
425                 current->status = -EIO;
426         }
427
428         current->finished = timeval_current();
429         /* valgrind gets overloaded if we run next script as it's still doing
430          * post-execution analysis, so kill finished child here. */
431         if (ctdb->valgrinding) {
432                 ctdb_kill(ctdb, state->child, SIGKILL);
433         }
434
435         state->child = 0;
436
437         status = script_status(state->scripts);
438
439         /* Aborted or finished all scripts?  We're done. */
440         if (status != 0 || state->current+1 == state->scripts->num_scripts) {
441                 DEBUG(DEBUG_INFO,(__location__ " Eventscript %s %s finished with state %d\n",
442                                   ctdb_eventscript_call_names[state->call], state->options, status));
443
444                 ctdb->event_script_timeouts = 0;
445                 talloc_free(state);
446                 return;
447         }
448
449         /* Forget about that old fd. */
450         talloc_free(fde);
451
452         /* Next script! */
453         state->current++;
454         current++;
455         current->status = fork_child_for_script(ctdb, state);
456         if (current->status != 0) {
457                 /* This calls the callback. */
458                 talloc_free(state);
459         }
460 }
461
462 struct debug_hung_script_state {
463         struct ctdb_context *ctdb;
464         pid_t child;
465         enum ctdb_eventscript_call call;
466 };
467
468 static int debug_hung_script_state_destructor(struct debug_hung_script_state *state)
469 {
470         if (state->child) {
471                 ctdb_kill(state->ctdb, state->child, SIGKILL);
472         }
473         return 0;
474 }
475
476 static void debug_hung_script_timeout(struct tevent_context *ev, struct tevent_timer *te,
477                                       struct timeval t, void *p)
478 {
479         struct debug_hung_script_state *state =
480                 talloc_get_type(p, struct debug_hung_script_state);
481
482         talloc_free(state);
483 }
484
485 static void debug_hung_script_done(struct tevent_context *ev, struct tevent_fd *fde,
486                                    uint16_t flags, void *p)
487 {
488         struct debug_hung_script_state *state =
489                 talloc_get_type(p, struct debug_hung_script_state);
490
491         talloc_free(state);
492 }
493
494 static void ctdb_run_debug_hung_script(struct ctdb_context *ctdb, struct debug_hung_script_state *state)
495 {
496         pid_t pid;
497         const char * debug_hung_script = ETCDIR "/ctdb/debug-hung-script.sh";
498         int fd[2];
499         struct tevent_timer *ttimer;
500         struct tevent_fd *tfd;
501         const char **argv;
502         int i;
503
504         if (helper_prog == NULL) {
505                 return;
506         }
507
508         if (pipe(fd) < 0) {
509                 DEBUG(DEBUG_ERR,("Failed to create pipe fd for debug hung script\n"));
510                 return;
511         }
512
513         argv = talloc_array(state, const char *, 5);
514
515         argv[0] = talloc_asprintf(argv, "%d", fd[1]);
516         argv[1] = talloc_strdup(argv, debug_hung_script);
517         argv[2] = talloc_asprintf(argv, "%d", state->child);
518         argv[3] = talloc_strdup(argv, ctdb_eventscript_call_names[state->call]);
519         argv[4] = NULL;
520
521         for (i=0; i<4; i++) {
522                 if (argv[i] == NULL) {
523                         close(fd[0]);
524                         close(fd[1]);
525                         talloc_free(argv);
526                         return;
527                 }
528         }
529
530
531         if (!ctdb_vfork_with_logging(state, ctdb, "Hung-script",
532                                      helper_prog, 5, argv, NULL, NULL, &pid)) {
533                 DEBUG(DEBUG_ERR,("Failed to fork a child to track hung event script\n"));
534                 talloc_free(argv);
535                 close(fd[0]);
536                 close(fd[1]);
537                 return;
538         }
539
540         talloc_free(argv);
541         close(fd[1]);
542
543         ttimer = tevent_add_timer(ctdb->ev, state,
544                                   timeval_current_ofs(ctdb->tunable.script_timeout, 0),
545                                   debug_hung_script_timeout, state);
546         if (ttimer == NULL) {
547                 close(fd[0]);
548                 return;
549         }
550
551         tfd = tevent_add_fd(ctdb->ev, state, fd[0], EVENT_FD_READ,
552                             debug_hung_script_done, state);
553         if (tfd == NULL) {
554                 talloc_free(ttimer);
555                 close(fd[0]);
556                 return;
557         }
558         tevent_fd_set_auto_close(tfd);
559 }
560
561 /* called when child times out */
562 static void ctdb_event_script_timeout(struct event_context *ev, struct timed_event *te, 
563                                       struct timeval t, void *p)
564 {
565         struct ctdb_event_script_state *state = talloc_get_type(p, struct ctdb_event_script_state);
566         struct ctdb_context *ctdb = state->ctdb;
567         struct ctdb_script_wire *current = get_current_script(state);
568         struct debug_hung_script_state *debug_state;
569
570         DEBUG(DEBUG_ERR,("Event script '%s %s %s' timed out after %.1fs, count: %u, pid: %d\n",
571                          current->name, ctdb_eventscript_call_names[state->call], state->options,
572                          timeval_elapsed(&current->start),
573                          ctdb->event_script_timeouts, state->child));
574
575         /* ignore timeouts for these events */
576         switch (state->call) {
577         case CTDB_EVENT_START_RECOVERY:
578         case CTDB_EVENT_RECOVERED:
579         case CTDB_EVENT_TAKE_IP:
580         case CTDB_EVENT_RELEASE_IP:
581                 state->scripts->scripts[state->current].status = 0;
582                 DEBUG(DEBUG_ERR,("Ignoring hung script for %s call %d\n", state->options, state->call));
583                 break;
584         default:
585                 state->scripts->scripts[state->current].status = -ETIME;
586         }
587
588         debug_state = talloc_zero(ctdb, struct debug_hung_script_state);
589         if (debug_state == NULL) {
590                 talloc_free(state);
591                 return;
592         }
593
594         /* Save information useful for running debug hung script, so
595          * eventscript state can be freed.
596          */
597         debug_state->ctdb = ctdb;
598         debug_state->child = state->child;
599         debug_state->call = state->call;
600
601         /* This destructor will actually kill the hung event script */
602         talloc_set_destructor(debug_state, debug_hung_script_state_destructor);
603
604         state->child = 0;
605         talloc_free(state);
606
607         ctdb_run_debug_hung_script(ctdb, debug_state);
608 }
609
610 /*
611   destroy an event script: kill it if ->child != 0.
612  */
613 static int event_script_destructor(struct ctdb_event_script_state *state)
614 {
615         int status;
616         struct event_script_callback *callback;
617
618         if (state->child) {
619                 DEBUG(DEBUG_ERR,(__location__ " Sending SIGTERM to child pid:%d\n", state->child));
620
621                 if (ctdb_kill(state->ctdb, state->child, SIGTERM) != 0) {
622                         DEBUG(DEBUG_ERR,("Failed to kill child process for eventscript, errno %s(%d)\n", strerror(errno), errno));
623                 }
624         }
625
626         /* If we were the current monitor, we no longer are. */
627         if (state->ctdb->current_monitor == state) {
628                 state->ctdb->current_monitor = NULL;
629         }
630
631         /* Save our scripts as the last executed status, if we have them.
632          * See ctdb_event_script_callback_v where we abort monitor event. */
633         if (state->scripts) {
634                 talloc_free(state->ctdb->last_status[state->call]);
635                 state->ctdb->last_status[state->call] = state->scripts;
636                 if (state->current < state->ctdb->last_status[state->call]->num_scripts) {
637                         state->ctdb->last_status[state->call]->num_scripts = state->current+1;
638                 }
639         }
640
641         /* Use last status as result, or "OK" if none. */
642         if (state->ctdb->last_status[state->call]) {
643                 status = script_status(state->ctdb->last_status[state->call]);
644         } else {
645                 status = 0;
646         }
647
648         state->ctdb->active_events--;
649         if (state->ctdb->active_events < 0) {
650                 ctdb_fatal(state->ctdb, "Active events < 0");
651         }
652
653         /* This is allowed to free us; talloc will prevent double free anyway,
654          * but beware if you call this outside the destructor!
655          * the callback hangs off a different context so we walk the list
656          * of "active" callbacks until we find the one state points to.
657          * if we cant find it it means the callback has been removed.
658          */
659         for (callback = state->ctdb->script_callbacks; callback != NULL; callback = callback->next) {
660                 if (callback == state->callback) {
661                         break;
662                 }
663         }
664         
665         state->callback = NULL;
666
667         if (callback) {
668                 /* Make sure destructor doesn't free itself! */
669                 talloc_steal(NULL, callback);
670                 callback->fn(state->ctdb, status, callback->private_data);
671                 talloc_free(callback);
672         }
673
674         return 0;
675 }
676
677 static unsigned int count_words(const char *options)
678 {
679         unsigned int words = 0;
680
681         options += strspn(options, " \t");
682         while (*options) {
683                 words++;
684                 options += strcspn(options, " \t");
685                 options += strspn(options, " \t");
686         }
687         return words;
688 }
689
690 static bool check_options(enum ctdb_eventscript_call call, const char *options)
691 {
692         switch (call) {
693         /* These all take no arguments. */
694         case CTDB_EVENT_INIT:
695         case CTDB_EVENT_SETUP:
696         case CTDB_EVENT_STARTUP:
697         case CTDB_EVENT_START_RECOVERY:
698         case CTDB_EVENT_RECOVERED:
699         case CTDB_EVENT_MONITOR:
700         case CTDB_EVENT_SHUTDOWN:
701         case CTDB_EVENT_IPREALLOCATED:
702                 return count_words(options) == 0;
703
704         case CTDB_EVENT_TAKE_IP: /* interface, IP address, netmask bits. */
705         case CTDB_EVENT_RELEASE_IP:
706                 return count_words(options) == 3;
707
708         case CTDB_EVENT_UPDATE_IP: /* old interface, new interface, IP address, netmask bits. */
709                 return count_words(options) == 4;
710
711         default:
712                 DEBUG(DEBUG_ERR,(__location__ "Unknown ctdb_eventscript_call %u\n", call));
713                 return false;
714         }
715 }
716
717 static int remove_callback(struct event_script_callback *callback)
718 {
719         DLIST_REMOVE(callback->ctdb->script_callbacks, callback);
720         return 0;
721 }
722
723 /*
724   run the event script in the background, calling the callback when 
725   finished
726  */
727 static int ctdb_event_script_callback_v(struct ctdb_context *ctdb,
728                                         const void *mem_ctx,
729                                         void (*callback)(struct ctdb_context *, int, void *),
730                                         void *private_data,
731                                         enum ctdb_eventscript_call call,
732                                         const char *fmt, va_list ap)
733 {
734         struct ctdb_event_script_state *state;
735
736         if (ctdb->recovery_mode != CTDB_RECOVERY_NORMAL) {
737                 /* we guarantee that only some specifically allowed event scripts are run
738                    while in recovery */
739                 const enum ctdb_eventscript_call allowed_calls[] = {
740                         CTDB_EVENT_INIT,
741                         CTDB_EVENT_SETUP,
742                         CTDB_EVENT_START_RECOVERY,
743                         CTDB_EVENT_SHUTDOWN,
744                         CTDB_EVENT_RELEASE_IP,
745                         CTDB_EVENT_IPREALLOCATED,
746                 };
747                 int i;
748                 for (i=0;i<ARRAY_SIZE(allowed_calls);i++) {
749                         if (call == allowed_calls[i]) break;
750                 }
751                 if (i == ARRAY_SIZE(allowed_calls)) {
752                         DEBUG(DEBUG_ERR,("Refusing to run event scripts call '%s' while in recovery\n",
753                                  ctdb_eventscript_call_names[call]));
754                         return -1;
755                 }
756         }
757
758         /* Do not run new monitor events if some event is already running */
759         if (call == CTDB_EVENT_MONITOR && ctdb->active_events > 0) {
760                 if (callback != NULL) {
761                         callback(ctdb, -ECANCELED, private_data);
762                 }
763                 return 0;
764         }
765
766         /* Kill off any running monitor events to run this event. */
767         if (ctdb->current_monitor) {
768                 struct ctdb_event_script_state *ms = talloc_get_type(ctdb->current_monitor, struct ctdb_event_script_state);
769
770                 /* Cancel current monitor callback state only if monitoring
771                  * context ctdb->monitor->monitor_context has not been freed */
772                 if (ms->callback != NULL && !ctdb_stopped_monitoring(ctdb)) {
773                         ms->callback->fn(ctdb, -ECANCELED, ms->callback->private_data);
774                         talloc_free(ms->callback);
775                 }
776
777                 /* Discard script status so we don't save to last_status */
778                 talloc_free(ctdb->current_monitor->scripts);
779                 ctdb->current_monitor->scripts = NULL;
780                 talloc_free(ctdb->current_monitor);
781                 ctdb->current_monitor = NULL;
782         }
783
784         state = talloc(ctdb->event_script_ctx, struct ctdb_event_script_state);
785         CTDB_NO_MEMORY(ctdb, state);
786
787         /* The callback isn't done if the context is freed. */
788         state->callback = talloc(mem_ctx, struct event_script_callback);
789         CTDB_NO_MEMORY(ctdb, state->callback);
790         DLIST_ADD(ctdb->script_callbacks, state->callback);
791         talloc_set_destructor(state->callback, remove_callback);
792         state->callback->ctdb         = ctdb;
793         state->callback->fn           = callback;
794         state->callback->private_data = private_data;
795
796         state->ctdb = ctdb;
797         state->call = call;
798         state->options = talloc_vasprintf(state, fmt, ap);
799         state->timeout = timeval_set(ctdb->tunable.script_timeout, 0);
800         state->scripts = NULL;
801         if (state->options == NULL) {
802                 DEBUG(DEBUG_ERR, (__location__ " could not allocate state->options\n"));
803                 talloc_free(state);
804                 return -1;
805         }
806         if (!check_options(state->call, state->options)) {
807                 DEBUG(DEBUG_ERR, ("Bad eventscript options '%s' for %s\n",
808                                   ctdb_eventscript_call_names[state->call], state->options));
809                 talloc_free(state);
810                 return -1;
811         }
812
813         DEBUG(DEBUG_INFO,(__location__ " Starting eventscript %s %s\n",
814                           ctdb_eventscript_call_names[state->call],
815                           state->options));
816
817         /* This is not a child of state, since we save it in destructor. */
818         state->scripts = ctdb_get_script_list(ctdb, ctdb);
819         if (state->scripts == NULL) {
820                 talloc_free(state);
821                 return -1;
822         }
823         state->current = 0;
824         state->child = 0;
825
826         if (call == CTDB_EVENT_MONITOR) {
827                 ctdb->current_monitor = state;
828         }
829
830         talloc_set_destructor(state, event_script_destructor);
831
832         ctdb->active_events++;
833
834         /* Nothing to do? */
835         if (state->scripts->num_scripts == 0) {
836                 talloc_free(state);
837                 return 0;
838         }
839
840         state->scripts->scripts[0].status = fork_child_for_script(ctdb, state);
841         if (state->scripts->scripts[0].status != 0) {
842                 /* Callback is called from destructor, with fail result. */
843                 talloc_free(state);
844                 return 0;
845         }
846
847         if (!timeval_is_zero(&state->timeout)) {
848                 event_add_timed(ctdb->ev, state, timeval_current_ofs(state->timeout.tv_sec, state->timeout.tv_usec), ctdb_event_script_timeout, state);
849         } else {
850                 DEBUG(DEBUG_ERR, (__location__ " eventscript %s %s called with no timeout\n",
851                                   ctdb_eventscript_call_names[state->call],
852                                   state->options));
853         }
854
855         return 0;
856 }
857
858
859 /*
860   run the event script in the background, calling the callback when 
861   finished.  If mem_ctx is freed, callback will never be called.
862  */
863 int ctdb_event_script_callback(struct ctdb_context *ctdb, 
864                                TALLOC_CTX *mem_ctx,
865                                void (*callback)(struct ctdb_context *, int, void *),
866                                void *private_data,
867                                enum ctdb_eventscript_call call,
868                                const char *fmt, ...)
869 {
870         va_list ap;
871         int ret;
872
873         va_start(ap, fmt);
874         ret = ctdb_event_script_callback_v(ctdb, mem_ctx, callback, private_data, call, fmt, ap);
875         va_end(ap);
876
877         return ret;
878 }
879
880
881 struct callback_status {
882         bool done;
883         int status;
884 };
885
886 /*
887   called when ctdb_event_script() finishes
888  */
889 static void event_script_callback(struct ctdb_context *ctdb, int status, void *private_data)
890 {
891         struct callback_status *s = (struct callback_status *)private_data;
892         s->done = true;
893         s->status = status;
894 }
895
896 /*
897   run the event script, waiting for it to complete. Used when the caller
898   doesn't want to continue till the event script has finished.
899  */
900 int ctdb_event_script_args(struct ctdb_context *ctdb, enum ctdb_eventscript_call call,
901                            const char *fmt, ...)
902 {
903         va_list ap;
904         int ret;
905         struct callback_status status;
906
907         va_start(ap, fmt);
908         ret = ctdb_event_script_callback_v(ctdb, ctdb,
909                         event_script_callback, &status, call, fmt, ap);
910         va_end(ap);
911         if (ret != 0) {
912                 return ret;
913         }
914
915         status.status = -1;
916         status.done = false;
917
918         while (status.done == false && event_loop_once(ctdb->ev) == 0) /* noop */;
919
920         if (status.status == -ETIME) {
921                 DEBUG(DEBUG_ERR, (__location__ " eventscript for '%s' timedout."
922                                   " Immediately banning ourself for %d seconds\n",
923                                   ctdb_eventscript_call_names[call],
924                                   ctdb->tunable.recovery_ban_period));
925
926                 /* Don't ban self if CTDB is starting up or shutting down */
927                 if (call != CTDB_EVENT_INIT && call != CTDB_EVENT_SHUTDOWN) {
928                         ctdb_ban_self(ctdb);
929                 }
930         }
931
932         return status.status;
933 }
934
935 int ctdb_event_script(struct ctdb_context *ctdb, enum ctdb_eventscript_call call)
936 {
937         /* GCC complains about empty format string, so use %s and "". */
938         return ctdb_event_script_args(ctdb, call, "%s", "");
939 }
940
941 struct eventscript_callback_state {
942         struct ctdb_req_control *c;
943 };
944
945 /*
946   called when a forced eventscript run has finished
947  */
948 static void run_eventscripts_callback(struct ctdb_context *ctdb, int status, 
949                                  void *private_data)
950 {
951         struct eventscript_callback_state *state = 
952                 talloc_get_type(private_data, struct eventscript_callback_state);
953
954         ctdb_enable_monitoring(ctdb);
955
956         if (status != 0) {
957                 DEBUG(DEBUG_ERR,(__location__ " Failed to run eventscripts\n"));
958         }
959
960         ctdb_request_control_reply(ctdb, state->c, NULL, status, NULL);
961         /* This will free the struct ctdb_event_script_state we are in! */
962         talloc_free(state);
963         return;
964 }
965
966
967 /* Returns rest of string, or NULL if no match. */
968 static const char *get_call(const char *p, enum ctdb_eventscript_call *call)
969 {
970         unsigned int len;
971
972         /* Skip any initial whitespace. */
973         p += strspn(p, " \t");
974
975         /* See if we match any. */
976         for (*call = 0; *call < CTDB_EVENT_MAX; (*call)++) {
977                 len = strlen(ctdb_eventscript_call_names[*call]);
978                 if (strncmp(p, ctdb_eventscript_call_names[*call], len) == 0) {
979                         /* If end of string or whitespace, we're done. */
980                         if (strcspn(p + len, " \t") == 0) {
981                                 return p + len;
982                         }
983                 }
984         }
985         return NULL;
986 }
987
988 /*
989   A control to force running of the eventscripts from the ctdb client tool
990 */
991 int32_t ctdb_run_eventscripts(struct ctdb_context *ctdb,
992                 struct ctdb_req_control *c,
993                 TDB_DATA indata, bool *async_reply)
994 {
995         int ret;
996         struct eventscript_callback_state *state;
997         const char *options;
998         enum ctdb_eventscript_call call;
999
1000         /* Figure out what call they want. */
1001         options = get_call((const char *)indata.dptr, &call);
1002         if (!options) {
1003                 DEBUG(DEBUG_ERR, (__location__ " Invalid event name \"%s\"\n", (const char *)indata.dptr));
1004                 return -1;
1005         }
1006
1007         if (ctdb->recovery_mode != CTDB_RECOVERY_NORMAL) {
1008                 DEBUG(DEBUG_ERR, (__location__ " Aborted running eventscript \"%s\" while in RECOVERY mode\n", indata.dptr));
1009                 return -1;
1010         }
1011
1012         state = talloc(ctdb->event_script_ctx, struct eventscript_callback_state);
1013         CTDB_NO_MEMORY(ctdb, state);
1014
1015         state->c = talloc_steal(state, c);
1016
1017         DEBUG(DEBUG_NOTICE,("Running eventscripts with arguments %s\n", indata.dptr));
1018
1019         ctdb_disable_monitoring(ctdb);
1020
1021         ret = ctdb_event_script_callback(ctdb, 
1022                          state, run_eventscripts_callback, state,
1023                          call, "%s", options);
1024
1025         if (ret != 0) {
1026                 ctdb_enable_monitoring(ctdb);
1027                 DEBUG(DEBUG_ERR,(__location__ " Failed to run eventscripts with arguments %s\n", indata.dptr));
1028                 talloc_free(state);
1029                 return -1;
1030         }
1031
1032         /* tell ctdb_control.c that we will be replying asynchronously */
1033         *async_reply = true;
1034
1035         return 0;
1036 }
1037
1038
1039
1040 int32_t ctdb_control_enable_script(struct ctdb_context *ctdb, TDB_DATA indata)
1041 {
1042         const char *script;
1043         struct stat st;
1044         char *filename;
1045         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
1046
1047         script = (char *)indata.dptr;
1048         if (indata.dsize == 0) {
1049                 DEBUG(DEBUG_ERR,(__location__ " No script specified.\n"));
1050                 talloc_free(tmp_ctx);
1051                 return -1;
1052         }
1053         if (indata.dptr[indata.dsize - 1] != '\0') {
1054                 DEBUG(DEBUG_ERR,(__location__ " String is not null terminated.\n"));
1055                 talloc_free(tmp_ctx);
1056                 return -1;
1057         }
1058         if (index(script,'/') != NULL) {
1059                 DEBUG(DEBUG_ERR,(__location__ " Script name contains '/'. Failed to enable script %s\n", script));
1060                 talloc_free(tmp_ctx);
1061                 return -1;
1062         }
1063
1064
1065         if (stat(ctdb->event_script_dir, &st) != 0 && 
1066             errno == ENOENT) {
1067                 DEBUG(DEBUG_CRIT,("No event script directory found at '%s'\n", ctdb->event_script_dir));
1068                 talloc_free(tmp_ctx);
1069                 return -1;
1070         }
1071
1072
1073         filename = talloc_asprintf(tmp_ctx, "%s/%s", ctdb->event_script_dir, script);
1074         if (filename == NULL) {
1075                 DEBUG(DEBUG_ERR,(__location__ " Failed to create script path\n"));
1076                 talloc_free(tmp_ctx);
1077                 return -1;
1078         }
1079
1080         if (stat(filename, &st) != 0) {
1081                 DEBUG(DEBUG_ERR,("Could not stat event script %s. Failed to enable script.\n", filename));
1082                 talloc_free(tmp_ctx);
1083                 return -1;
1084         }
1085
1086         if (chmod(filename, st.st_mode | S_IXUSR) == -1) {
1087                 DEBUG(DEBUG_ERR,("Could not chmod %s. Failed to enable script.\n", filename));
1088                 talloc_free(tmp_ctx);
1089                 return -1;
1090         }
1091
1092         talloc_free(tmp_ctx);
1093         return 0;
1094 }
1095
1096 int32_t ctdb_control_disable_script(struct ctdb_context *ctdb, TDB_DATA indata)
1097 {
1098         const char *script;
1099         struct stat st;
1100         char *filename;
1101         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
1102
1103         script = (char *)indata.dptr;
1104         if (indata.dsize == 0) {
1105                 DEBUG(DEBUG_ERR,(__location__ " No script specified.\n"));
1106                 talloc_free(tmp_ctx);
1107                 return -1;
1108         }
1109         if (indata.dptr[indata.dsize - 1] != '\0') {
1110                 DEBUG(DEBUG_ERR,(__location__ " String is not null terminated.\n"));
1111                 talloc_free(tmp_ctx);
1112                 return -1;
1113         }
1114         if (index(script,'/') != NULL) {
1115                 DEBUG(DEBUG_ERR,(__location__ " Script name contains '/'. Failed to disable script %s\n", script));
1116                 talloc_free(tmp_ctx);
1117                 return -1;
1118         }
1119
1120
1121         if (stat(ctdb->event_script_dir, &st) != 0 && 
1122             errno == ENOENT) {
1123                 DEBUG(DEBUG_CRIT,("No event script directory found at '%s'\n", ctdb->event_script_dir));
1124                 talloc_free(tmp_ctx);
1125                 return -1;
1126         }
1127
1128
1129         filename = talloc_asprintf(tmp_ctx, "%s/%s", ctdb->event_script_dir, script);
1130         if (filename == NULL) {
1131                 DEBUG(DEBUG_ERR,(__location__ " Failed to create script path\n"));
1132                 talloc_free(tmp_ctx);
1133                 return -1;
1134         }
1135
1136         if (stat(filename, &st) != 0) {
1137                 DEBUG(DEBUG_ERR,("Could not stat event script %s. Failed to disable script.\n", filename));
1138                 talloc_free(tmp_ctx);
1139                 return -1;
1140         }
1141
1142         if (chmod(filename, st.st_mode & ~(S_IXUSR|S_IXGRP|S_IXOTH)) == -1) {
1143                 DEBUG(DEBUG_ERR,("Could not chmod %s. Failed to disable script.\n", filename));
1144                 talloc_free(tmp_ctx);
1145                 return -1;
1146         }
1147
1148         talloc_free(tmp_ctx);
1149         return 0;
1150 }