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