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