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