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