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