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