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