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