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