Ignore any scripts that timesout for most events, except startup.
[sahlberg/ctdb.git] / 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 "lib/events/events.h"
28 #include "../common/rb_tree.h"
29
30 static struct {
31         struct timeval start;
32         const char *script_running;
33 } child_state;
34
35 static void ctdb_event_script_timeout(struct event_context *ev, struct timed_event *te, struct timeval t, void *p);
36
37 /*
38   ctdbd sends us a SIGTERM when we should time out the current script
39  */
40 static void sigterm(int sig)
41 {
42         char tbuf[100], buf[200];
43         time_t t;
44
45         DEBUG(DEBUG_ERR,("Timed out running script '%s' after %.1f seconds pid :%d\n", 
46                  child_state.script_running, timeval_elapsed(&child_state.start), getpid()));
47
48         t = time(NULL);
49
50         strftime(tbuf, sizeof(tbuf)-1, "%Y%m%d%H%M%S",  localtime(&t));
51         sprintf(buf, "{ pstree -p; cat /proc/locks; ls -li /var/ctdb/ /var/ctdb/persistent; }"
52                 " >/tmp/ctdb.event.%s.%d", tbuf, getpid());
53         system(buf);
54
55         DEBUG(DEBUG_ERR,("Logged timedout eventscript : %s\n", buf));
56
57         /* all the child processes will be running in the same process group */
58         kill(-getpgrp(), SIGKILL);
59         _exit(1);
60 }
61
62 struct ctdb_event_script_state {
63         struct ctdb_context *ctdb;
64         pid_t child;
65         /* Warning: this can free us! */
66         void (*callback)(struct ctdb_context *, int, void *);
67         int fd[2];
68         void *private_data;
69         bool from_user;
70         enum ctdb_eventscript_call call;
71         const char *options;
72         struct timeval timeout;
73
74         unsigned int current;
75         struct ctdb_scripts_wire *scripts;
76 };
77
78 static struct ctdb_script_wire *get_current_script(struct ctdb_event_script_state *state)
79 {
80         return &state->scripts->scripts[state->current];
81 }
82
83 /* called from ctdb_logging when we have received output on STDERR from
84  * one of the eventscripts
85  */
86 static void log_event_script_output(const char *str, uint16_t len, void *p)
87 {
88         struct ctdb_event_script_state *state
89                 = talloc_get_type(p, struct ctdb_event_script_state);
90         struct ctdb_script_wire *current;
91         unsigned int slen, min;
92
93         /* We may have been aborted to run something else.  Discard */
94         if (state->scripts == NULL) {
95                 return;
96         }
97
98         current = get_current_script(state);
99
100         /* Append, but don't overfill buffer.  It starts zero-filled. */
101         slen = strlen(current->output);
102         min = MIN(len, sizeof(current->output) - slen - 1);
103
104         memcpy(current->output + slen, str, min);
105 }
106
107 int32_t ctdb_control_get_event_script_status(struct ctdb_context *ctdb,
108                                              uint32_t call_type,
109                                              TDB_DATA *outdata)
110 {
111         if (call_type >= CTDB_EVENT_MAX) {
112                 return -1;
113         }
114
115         if (ctdb->last_status[call_type] == NULL) {
116                 /* If it's never been run, return nothing so they can tell. */
117                 outdata->dsize = 0;
118         } else {
119                 outdata->dsize = talloc_get_size(ctdb->last_status[call_type]);
120                 outdata->dptr  = (uint8_t *)ctdb->last_status[call_type];
121         }
122         return 0;
123 }
124
125 struct ctdb_script_tree_item {
126         const char *name;
127         int error;
128 };
129
130 /* Return true if OK, otherwise set errno. */
131 static bool check_executable(const char *dir, const char *name)
132 {
133         char *full;
134         struct stat st;
135
136         full = talloc_asprintf(NULL, "%s/%s", dir, name);
137         if (!full)
138                 return false;
139
140         if (stat(full, &st) != 0) {
141                 DEBUG(DEBUG_ERR,("Could not stat event script %s: %s\n",
142                                  full, strerror(errno)));
143                 talloc_free(full);
144                 return false;
145         }
146
147         if (!(st.st_mode & S_IXUSR)) {
148                 DEBUG(DEBUG_DEBUG,("Event script %s is not executable. Ignoring this event script\n", full));
149                 errno = ENOEXEC;
150                 talloc_free(full);
151                 return false;
152         }
153
154         talloc_free(full);
155         return true;
156 }
157
158 static struct ctdb_scripts_wire *ctdb_get_script_list(struct ctdb_context *ctdb, TALLOC_CTX *mem_ctx)
159 {
160         DIR *dir;
161         struct dirent *de;
162         struct stat st;
163         trbt_tree_t *tree;
164         struct ctdb_scripts_wire *scripts;
165         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
166         struct ctdb_script_tree_item *tree_item;
167         int count;
168
169         /*
170           the service specific event scripts 
171         */
172         if (stat(ctdb->event_script_dir, &st) != 0 && 
173             errno == ENOENT) {
174                 DEBUG(DEBUG_CRIT,("No event script directory found at '%s'\n", ctdb->event_script_dir));
175                 talloc_free(tmp_ctx);
176                 return NULL;
177         }
178
179         /* create a tree to store all the script names in */
180         tree = trbt_create(tmp_ctx, 0);
181
182         /* scan all directory entries and insert all valid scripts into the 
183            tree
184         */
185         dir = opendir(ctdb->event_script_dir);
186         if (dir == NULL) {
187                 DEBUG(DEBUG_CRIT,("Failed to open event script directory '%s'\n", ctdb->event_script_dir));
188                 talloc_free(tmp_ctx);
189                 return NULL;
190         }
191
192         count = 0;
193         while ((de=readdir(dir)) != NULL) {
194                 int namlen;
195                 unsigned num;
196
197                 namlen = strlen(de->d_name);
198
199                 if (namlen < 3) {
200                         continue;
201                 }
202
203                 if (de->d_name[namlen-1] == '~') {
204                         /* skip files emacs left behind */
205                         continue;
206                 }
207
208                 if (de->d_name[2] != '.') {
209                         continue;
210                 }
211
212                 if (sscanf(de->d_name, "%02u.", &num) != 1) {
213                         continue;
214                 }
215
216                 if (strlen(de->d_name) > MAX_SCRIPT_NAME) {
217                         DEBUG(DEBUG_ERR,("Script name %s too long! %u chars max",
218                                          de->d_name, MAX_SCRIPT_NAME));
219                         continue;
220                 }
221
222                 tree_item = talloc(tree, struct ctdb_script_tree_item);
223                 if (tree_item == NULL) {
224                         DEBUG(DEBUG_ERR, (__location__ " Failed to allocate new tree item\n"));
225                         talloc_free(tmp_ctx);
226                         return NULL;
227                 }
228         
229                 tree_item->error = 0;
230                 if (!check_executable(ctdb->event_script_dir, de->d_name)) {
231                         tree_item->error = errno;
232                 }
233
234                 tree_item->name = talloc_strdup(tree_item, de->d_name);
235                 if (tree_item->name == NULL) {
236                         DEBUG(DEBUG_ERR,(__location__ " Failed to allocate script name.\n"));
237                         talloc_free(tmp_ctx);
238                         return NULL;
239                 }
240
241                 /* store the event script in the tree */
242                 trbt_insert32(tree, (num<<16)|count++, tree_item);
243         }
244         closedir(dir);
245
246         /* Overallocates by one, but that's OK */
247         scripts = talloc_zero_size(tmp_ctx,
248                                    sizeof(*scripts)
249                                    + sizeof(scripts->scripts[0]) * count);
250         if (scripts == NULL) {
251                 DEBUG(DEBUG_ERR, (__location__ " Failed to allocate scripts\n"));
252                 talloc_free(tmp_ctx);
253                 return NULL;
254         }
255         scripts->num_scripts = count;
256
257         for (count = 0; count < scripts->num_scripts; count++) {
258                 tree_item = trbt_findfirstarray32(tree, 1);
259
260                 strcpy(scripts->scripts[count].name, tree_item->name);
261                 scripts->scripts[count].status = -tree_item->error;
262
263                 /* remove this script from the tree */
264                 talloc_free(tree_item);
265         }
266
267         talloc_steal(mem_ctx, scripts);
268         talloc_free(tmp_ctx);
269         return scripts;
270 }
271
272 static int child_setup(struct ctdb_context *ctdb)
273 {
274         if (setpgid(0,0) != 0) {
275                 int ret = -errno;
276                 DEBUG(DEBUG_ERR,("Failed to create process group for event scripts - %s\n",
277                          strerror(errno)));
278                 return ret;
279         }
280
281         signal(SIGTERM, sigterm);
282         return 0;
283 }
284
285 static char *child_command_string(struct ctdb_context *ctdb,
286                                        TALLOC_CTX *ctx,
287                                        bool from_user,
288                                        const char *scriptname,
289                                        enum ctdb_eventscript_call call,
290                                        const char *options)
291 {
292         const char *str = from_user ? "CTDB_CALLED_BY_USER=1 " : "";
293
294         /* Allow a setting where we run the actual monitor event
295            from an external source and replace it with
296            a "status" event that just picks up the actual
297            status of the event asynchronously.
298         */
299         if ((ctdb->tunable.use_status_events_for_monitoring != 0)
300             &&  (call == CTDB_EVENT_MONITOR)
301             &&  !from_user) {
302                 return talloc_asprintf(ctx, "%s%s/%s %s",
303                                        str,
304                                        ctdb->event_script_dir,
305                                        scriptname, "status");
306         } else {
307                 return talloc_asprintf(ctx, "%s%s/%s %s %s",
308                                        str,
309                                        ctdb->event_script_dir,
310                                        scriptname,
311                                        ctdb_eventscript_call_names[call],
312                                        options);
313         }
314 }
315
316 static int child_run_one(struct ctdb_context *ctdb,
317                          const char *scriptname, const char *cmdstr)
318 {
319         int ret;
320
321         ret = system(cmdstr);
322         /* if the system() call was successful, translate ret into the
323            return code from the command
324         */
325         if (ret != -1) {
326                 ret = WEXITSTATUS(ret);
327         } else {
328                 ret = -errno;
329         }
330
331         /* 127 could mean it does not exist, 126 non-executable. */
332         if (ret == 127 || ret == 126) {
333                 /* Re-check it... */
334                 if (!check_executable(ctdb->event_script_dir, scriptname)) {
335                         DEBUG(DEBUG_ERR,("Script %s returned status %u. Someone just deleted it?\n",
336                                          cmdstr, ret));
337                         ret = -errno;
338                 }
339         }
340         return ret;
341 }
342
343 /*
344   Actually run one event script
345   this function is called and run in the context of a forked child
346   which allows it to do blocking calls such as system()
347  */
348 static int child_run_script(struct ctdb_context *ctdb,
349                             bool from_user,
350                             enum ctdb_eventscript_call call,
351                             const char *options,
352                             struct ctdb_script_wire *current)
353 {
354         char *cmdstr;
355         int ret;
356         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
357
358         child_state.start = timeval_current();
359         ret = child_setup(ctdb);
360         if (ret != 0)
361                 goto out;
362
363         cmdstr = child_command_string(ctdb, tmp_ctx, from_user,
364                                       current->name, call, options);
365         CTDB_NO_MEMORY(ctdb, cmdstr);
366         child_state.script_running = cmdstr;
367
368         DEBUG(DEBUG_DEBUG,("Executing event script %s\n",cmdstr));
369
370         if (current->status) {
371                 ret = current->status;
372                 goto out;
373         }
374
375         ret = child_run_one(ctdb, current->name, cmdstr);
376 out:
377         talloc_free(tmp_ctx);
378         return ret;
379 }
380
381 static void ctdb_event_script_handler(struct event_context *ev, struct fd_event *fde,
382                                       uint16_t flags, void *p);
383
384 static int fork_child_for_script(struct ctdb_context *ctdb,
385                                  struct ctdb_event_script_state *state)
386 {
387         int r;
388         struct ctdb_script_wire *current = get_current_script(state);
389
390         current->start = timeval_current();
391
392         r = pipe(state->fd);
393         if (r != 0) {
394                 DEBUG(DEBUG_ERR, (__location__ " pipe failed for child eventscript process\n"));
395                 return -errno;
396         }
397
398         if (!ctdb_fork_with_logging(state, ctdb, log_event_script_output,
399                                     state, &state->child)) {
400                 r = -errno;
401                 close(state->fd[0]);
402                 close(state->fd[1]);
403                 return r;
404         }
405
406         /* If we are the child, do the work. */
407         if (state->child == 0) {
408                 int rt;
409
410                 close(state->fd[0]);
411                 set_close_on_exec(state->fd[1]);
412
413                 rt = child_run_script(ctdb, state->from_user, state->call, state->options, current);
414                 /* We must be able to write PIPEBUF bytes at least; if this
415                    somehow fails, the read above will be short. */
416                 write(state->fd[1], &rt, sizeof(rt));
417                 close(state->fd[1]);
418                 _exit(rt);
419         }
420
421         close(state->fd[1]);
422         set_close_on_exec(state->fd[0]);
423
424         DEBUG(DEBUG_DEBUG, (__location__ " Created PIPE FD:%d to child eventscript process\n", state->fd[0]));
425
426         /* Set ourselves up to be called when that's done. */
427         event_add_fd(ctdb->ev, state, state->fd[0], EVENT_FD_READ|EVENT_FD_AUTOCLOSE,
428                      ctdb_event_script_handler, state);
429         return 0;
430 }
431
432 /*
433  Summarize status of this run of scripts.
434  */
435 static int script_status(struct ctdb_scripts_wire *scripts)
436 {
437         unsigned int i;
438
439         for (i = 0; i < scripts->num_scripts; i++) {
440                 switch (scripts->scripts[i].status) {
441                 case -ENOENT:
442                 case -ENOEXEC:
443                         /* Disabled or missing; that's OK. */
444                         break;
445                 case 0:
446                         /* No problem. */
447                         break;
448                 default:
449                         return scripts->scripts[i].status;
450                 }
451         }
452
453         /* All OK! */
454         return 0;
455 }
456
457 /* called when child is finished */
458 static void ctdb_event_script_handler(struct event_context *ev, struct fd_event *fde, 
459                                       uint16_t flags, void *p)
460 {
461         struct ctdb_event_script_state *state = 
462                 talloc_get_type(p, struct ctdb_event_script_state);
463         struct ctdb_script_wire *current = get_current_script(state);
464         struct ctdb_context *ctdb = state->ctdb;
465         int r, status;
466
467         r = read(state->fd[0], &current->status, sizeof(current->status));
468         if (r < 0) {
469                 current->status = -errno;
470         } else if (r != sizeof(current->status)) {
471                 current->status = -EIO;
472         }
473
474         current->finished = timeval_current();
475         /* valgrind gets overloaded if we run next script as it's still doing
476          * post-execution analysis, so kill finished child here. */
477         if (ctdb->valgrinding) {
478                 kill(state->child, SIGKILL);
479         }
480
481         state->child = 0;
482
483         status = script_status(state->scripts);
484
485         /* Aborted or finished all scripts?  We're done. */
486         if (status != 0 || state->current+1 == state->scripts->num_scripts) {
487                 DEBUG(DEBUG_INFO,(__location__ " Eventscript %s %s finished with state %d\n",
488                                   ctdb_eventscript_call_names[state->call], state->options, status));
489
490                 ctdb->event_script_timeouts = 0;
491                 talloc_free(state);
492                 return;
493         }
494
495         /* Forget about that old fd. */
496         talloc_free(fde);
497
498         /* Next script! */
499         state->current++;
500         current++;
501         current->status = fork_child_for_script(ctdb, state);
502         if (current->status != 0) {
503                 /* This calls the callback. */
504                 talloc_free(state);
505         }
506 }
507
508 /* called when child times out */
509 static void ctdb_event_script_timeout(struct event_context *ev, struct timed_event *te, 
510                                       struct timeval t, void *p)
511 {
512         struct ctdb_event_script_state *state = talloc_get_type(p, struct ctdb_event_script_state);
513         struct ctdb_context *ctdb = state->ctdb;
514         struct ctdb_script_wire *current = get_current_script(state);
515
516         DEBUG(DEBUG_ERR,("Event script timed out : %s %s %s count : %u  pid : %d\n",
517                          current->name, ctdb_eventscript_call_names[state->call], state->options, ctdb->event_script_timeouts, state->child));
518
519         /* ignore timeouts for these events */
520         switch (state->call) {
521         case CTDB_EVENT_START_RECOVERY:
522         case CTDB_EVENT_RECOVERED:
523         case CTDB_EVENT_TAKE_IP:
524         case CTDB_EVENT_RELEASE_IP:
525         case CTDB_EVENT_STOPPED:
526         case CTDB_EVENT_MONITOR:
527         case CTDB_EVENT_STATUS:
528                 state->scripts->scripts[state->current].status = 0;
529                 DEBUG(DEBUG_ERR,("Ignoring hung script for %s call %d\n", state->options, state->call));
530                 break;
531         default:
532                 state->scripts->scripts[state->current].status = -ETIME;
533         }
534
535         if (kill(state->child, 0) != 0) {
536                 DEBUG(DEBUG_ERR,("Event script child process already dead, errno %s(%d)\n", strerror(errno), errno));
537                 state->child = 0;
538         }
539
540         talloc_free(state);
541 }
542
543 /*
544   destroy an event script: kill it if ->child != 0.
545  */
546 static int event_script_destructor(struct ctdb_event_script_state *state)
547 {
548         int status;
549
550         if (state->child) {
551                 DEBUG(DEBUG_ERR,(__location__ " Sending SIGTERM to child pid:%d\n", state->child));
552
553                 if (kill(state->child, SIGTERM) != 0) {
554                         DEBUG(DEBUG_ERR,("Failed to kill child process for eventscript, errno %s(%d)\n", strerror(errno), errno));
555                 }
556         }
557
558         /* If we were the current monitor, we no longer are. */
559         if (state->ctdb->current_monitor == state) {
560                 state->ctdb->current_monitor = NULL;
561         }
562
563         /* Save our scripts as the last executed status, if we have them.
564          * See ctdb_event_script_callback_v where we abort monitor event. */
565         if (state->scripts) {
566                 talloc_free(state->ctdb->last_status[state->call]);
567                 state->ctdb->last_status[state->call] = state->scripts;
568                 if (state->current < state->ctdb->last_status[state->call]->num_scripts) {
569                         state->ctdb->last_status[state->call]->num_scripts = state->current+1;
570                 }
571         }
572
573         /* Use last status as result, or "OK" if none. */
574         if (state->ctdb->last_status[state->call]) {
575                 status = script_status(state->ctdb->last_status[state->call]);
576         } else {
577                 status = 0;
578         }
579
580         /* This is allowed to free us; talloc will prevent double free anyway,
581          * but beware if you call this outside the destructor! */
582         if (state->callback) {
583                 state->callback(state->ctdb, status, state->private_data);
584         }
585
586         return 0;
587 }
588
589 static unsigned int count_words(const char *options)
590 {
591         unsigned int words = 0;
592
593         options += strspn(options, " \t");
594         while (*options) {
595                 words++;
596                 options += strcspn(options, " \t");
597                 options += strspn(options, " \t");
598         }
599         return words;
600 }
601
602 static bool check_options(enum ctdb_eventscript_call call, const char *options)
603 {
604         switch (call) {
605         /* These all take no arguments. */
606         case CTDB_EVENT_INIT:
607         case CTDB_EVENT_STARTUP:
608         case CTDB_EVENT_START_RECOVERY:
609         case CTDB_EVENT_RECOVERED:
610         case CTDB_EVENT_STOPPED:
611         case CTDB_EVENT_MONITOR:
612         case CTDB_EVENT_STATUS:
613         case CTDB_EVENT_SHUTDOWN:
614         case CTDB_EVENT_RELOAD:
615                 return count_words(options) == 0;
616
617         case CTDB_EVENT_TAKE_IP: /* interface, IP address, netmask bits. */
618         case CTDB_EVENT_RELEASE_IP:
619                 return count_words(options) == 3;
620
621         case CTDB_EVENT_UPDATE_IP: /* old interface, new interface, IP address, netmask bits. */
622                 return count_words(options) == 4;
623
624         default:
625                 DEBUG(DEBUG_ERR,(__location__ "Unknown ctdb_eventscript_call %u\n", call));
626                 return false;
627         }
628 }
629
630 /*
631   run the event script in the background, calling the callback when 
632   finished
633  */
634 static int ctdb_event_script_callback_v(struct ctdb_context *ctdb, 
635                                         void (*callback)(struct ctdb_context *, int, void *),
636                                         void *private_data,
637                                         bool from_user,
638                                         enum ctdb_eventscript_call call,
639                                         const char *fmt, va_list ap)
640 {
641         struct ctdb_event_script_state *state;
642
643         state = talloc(ctdb->event_script_ctx, struct ctdb_event_script_state);
644         CTDB_NO_MEMORY(ctdb, state);
645
646         state->ctdb = ctdb;
647         state->callback = callback;
648         state->private_data = private_data;
649         state->from_user = from_user;
650         state->call = call;
651         state->options = talloc_vasprintf(state, fmt, ap);
652         state->timeout = timeval_set(ctdb->tunable.script_timeout, 0);
653         state->scripts = NULL;
654         if (state->options == NULL) {
655                 DEBUG(DEBUG_ERR, (__location__ " could not allocate state->options\n"));
656                 talloc_free(state);
657                 return -1;
658         }
659         if (!check_options(state->call, state->options)) {
660                 DEBUG(DEBUG_ERR, ("Bad eventscript options '%s' for %s\n",
661                                   ctdb_eventscript_call_names[state->call], state->options));
662                 talloc_free(state);
663                 return -1;
664         }
665
666         if (ctdb->recovery_mode != CTDB_RECOVERY_NORMAL) {
667                 /* we guarantee that only some specifically allowed event scripts are run
668                    while in recovery */
669                 const enum ctdb_eventscript_call allowed_calls[] = {
670                         CTDB_EVENT_INIT,
671                         CTDB_EVENT_START_RECOVERY,
672                         CTDB_EVENT_SHUTDOWN,
673                         CTDB_EVENT_RELEASE_IP,
674                         CTDB_EVENT_STOPPED
675                 };
676                 int i;
677                 for (i=0;i<ARRAY_SIZE(allowed_calls);i++) {
678                         if (call == allowed_calls[i]) break;
679                 }
680                 if (i == ARRAY_SIZE(allowed_calls)) {
681                         DEBUG(DEBUG_ERR,("Refusing to run event scripts call '%s' while in recovery\n",
682                                  ctdb_eventscript_call_names[call]));
683                         talloc_free(state);
684                         return -1;
685                 }
686         }
687
688         /* Kill off any running monitor events to run this event. */
689         if (ctdb->current_monitor) {
690                 /* Discard script status so we don't save to last_status */
691                 talloc_free(ctdb->current_monitor->scripts);
692                 ctdb->current_monitor->scripts = NULL;
693                 talloc_free(ctdb->current_monitor);
694                 ctdb->current_monitor = NULL;
695         }
696
697         DEBUG(DEBUG_INFO,(__location__ " Starting eventscript %s %s\n",
698                           ctdb_eventscript_call_names[state->call],
699                           state->options));
700
701         /* This is not a child of state, since we save it in destructor. */
702         state->scripts = ctdb_get_script_list(ctdb, ctdb);
703         if (state->scripts == NULL) {
704                 talloc_free(state);
705                 return -1;
706         }
707         state->current = 0;
708
709         if (!from_user && (call == CTDB_EVENT_MONITOR || call == CTDB_EVENT_STATUS)) {
710                 ctdb->current_monitor = state;
711         }
712
713         talloc_set_destructor(state, event_script_destructor);
714
715         /* Nothing to do? */
716         if (state->scripts->num_scripts == 0) {
717                 talloc_free(state);
718                 return 0;
719         }
720
721         state->scripts->scripts[0].status = fork_child_for_script(ctdb, state);
722         if (state->scripts->scripts[0].status != 0) {
723                 /* Callback is called from destructor, with fail result. */
724                 talloc_free(state);
725                 return 0;
726         }
727
728         if (!timeval_is_zero(&state->timeout)) {
729                 event_add_timed(ctdb->ev, state, timeval_current_ofs(state->timeout.tv_sec, state->timeout.tv_usec), ctdb_event_script_timeout, state);
730         } else {
731                 DEBUG(DEBUG_ERR, (__location__ " eventscript %s %s called with no timeout\n",
732                                   ctdb_eventscript_call_names[state->call],
733                                   state->options));
734         }
735
736         return 0;
737 }
738
739
740 /*
741   run the event script in the background, calling the callback when 
742   finished
743  */
744 int ctdb_event_script_callback(struct ctdb_context *ctdb, 
745                                TALLOC_CTX *mem_ctx,
746                                void (*callback)(struct ctdb_context *, int, void *),
747                                void *private_data,
748                                bool from_user,
749                                enum ctdb_eventscript_call call,
750                                const char *fmt, ...)
751 {
752         va_list ap;
753         int ret;
754
755         va_start(ap, fmt);
756         ret = ctdb_event_script_callback_v(ctdb, callback, private_data, from_user, call, fmt, ap);
757         va_end(ap);
758
759         return ret;
760 }
761
762
763 struct callback_status {
764         bool done;
765         int status;
766 };
767
768 /*
769   called when ctdb_event_script() finishes
770  */
771 static void event_script_callback(struct ctdb_context *ctdb, int status, void *private_data)
772 {
773         struct callback_status *s = (struct callback_status *)private_data;
774         s->done = true;
775         s->status = status;
776 }
777
778 /*
779   run the event script, waiting for it to complete. Used when the caller
780   doesn't want to continue till the event script has finished.
781  */
782 int ctdb_event_script_args(struct ctdb_context *ctdb, enum ctdb_eventscript_call call,
783                            const char *fmt, ...)
784 {
785         va_list ap;
786         int ret;
787         struct callback_status status;
788
789         va_start(ap, fmt);
790         ret = ctdb_event_script_callback_v(ctdb,
791                         event_script_callback, &status, false, call, fmt, ap);
792         if (ret != 0) {
793                 return ret;
794         }
795         va_end(ap);
796
797         status.status = -1;
798         status.done = false;
799
800         while (status.done == false && event_loop_once(ctdb->ev) == 0) /* noop */;
801
802         if (status.status == -ETIME) {
803                 DEBUG(DEBUG_ERR, (__location__ " eventscript for '%s' timedout."
804                                   " Immediately banning ourself for %d seconds\n",
805                                   ctdb_eventscript_call_names[call],
806                                   ctdb->tunable.recovery_ban_period));
807                 ctdb_ban_self(ctdb);
808         }
809
810         return status.status;
811 }
812
813 int ctdb_event_script(struct ctdb_context *ctdb, enum ctdb_eventscript_call call)
814 {
815         /* GCC complains about empty format string, so use %s and "". */
816         return ctdb_event_script_args(ctdb, call, "%s", "");
817 }
818
819 struct eventscript_callback_state {
820         struct ctdb_req_control *c;
821 };
822
823 /*
824   called when a forced eventscript run has finished
825  */
826 static void run_eventscripts_callback(struct ctdb_context *ctdb, int status, 
827                                  void *private_data)
828 {
829         struct eventscript_callback_state *state = 
830                 talloc_get_type(private_data, struct eventscript_callback_state);
831
832         ctdb_enable_monitoring(ctdb);
833
834         if (status != 0) {
835                 DEBUG(DEBUG_ERR,(__location__ " Failed to forcibly run eventscripts\n"));
836         }
837
838         ctdb_request_control_reply(ctdb, state->c, NULL, status, NULL);
839         /* This will free the struct ctdb_event_script_state we are in! */
840         talloc_free(state);
841         return;
842 }
843
844
845 /* Returns rest of string, or NULL if no match. */
846 static const char *get_call(const char *p, enum ctdb_eventscript_call *call)
847 {
848         unsigned int len;
849
850         /* Skip any initial whitespace. */
851         p += strspn(p, " \t");
852
853         /* See if we match any. */
854         for (*call = 0; *call < CTDB_EVENT_MAX; (*call)++) {
855                 len = strlen(ctdb_eventscript_call_names[*call]);
856                 if (strncmp(p, ctdb_eventscript_call_names[*call], len) == 0) {
857                         /* If end of string or whitespace, we're done. */
858                         if (strcspn(p + len, " \t") == 0) {
859                                 return p + len;
860                         }
861                 }
862         }
863         return NULL;
864 }
865
866 /*
867   A control to force running of the eventscripts from the ctdb client tool
868 */
869 int32_t ctdb_run_eventscripts(struct ctdb_context *ctdb,
870                 struct ctdb_req_control *c,
871                 TDB_DATA indata, bool *async_reply)
872 {
873         int ret;
874         struct eventscript_callback_state *state;
875         const char *options;
876         enum ctdb_eventscript_call call;
877
878         /* Figure out what call they want. */
879         options = get_call((const char *)indata.dptr, &call);
880         if (!options) {
881                 DEBUG(DEBUG_ERR, (__location__ " Invalid forced \"%s\"\n", (const char *)indata.dptr));
882                 return -1;
883         }
884
885         if (ctdb->recovery_mode != CTDB_RECOVERY_NORMAL) {
886                 DEBUG(DEBUG_ERR, (__location__ " Aborted running eventscript \"%s\" while in RECOVERY mode\n", indata.dptr));
887                 return -1;
888         }
889
890         state = talloc(ctdb->event_script_ctx, struct eventscript_callback_state);
891         CTDB_NO_MEMORY(ctdb, state);
892
893         state->c = talloc_steal(state, c);
894
895         DEBUG(DEBUG_NOTICE,("Forced running of eventscripts with arguments %s\n", indata.dptr));
896
897         ctdb_disable_monitoring(ctdb);
898
899         ret = ctdb_event_script_callback(ctdb, 
900                          state, run_eventscripts_callback, state,
901                          true, call, "%s", options);
902
903         if (ret != 0) {
904                 ctdb_enable_monitoring(ctdb);
905                 DEBUG(DEBUG_ERR,(__location__ " Failed to run eventscripts with arguments %s\n", indata.dptr));
906                 talloc_free(state);
907                 return -1;
908         }
909
910         /* tell ctdb_control.c that we will be replying asynchronously */
911         *async_reply = true;
912
913         return 0;
914 }
915
916
917
918 int32_t ctdb_control_enable_script(struct ctdb_context *ctdb, TDB_DATA indata)
919 {
920         const char *script;
921         struct stat st;
922         char *filename;
923         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
924
925         script = (char *)indata.dptr;
926         if (indata.dsize == 0) {
927                 DEBUG(DEBUG_ERR,(__location__ " No script specified.\n"));
928                 talloc_free(tmp_ctx);
929                 return -1;
930         }
931         if (indata.dptr[indata.dsize - 1] != '\0') {
932                 DEBUG(DEBUG_ERR,(__location__ " String is not null terminated.\n"));
933                 talloc_free(tmp_ctx);
934                 return -1;
935         }
936         if (index(script,'/') != NULL) {
937                 DEBUG(DEBUG_ERR,(__location__ " Script name contains '/'. Failed to enable script %s\n", script));
938                 talloc_free(tmp_ctx);
939                 return -1;
940         }
941
942
943         if (stat(ctdb->event_script_dir, &st) != 0 && 
944             errno == ENOENT) {
945                 DEBUG(DEBUG_CRIT,("No event script directory found at '%s'\n", ctdb->event_script_dir));
946                 talloc_free(tmp_ctx);
947                 return -1;
948         }
949
950
951         filename = talloc_asprintf(tmp_ctx, "%s/%s", ctdb->event_script_dir, script);
952         if (filename == NULL) {
953                 DEBUG(DEBUG_ERR,(__location__ " Failed to create script path\n"));
954                 talloc_free(tmp_ctx);
955                 return -1;
956         }
957
958         if (stat(filename, &st) != 0) {
959                 DEBUG(DEBUG_ERR,("Could not stat event script %s. Failed to enable script.\n", filename));
960                 talloc_free(tmp_ctx);
961                 return -1;
962         }
963
964         if (chmod(filename, st.st_mode | S_IXUSR) == -1) {
965                 DEBUG(DEBUG_ERR,("Could not chmod %s. Failed to enable script.\n", filename));
966                 talloc_free(tmp_ctx);
967                 return -1;
968         }
969
970         talloc_free(tmp_ctx);
971         return 0;
972 }
973
974 int32_t ctdb_control_disable_script(struct ctdb_context *ctdb, TDB_DATA indata)
975 {
976         const char *script;
977         struct stat st;
978         char *filename;
979         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
980
981         script = (char *)indata.dptr;
982         if (indata.dsize == 0) {
983                 DEBUG(DEBUG_ERR,(__location__ " No script specified.\n"));
984                 talloc_free(tmp_ctx);
985                 return -1;
986         }
987         if (indata.dptr[indata.dsize - 1] != '\0') {
988                 DEBUG(DEBUG_ERR,(__location__ " String is not null terminated.\n"));
989                 talloc_free(tmp_ctx);
990                 return -1;
991         }
992         if (index(script,'/') != NULL) {
993                 DEBUG(DEBUG_ERR,(__location__ " Script name contains '/'. Failed to disable script %s\n", script));
994                 talloc_free(tmp_ctx);
995                 return -1;
996         }
997
998
999         if (stat(ctdb->event_script_dir, &st) != 0 && 
1000             errno == ENOENT) {
1001                 DEBUG(DEBUG_CRIT,("No event script directory found at '%s'\n", ctdb->event_script_dir));
1002                 talloc_free(tmp_ctx);
1003                 return -1;
1004         }
1005
1006
1007         filename = talloc_asprintf(tmp_ctx, "%s/%s", ctdb->event_script_dir, script);
1008         if (filename == NULL) {
1009                 DEBUG(DEBUG_ERR,(__location__ " Failed to create script path\n"));
1010                 talloc_free(tmp_ctx);
1011                 return -1;
1012         }
1013
1014         if (stat(filename, &st) != 0) {
1015                 DEBUG(DEBUG_ERR,("Could not stat event script %s. Failed to disable script.\n", filename));
1016                 talloc_free(tmp_ctx);
1017                 return -1;
1018         }
1019
1020         if (chmod(filename, st.st_mode & ~(S_IXUSR|S_IXGRP|S_IXOTH)) == -1) {
1021                 DEBUG(DEBUG_ERR,("Could not chmod %s. Failed to disable script.\n", filename));
1022                 talloc_free(tmp_ctx);
1023                 return -1;
1024         }
1025
1026         talloc_free(tmp_ctx);
1027         return 0;
1028 }