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