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