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