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