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