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