Merge commit 'origin/master'
[obnox/samba/samba-obnox.git] / ctdb / server / eventscript.c
1 /* 
2    event script handling
3
4    Copyright (C) Andrew Tridgell  2007
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3 of the License, or
9    (at your option) any later version.
10    
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15    
16    You should have received a copy of the GNU General Public License
17    along with this program; if not, see <http://www.gnu.org/licenses/>.
18 */
19
20 #include "includes.h"
21 #include <time.h>
22 #include "system/filesys.h"
23 #include "system/wait.h"
24 #include "system/dir.h"
25 #include "system/locale.h"
26 #include "../include/ctdb_private.h"
27 #include "lib/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         DEBUG(DEBUG_INFO,(__location__ " Starting eventscript %s %s\n",
642                           ctdb_eventscript_call_names[state->call],
643                           state->options));
644
645         /* This is not a child of state, since we save it in destructor. */
646         state->scripts = ctdb_get_script_list(ctdb, ctdb);
647         if (state->scripts == NULL) {
648                 talloc_free(state);
649                 return -1;
650         }
651         state->current = 0;
652
653         /* Nothing to do? */
654         if (state->scripts->num_scripts == 0) {
655                 ctdb->event_script_timeouts = 0;
656                 talloc_free(state->scripts);
657                 talloc_free(state);
658                 return 0;
659         }
660
661         ret = fork_child_for_script(ctdb, state);
662         if (ret != 0) {
663                 talloc_free(state->scripts);
664                 talloc_free(state);
665                 return -1;
666         }
667
668         if (!from_user && (call == CTDB_EVENT_MONITOR || call == CTDB_EVENT_STATUS)) {
669                 ctdb->current_monitor = state;
670         }
671
672         talloc_set_destructor(state, event_script_destructor);
673         if (!timeval_is_zero(&state->timeout)) {
674                 event_add_timed(ctdb->ev, state, timeval_current_ofs(state->timeout.tv_sec, state->timeout.tv_usec), ctdb_event_script_timeout, state);
675         } else {
676                 DEBUG(DEBUG_ERR, (__location__ " eventscript %s %s called with no timeout\n",
677                                   ctdb_eventscript_call_names[state->call],
678                                   state->options));
679         }
680
681         return 0;
682 }
683
684
685 /*
686   run the event script in the background, calling the callback when 
687   finished
688  */
689 int ctdb_event_script_callback(struct ctdb_context *ctdb, 
690                                TALLOC_CTX *mem_ctx,
691                                void (*callback)(struct ctdb_context *, int, void *),
692                                void *private_data,
693                                bool from_user,
694                                enum ctdb_eventscript_call call,
695                                const char *fmt, ...)
696 {
697         va_list ap;
698         int ret;
699
700         va_start(ap, fmt);
701         ret = ctdb_event_script_callback_v(ctdb, callback, private_data, from_user, call, fmt, ap);
702         va_end(ap);
703
704         return ret;
705 }
706
707
708 struct callback_status {
709         bool done;
710         int status;
711 };
712
713 /*
714   called when ctdb_event_script() finishes
715  */
716 static void event_script_callback(struct ctdb_context *ctdb, int status, void *private_data)
717 {
718         struct callback_status *s = (struct callback_status *)private_data;
719         s->done = true;
720         s->status = status;
721 }
722
723 /*
724   run the event script, waiting for it to complete. Used when the caller
725   doesn't want to continue till the event script has finished.
726  */
727 int ctdb_event_script_args(struct ctdb_context *ctdb, enum ctdb_eventscript_call call,
728                            const char *fmt, ...)
729 {
730         va_list ap;
731         int ret;
732         struct callback_status status;
733
734         va_start(ap, fmt);
735         ret = ctdb_event_script_callback_v(ctdb,
736                         event_script_callback, &status, false, call, fmt, ap);
737         if (ret != 0) {
738                 return ret;
739         }
740         va_end(ap);
741
742         status.status = -1;
743         status.done = false;
744
745         while (status.done == false && event_loop_once(ctdb->ev) == 0) /* noop */;
746
747         if (status.status == -ETIME) {
748                 DEBUG(DEBUG_ERR, (__location__ " eventscript for '%s' timedout."
749                                   " Immediately banning ourself for %d seconds\n",
750                                   ctdb_eventscript_call_names[call],
751                                   ctdb->tunable.recovery_ban_period));
752                 ctdb_ban_self(ctdb);
753         }
754
755         return status.status;
756 }
757
758 int ctdb_event_script(struct ctdb_context *ctdb, enum ctdb_eventscript_call call)
759 {
760         /* GCC complains about empty format string, so use %s and "". */
761         return ctdb_event_script_args(ctdb, call, "%s", "");
762 }
763
764 struct eventscript_callback_state {
765         struct ctdb_req_control *c;
766 };
767
768 /*
769   called when a forced eventscript run has finished
770  */
771 static void run_eventscripts_callback(struct ctdb_context *ctdb, int status, 
772                                  void *private_data)
773 {
774         struct eventscript_callback_state *state = 
775                 talloc_get_type(private_data, struct eventscript_callback_state);
776
777         ctdb_enable_monitoring(ctdb);
778
779         if (status != 0) {
780                 DEBUG(DEBUG_ERR,(__location__ " Failed to forcibly run eventscripts\n"));
781         }
782
783         ctdb_request_control_reply(ctdb, state->c, NULL, status, NULL);
784         /* This will free the struct ctdb_event_script_state we are in! */
785         talloc_free(state);
786         return;
787 }
788
789
790 /* Returns rest of string, or NULL if no match. */
791 static const char *get_call(const char *p, enum ctdb_eventscript_call *call)
792 {
793         unsigned int len;
794
795         /* Skip any initial whitespace. */
796         p += strspn(p, " \t");
797
798         /* See if we match any. */
799         for (*call = 0; *call < CTDB_EVENT_MAX; (*call)++) {
800                 len = strlen(ctdb_eventscript_call_names[*call]);
801                 if (strncmp(p, ctdb_eventscript_call_names[*call], len) == 0) {
802                         /* If end of string or whitespace, we're done. */
803                         if (strcspn(p + len, " \t") == 0) {
804                                 return p + len;
805                         }
806                 }
807         }
808         return NULL;
809 }
810
811 /*
812   A control to force running of the eventscripts from the ctdb client tool
813 */
814 int32_t ctdb_run_eventscripts(struct ctdb_context *ctdb,
815                 struct ctdb_req_control *c,
816                 TDB_DATA indata, bool *async_reply)
817 {
818         int ret;
819         struct eventscript_callback_state *state;
820         const char *options;
821         enum ctdb_eventscript_call call;
822
823         /* Figure out what call they want. */
824         options = get_call((const char *)indata.dptr, &call);
825         if (!options) {
826                 DEBUG(DEBUG_ERR, (__location__ " Invalid forced \"%s\"\n", (const char *)indata.dptr));
827                 return -1;
828         }
829
830         if (ctdb->recovery_mode != CTDB_RECOVERY_NORMAL) {
831                 DEBUG(DEBUG_ERR, (__location__ " Aborted running eventscript \"%s\" while in RECOVERY mode\n", indata.dptr));
832                 return -1;
833         }
834
835         state = talloc(ctdb->event_script_ctx, struct eventscript_callback_state);
836         CTDB_NO_MEMORY(ctdb, state);
837
838         state->c = talloc_steal(state, c);
839
840         DEBUG(DEBUG_NOTICE,("Forced running of eventscripts with arguments %s\n", indata.dptr));
841
842         ctdb_disable_monitoring(ctdb);
843
844         ret = ctdb_event_script_callback(ctdb, 
845                          state, run_eventscripts_callback, state,
846                          true, call, "%s", options);
847
848         if (ret != 0) {
849                 ctdb_enable_monitoring(ctdb);
850                 DEBUG(DEBUG_ERR,(__location__ " Failed to run eventscripts with arguments %s\n", indata.dptr));
851                 talloc_free(state);
852                 return -1;
853         }
854
855         /* tell ctdb_control.c that we will be replying asynchronously */
856         *async_reply = true;
857
858         return 0;
859 }
860
861
862
863 int32_t ctdb_control_enable_script(struct ctdb_context *ctdb, TDB_DATA indata)
864 {
865         const char *script;
866         struct stat st;
867         char *filename;
868         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
869
870         script = (char *)indata.dptr;
871         if (indata.dsize == 0) {
872                 DEBUG(DEBUG_ERR,(__location__ " No script specified.\n"));
873                 talloc_free(tmp_ctx);
874                 return -1;
875         }
876         if (indata.dptr[indata.dsize - 1] != '\0') {
877                 DEBUG(DEBUG_ERR,(__location__ " String is not null terminated.\n"));
878                 talloc_free(tmp_ctx);
879                 return -1;
880         }
881         if (index(script,'/') != NULL) {
882                 DEBUG(DEBUG_ERR,(__location__ " Script name contains '/'. Failed to enable script %s\n", script));
883                 talloc_free(tmp_ctx);
884                 return -1;
885         }
886
887
888         if (stat(ctdb->event_script_dir, &st) != 0 && 
889             errno == ENOENT) {
890                 DEBUG(DEBUG_CRIT,("No event script directory found at '%s'\n", ctdb->event_script_dir));
891                 talloc_free(tmp_ctx);
892                 return -1;
893         }
894
895
896         filename = talloc_asprintf(tmp_ctx, "%s/%s", ctdb->event_script_dir, script);
897         if (filename == NULL) {
898                 DEBUG(DEBUG_ERR,(__location__ " Failed to create script path\n"));
899                 talloc_free(tmp_ctx);
900                 return -1;
901         }
902
903         if (stat(filename, &st) != 0) {
904                 DEBUG(DEBUG_ERR,("Could not stat event script %s. Failed to enable script.\n", filename));
905                 talloc_free(tmp_ctx);
906                 return -1;
907         }
908
909         if (chmod(filename, st.st_mode | S_IXUSR) == -1) {
910                 DEBUG(DEBUG_ERR,("Could not chmod %s. Failed to enable script.\n", filename));
911                 talloc_free(tmp_ctx);
912                 return -1;
913         }
914
915         talloc_free(tmp_ctx);
916         return 0;
917 }
918
919 int32_t ctdb_control_disable_script(struct ctdb_context *ctdb, TDB_DATA indata)
920 {
921         const char *script;
922         struct stat st;
923         char *filename;
924         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
925
926         script = (char *)indata.dptr;
927         if (indata.dsize == 0) {
928                 DEBUG(DEBUG_ERR,(__location__ " No script specified.\n"));
929                 talloc_free(tmp_ctx);
930                 return -1;
931         }
932         if (indata.dptr[indata.dsize - 1] != '\0') {
933                 DEBUG(DEBUG_ERR,(__location__ " String is not null terminated.\n"));
934                 talloc_free(tmp_ctx);
935                 return -1;
936         }
937         if (index(script,'/') != NULL) {
938                 DEBUG(DEBUG_ERR,(__location__ " Script name contains '/'. Failed to disable script %s\n", script));
939                 talloc_free(tmp_ctx);
940                 return -1;
941         }
942
943
944         if (stat(ctdb->event_script_dir, &st) != 0 && 
945             errno == ENOENT) {
946                 DEBUG(DEBUG_CRIT,("No event script directory found at '%s'\n", ctdb->event_script_dir));
947                 talloc_free(tmp_ctx);
948                 return -1;
949         }
950
951
952         filename = talloc_asprintf(tmp_ctx, "%s/%s", ctdb->event_script_dir, script);
953         if (filename == NULL) {
954                 DEBUG(DEBUG_ERR,(__location__ " Failed to create script path\n"));
955                 talloc_free(tmp_ctx);
956                 return -1;
957         }
958
959         if (stat(filename, &st) != 0) {
960                 DEBUG(DEBUG_ERR,("Could not stat event script %s. Failed to disable script.\n", filename));
961                 talloc_free(tmp_ctx);
962                 return -1;
963         }
964
965         if (chmod(filename, st.st_mode & ~(S_IXUSR|S_IXGRP|S_IXOTH)) == -1) {
966                 DEBUG(DEBUG_ERR,("Could not chmod %s. Failed to disable script.\n", filename));
967                 talloc_free(tmp_ctx);
968                 return -1;
969         }
970
971         talloc_free(tmp_ctx);
972         return 0;
973 }