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