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