eventscript: handle and report generic stat/execution errors
[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         enum ctdb_eventscript_call call;
83         const char *options;
84         struct timeval timeout;
85 };
86
87
88 struct ctdb_monitor_script_status {
89         struct ctdb_monitor_script_status *next;
90         const char *name;
91         struct timeval start;
92         struct timeval finished;
93         int32_t status;
94         char *output;
95 };
96
97 struct ctdb_monitor_script_status_ctx {
98         struct ctdb_monitor_script_status *scripts;
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_status_ctx == NULL) {
109                 return -1;
110         }
111
112         script = ctdb->current_monitor_status_ctx->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_status_ctx == 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_status_ctx == 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_status_ctx, 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_status_ctx->scripts;
164         script->name  = talloc_strdup(script, name);
165         CTDB_NO_MEMORY(ctdb, script->name);
166         script->start = timeval_current();
167         ctdb->current_monitor_status_ctx->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_status_ctx == 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_status_ctx->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_status_ctx == 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_status_ctx->scripts);
255         talloc_free(ctdb->current_monitor_status_ctx);
256         ctdb->current_monitor_status_ctx = 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
436
437 /*
438   Actually run the event script
439   this function is called and run in the context of a forked child
440   which allows it to do blocking calls such as system()
441  */
442 static int ctdb_run_event_script(struct ctdb_context *ctdb,
443                                  bool from_user,
444                                  enum ctdb_eventscript_call call,
445                                  const char *options)
446 {
447         char *cmdstr;
448         int ret;
449         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
450         struct ctdb_script_list *scripts, *current;
451
452         if (!from_user && call == CTDB_EVENT_MONITOR) {
453                 /* This is running in the forked child process. At this stage
454                  * we want to switch from being a ctdb daemon into being a
455                  * client and connect to the real local daemon.
456                  */
457                 if (switch_from_server_to_client(ctdb) != 0) {
458                         DEBUG(DEBUG_CRIT, (__location__ "ERROR: failed to switch eventscript child into client mode. shutting down.\n"));
459                         _exit(1);
460                 }
461
462                 if (ctdb_ctrl_event_script_init(ctdb) != 0) {
463                         DEBUG(DEBUG_ERR,(__location__ " Failed to init event script monitoring\n"));
464                         talloc_free(tmp_ctx);
465                         return -1;
466                 }
467         }
468
469         if (ctdb->recovery_mode != CTDB_RECOVERY_NORMAL) {
470                 /* we guarantee that only some specifically allowed event scripts are run
471                    while in recovery */
472                 const enum ctdb_eventscript_call allowed_calls[] = {
473                         CTDB_EVENT_START_RECOVERY, CTDB_EVENT_SHUTDOWN, CTDB_EVENT_RELEASE_IP, CTDB_EVENT_STOPPED };
474                 int i;
475                 for (i=0;i<ARRAY_SIZE(allowed_calls);i++) {
476                         if (call == allowed_calls[i]) break;
477                 }
478                 if (i == ARRAY_SIZE(allowed_calls)) {
479                         DEBUG(DEBUG_ERR,("Refusing to run event scripts call '%s' while in recovery\n",
480                                  call_names[call]));
481                         talloc_free(tmp_ctx);
482                         return -1;
483                 }
484         }
485
486         if (setpgid(0,0) != 0) {
487                 DEBUG(DEBUG_ERR,("Failed to create process group for event scripts - %s\n",
488                          strerror(errno)));
489                 talloc_free(tmp_ctx);
490                 return -1;              
491         }
492
493         signal(SIGTERM, sigterm);
494
495         child_state.start = timeval_current();
496         child_state.script_running = "startup";
497
498         scripts = ctdb_get_script_list(ctdb, tmp_ctx);
499
500         /* fetch the scripts from the tree one by one and execute
501            them
502          */
503         for (current=scripts; current; current=current->next) {
504                 const char *str = from_user ? "CTDB_CALLED_BY_USER=1 " : "";
505         
506                 /* Allow a setting where we run the actual monitor event
507                    from an external source and replace it with
508                    a "status" event that just picks up the actual
509                    status of the event asynchronously.
510                 */
511                 if ((ctdb->tunable.use_status_events_for_monitoring != 0) 
512                 &&  (call == CTDB_EVENT_MONITOR)
513                 &&  !from_user) {
514                         cmdstr = talloc_asprintf(tmp_ctx, "%s%s/%s %s",
515                                         str,
516                                         ctdb->event_script_dir,
517                                         current->name, "status");
518                 } else {
519                         cmdstr = talloc_asprintf(tmp_ctx, "%s%s/%s %s %s",
520                                         str,
521                                         ctdb->event_script_dir,
522                                         current->name, call_names[call], options);
523                 }
524                 CTDB_NO_MEMORY(ctdb, cmdstr);
525
526                 DEBUG(DEBUG_INFO,("Executing event script %s\n",cmdstr));
527
528                 child_state.start = timeval_current();
529                 child_state.script_running = cmdstr;
530
531                 if (!from_user && call == CTDB_EVENT_MONITOR) {
532                         if (ctdb_ctrl_event_script_start(ctdb, current->name) != 0) {
533                                 DEBUG(DEBUG_ERR,(__location__ " Failed to start event script monitoring\n"));
534                                 talloc_free(tmp_ctx);
535                                 return -1;
536                         }
537
538                         if (current->error) {
539                                 if (ctdb_ctrl_event_script_stop(ctdb, -current->error) != 0) {
540                                         DEBUG(DEBUG_ERR,(__location__ " Failed to report disabled eventscript\n"));
541                                         talloc_free(tmp_ctx);
542                                         return -1;
543                                 }
544                         }
545                 }
546
547                 if (current->error) {
548                         continue;
549                 }
550
551                 ret = system(cmdstr);
552                 /* if the system() call was successful, translate ret into the
553                    return code from the command
554                 */
555                 if (ret != -1) {
556                         ret = WEXITSTATUS(ret);
557                 } else {
558                         ret = -errno;
559                 }
560
561                 /* 127 could mean it does not exist, 126 non-executable. */
562                 if (ret == 127 || ret == 126) {
563                         /* Re-check it... */
564                         if (!check_executable(ctdb->event_script_dir,
565                                               current->name)) {
566                                 DEBUG(DEBUG_ERR,("Script %s returned status %u. Someone just deleted it?\n",
567                                                  cmdstr, ret));
568                                 ret = -errno;
569                         }
570                 }
571  
572                 if (!from_user && call == CTDB_EVENT_MONITOR) {
573                         if (ctdb_ctrl_event_script_stop(ctdb, ret) != 0) {
574                                 DEBUG(DEBUG_ERR,(__location__ " Failed to stop event script monitoring\n"));
575                                 talloc_free(tmp_ctx);
576                                 return -1;
577                         }
578                 }
579
580                 /* now we've reported the per-script error, don't exit the loop
581                  * just because it vanished or was disabled. */
582                 if (ret == -ENOENT || ret == -ENOEXEC) {
583                         ret = 0;
584                 }
585
586                 /* return an error if the script failed */
587                 if (ret != 0) {
588                         DEBUG(DEBUG_ERR,("Event script %s failed with error %d\n", cmdstr, ret));
589                         if (!from_user && call == CTDB_EVENT_MONITOR) {
590                                 if (ctdb_ctrl_event_script_finished(ctdb) != 0) {
591                                         DEBUG(DEBUG_ERR,(__location__ " Failed to finish event script monitoring\n"));
592                                         talloc_free(tmp_ctx);
593                                         return -1;
594                                 }
595                         }
596
597                         talloc_free(tmp_ctx);
598                         return ret;
599                 }
600         }
601
602         child_state.start = timeval_current();
603         child_state.script_running = "finished";
604         
605         if (!from_user && call == CTDB_EVENT_MONITOR) {
606                 if (ctdb_ctrl_event_script_finished(ctdb) != 0) {
607                         DEBUG(DEBUG_ERR,(__location__ " Failed to finish event script monitoring\n"));
608                         talloc_free(tmp_ctx);
609                         return -1;
610                 }
611         }
612
613         talloc_free(tmp_ctx);
614         return 0;
615 }
616
617 /* called when child is finished */
618 static void ctdb_event_script_handler(struct event_context *ev, struct fd_event *fde, 
619                                       uint16_t flags, void *p)
620 {
621         struct ctdb_event_script_state *state = 
622                 talloc_get_type(p, struct ctdb_event_script_state);
623         struct ctdb_context *ctdb = state->ctdb;
624
625         if (read(state->fd[0], &state->cb_status, sizeof(state->cb_status)) !=
626             sizeof(state->cb_status)) {
627                 state->cb_status = -2;
628         }
629
630         DEBUG(DEBUG_INFO,(__location__ " Eventscript %s %s finished with state %d\n",
631                           call_names[state->call], state->options, state->cb_status));
632
633         state->child = 0;
634         ctdb->event_script_timeouts = 0;
635         talloc_free(state);
636 }
637
638 static void ctdb_ban_self(struct ctdb_context *ctdb, uint32_t ban_period)
639 {
640         TDB_DATA data;
641         struct ctdb_ban_time bantime;
642
643         bantime.pnn  = ctdb->pnn;
644         bantime.time = ban_period;
645
646         data.dsize = sizeof(bantime);
647         data.dptr  = (uint8_t *)&bantime;
648
649         ctdb_control_set_ban_state(ctdb, data);
650 }
651
652
653 /* called when child times out */
654 static void ctdb_event_script_timeout(struct event_context *ev, struct timed_event *te, 
655                                       struct timeval t, void *p)
656 {
657         struct ctdb_event_script_state *state = talloc_get_type(p, struct ctdb_event_script_state);
658         struct ctdb_context *ctdb = state->ctdb;
659
660         DEBUG(DEBUG_ERR,("Event script timed out : %s %s count : %u  pid : %d\n",
661                          call_names[state->call], state->options, ctdb->event_script_timeouts, state->child));
662
663         if (kill(state->child, 0) != 0) {
664                 DEBUG(DEBUG_ERR,("Event script child process already dead, errno %s(%d)\n", strerror(errno), errno));
665                 state->child = 0;
666                 talloc_free(state);
667                 return;
668         }
669
670         if (state->call == CTDB_EVENT_MONITOR) {
671                 /* if it is a monitor event, we allow it to "hang" a few times
672                    before we declare it a failure and ban ourself (and make
673                    ourself unhealthy)
674                 */
675                 DEBUG(DEBUG_ERR, (__location__ " eventscript for monitor event timedout.\n"));
676
677                 ctdb->event_script_timeouts++;
678
679                 if (ctdb->event_script_timeouts > ctdb->tunable.script_ban_count) {
680                         DEBUG(DEBUG_ERR, ("Maximum timeout count %u reached for eventscript. Making node unhealthy\n", ctdb->tunable.script_ban_count));
681                         state->cb_status = -ETIME;
682                 } else {
683                         state->cb_status = 0;
684                 }
685         } else if (state->call == CTDB_EVENT_STARTUP) {
686                 DEBUG(DEBUG_ERR, (__location__ " eventscript for startup event timedout.\n"));
687                 state->cb_status = -ETIME;
688         } else {
689                 /* if it is not a monitor or a startup event we ban ourself
690                    immediately
691                 */
692                 DEBUG(DEBUG_ERR, (__location__ " eventscript for NON-monitor/NON-startup event timedout. Immediately banning ourself for %d seconds\n", ctdb->tunable.recovery_ban_period));
693
694                 ctdb_ban_self(ctdb, ctdb->tunable.recovery_ban_period);
695
696                 state->cb_status = -ETIME;
697         }
698
699         if (state->call == CTDB_EVENT_MONITOR || state->call == CTDB_EVENT_STATUS) {
700                 struct ctdb_monitor_script_status *script;
701
702                 if (ctdb->current_monitor_status_ctx == NULL) {
703                         talloc_free(state);
704                         return;
705                 }
706
707                 script = ctdb->current_monitor_status_ctx->scripts;
708                 if (script != NULL) {
709                         script->status = state->cb_status;
710                 }
711
712                 ctdb_control_event_script_finished(ctdb);
713         }
714
715         talloc_free(state);
716 }
717
718 /*
719   destroy an event script: kill it if ->child != 0.
720  */
721 static int event_script_destructor(struct ctdb_event_script_state *state)
722 {
723         if (state->child) {
724                 DEBUG(DEBUG_ERR,(__location__ " Sending SIGTERM to child pid:%d\n", state->child));
725
726                 if (kill(state->child, SIGTERM) != 0) {
727                         DEBUG(DEBUG_ERR,("Failed to kill child process for eventscript, errno %s(%d)\n", strerror(errno), errno));
728                 }
729         }
730
731         /* This is allowed to free us; talloc will prevent double free anyway,
732          * but beware if you call this outside the destructor! */
733         if (state->callback) {
734                 state->callback(state->ctdb, state->cb_status, state->private_data);
735         }
736
737         return 0;
738 }
739
740 static unsigned int count_words(const char *options)
741 {
742         unsigned int words = 0;
743
744         options += strspn(options, " \t");
745         while (*options) {
746                 words++;
747                 options += strcspn(options, " \t");
748                 options += strspn(options, " \t");
749         }
750         return words;
751 }
752
753 static bool check_options(enum ctdb_eventscript_call call, const char *options)
754 {
755         switch (call) {
756         /* These all take no arguments. */
757         case CTDB_EVENT_STARTUP:
758         case CTDB_EVENT_START_RECOVERY:
759         case CTDB_EVENT_RECOVERED:
760         case CTDB_EVENT_STOPPED:
761         case CTDB_EVENT_MONITOR:
762         case CTDB_EVENT_STATUS:
763         case CTDB_EVENT_SHUTDOWN:
764         case CTDB_EVENT_RELOAD:
765                 return count_words(options) == 0;
766
767         case CTDB_EVENT_TAKE_IP: /* interface, IP address, netmask bits. */
768         case CTDB_EVENT_RELEASE_IP:
769                 return count_words(options) == 3;
770
771         default:
772                 DEBUG(DEBUG_ERR,(__location__ "Unknown ctdb_eventscript_call %u\n", call));
773                 return false;
774         }
775 }
776
777 /*
778   run the event script in the background, calling the callback when 
779   finished
780  */
781 static int ctdb_event_script_callback_v(struct ctdb_context *ctdb, 
782                                         void (*callback)(struct ctdb_context *, int, void *),
783                                         void *private_data,
784                                         bool from_user,
785                                         enum ctdb_eventscript_call call,
786                                         const char *fmt, va_list ap)
787 {
788         TALLOC_CTX *mem_ctx;
789         struct ctdb_event_script_state *state;
790         int ret;
791
792         if (!from_user && (call == CTDB_EVENT_MONITOR || call == CTDB_EVENT_STATUS)) {
793                 /* if this was a "monitor" or a status event, we recycle the
794                    context to start a new monitor event
795                 */
796                 if (ctdb->monitor_event_script_ctx != NULL) {
797                         talloc_free(ctdb->monitor_event_script_ctx);
798                         ctdb->monitor_event_script_ctx = NULL;
799                 }
800                 ctdb->monitor_event_script_ctx = talloc_new(ctdb);
801                 mem_ctx = ctdb->monitor_event_script_ctx;
802
803                 if (ctdb->current_monitor_status_ctx != NULL) {
804                         talloc_free(ctdb->current_monitor_status_ctx);
805                         ctdb->current_monitor_status_ctx = NULL;
806                 }
807
808                 ctdb->current_monitor_status_ctx = talloc(ctdb, struct ctdb_monitor_script_status_ctx);
809                 CTDB_NO_MEMORY(ctdb, ctdb->current_monitor_status_ctx);
810                 ctdb->current_monitor_status_ctx->scripts = NULL;
811         } else {
812                 /* any other script will first terminate any monitor event */
813                 if (ctdb->monitor_event_script_ctx != NULL) {
814                         talloc_free(ctdb->monitor_event_script_ctx);
815                         ctdb->monitor_event_script_ctx = NULL;
816                 }
817                 /* and then use a context common for all non-monitor events */
818                 if (ctdb->other_event_script_ctx == NULL) {
819                         ctdb->other_event_script_ctx = talloc_new(ctdb);
820                 }
821                 mem_ctx = ctdb->other_event_script_ctx;
822         }
823
824         state = talloc(mem_ctx, struct ctdb_event_script_state);
825         CTDB_NO_MEMORY(ctdb, state);
826
827         state->ctdb = ctdb;
828         state->callback = callback;
829         state->private_data = private_data;
830         state->call = call;
831         state->options = talloc_vasprintf(state, fmt, ap);
832         state->timeout = timeval_set(ctdb->tunable.script_timeout, 0);
833         if (state->options == NULL) {
834                 DEBUG(DEBUG_ERR, (__location__ " could not allocate state->options\n"));
835                 talloc_free(state);
836                 return -1;
837         }
838         if (!check_options(state->call, state->options)) {
839                 DEBUG(DEBUG_ERR, ("Bad eventscript options '%s' for %s\n",
840                                   call_names[state->call], state->options));
841                 talloc_free(state);
842                 return -1;
843         }
844
845         DEBUG(DEBUG_INFO,(__location__ " Starting eventscript %s %s\n",
846                           call_names[state->call], state->options));
847         
848         ret = pipe(state->fd);
849         if (ret != 0) {
850                 talloc_free(state);
851                 return -1;
852         }
853
854         state->child = fork();
855
856         if (state->child == (pid_t)-1) {
857                 close(state->fd[0]);
858                 close(state->fd[1]);
859                 talloc_free(state);
860                 return -1;
861         }
862
863         if (state->child == 0) {
864                 int rt;
865
866                 close(state->fd[0]);
867                 set_close_on_exec(state->fd[1]);
868
869                 rt = ctdb_run_event_script(ctdb, from_user, state->call, state->options);
870                 /* We must be able to write PIPEBUF bytes at least; if this
871                    somehow fails, the read above will be short. */
872                 write(state->fd[1], &rt, sizeof(rt));
873                 close(state->fd[1]);
874                 _exit(rt);
875         }
876
877         close(state->fd[1]);
878         set_close_on_exec(state->fd[0]);
879         talloc_set_destructor(state, event_script_destructor);
880
881         DEBUG(DEBUG_DEBUG, (__location__ " Created PIPE FD:%d to child eventscript process\n", state->fd[0]));
882
883         event_add_fd(ctdb->ev, state, state->fd[0], EVENT_FD_READ|EVENT_FD_AUTOCLOSE,
884                      ctdb_event_script_handler, state);
885
886         if (!timeval_is_zero(&state->timeout)) {
887                 event_add_timed(ctdb->ev, state, timeval_current_ofs(state->timeout.tv_sec, state->timeout.tv_usec), ctdb_event_script_timeout, state);
888         } else {
889                 DEBUG(DEBUG_ERR, (__location__ " eventscript %s %s called with no timeout\n",
890                                   call_names[state->call], state->options));
891         }
892
893         return 0;
894 }
895
896
897 /*
898   run the event script in the background, calling the callback when 
899   finished
900  */
901 int ctdb_event_script_callback(struct ctdb_context *ctdb, 
902                                TALLOC_CTX *mem_ctx,
903                                void (*callback)(struct ctdb_context *, int, void *),
904                                void *private_data,
905                                bool from_user,
906                                enum ctdb_eventscript_call call,
907                                const char *fmt, ...)
908 {
909         va_list ap;
910         int ret;
911
912         va_start(ap, fmt);
913         ret = ctdb_event_script_callback_v(ctdb, callback, private_data, from_user, call, fmt, ap);
914         va_end(ap);
915
916         return ret;
917 }
918
919
920 struct callback_status {
921         bool done;
922         int status;
923 };
924
925 /*
926   called when ctdb_event_script() finishes
927  */
928 static void event_script_callback(struct ctdb_context *ctdb, int status, void *private_data)
929 {
930         struct callback_status *s = (struct callback_status *)private_data;
931         s->done = true;
932         s->status = status;
933 }
934
935 /*
936   run the event script, waiting for it to complete. Used when the caller
937   doesn't want to continue till the event script has finished.
938  */
939 int ctdb_event_script_args(struct ctdb_context *ctdb, enum ctdb_eventscript_call call,
940                            const char *fmt, ...)
941 {
942         va_list ap;
943         int ret;
944         struct callback_status status;
945
946         va_start(ap, fmt);
947         ret = ctdb_event_script_callback_v(ctdb,
948                         event_script_callback, &status, false, call, fmt, ap);
949         if (ret != 0) {
950                 return ret;
951         }
952         va_end(ap);
953
954         status.status = -1;
955         status.done = false;
956
957         while (status.done == false && event_loop_once(ctdb->ev) == 0) /* noop */;
958
959         return status.status;
960 }
961
962 int ctdb_event_script(struct ctdb_context *ctdb, enum ctdb_eventscript_call call)
963 {
964         /* GCC complains about empty format string, so use %s and "". */
965         return ctdb_event_script_args(ctdb, call, "%s", "");
966 }
967
968 struct eventscript_callback_state {
969         struct ctdb_req_control *c;
970 };
971
972 /*
973   called when a forced eventscript run has finished
974  */
975 static void run_eventscripts_callback(struct ctdb_context *ctdb, int status, 
976                                  void *private_data)
977 {
978         struct eventscript_callback_state *state = 
979                 talloc_get_type(private_data, struct eventscript_callback_state);
980
981         ctdb_enable_monitoring(ctdb);
982
983         if (status != 0) {
984                 DEBUG(DEBUG_ERR,(__location__ " Failed to forcibly run eventscripts\n"));
985         }
986
987         ctdb_request_control_reply(ctdb, state->c, NULL, status, NULL);
988         /* This will free the struct ctdb_event_script_state we are in! */
989         talloc_free(state);
990         return;
991 }
992
993
994 /* Returns rest of string, or NULL if no match. */
995 static const char *get_call(const char *p, enum ctdb_eventscript_call *call)
996 {
997         unsigned int len;
998
999         /* Skip any initial whitespace. */
1000         p += strspn(p, " \t");
1001
1002         /* See if we match any. */
1003         for (*call = 0; *call < ARRAY_SIZE(call_names); (*call)++) {
1004                 len = strlen(call_names[*call]);
1005                 if (strncmp(p, call_names[*call], len) == 0) {
1006                         /* If end of string or whitespace, we're done. */
1007                         if (strcspn(p + len, " \t") == 0) {
1008                                 return p + len;
1009                         }
1010                 }
1011         }
1012         return NULL;
1013 }
1014
1015 /*
1016   A control to force running of the eventscripts from the ctdb client tool
1017 */
1018 int32_t ctdb_run_eventscripts(struct ctdb_context *ctdb,
1019                 struct ctdb_req_control *c,
1020                 TDB_DATA indata, bool *async_reply)
1021 {
1022         int ret;
1023         struct eventscript_callback_state *state;
1024         const char *options;
1025         enum ctdb_eventscript_call call;
1026
1027         /* Figure out what call they want. */
1028         options = get_call((const char *)indata.dptr, &call);
1029         if (!options) {
1030                 DEBUG(DEBUG_ERR, (__location__ " Invalid forced \"%s\"\n", (const char *)indata.dptr));
1031                 return -1;
1032         }
1033
1034         if (ctdb->recovery_mode != CTDB_RECOVERY_NORMAL) {
1035                 DEBUG(DEBUG_ERR, (__location__ " Aborted running eventscript \"%s\" while in RECOVERY mode\n", indata.dptr));
1036                 return -1;
1037         }
1038
1039         state = talloc(ctdb->other_event_script_ctx, struct eventscript_callback_state);
1040         CTDB_NO_MEMORY(ctdb, state);
1041
1042         state->c = talloc_steal(state, c);
1043
1044         DEBUG(DEBUG_NOTICE,("Forced running of eventscripts with arguments %s\n", indata.dptr));
1045
1046         ctdb_disable_monitoring(ctdb);
1047
1048         ret = ctdb_event_script_callback(ctdb, 
1049                          state, run_eventscripts_callback, state,
1050                          true, call, "%s", options);
1051
1052         if (ret != 0) {
1053                 ctdb_enable_monitoring(ctdb);
1054                 DEBUG(DEBUG_ERR,(__location__ " Failed to run eventscripts with arguments %s\n", indata.dptr));
1055                 talloc_free(state);
1056                 return -1;
1057         }
1058
1059         /* tell ctdb_control.c that we will be replying asynchronously */
1060         *async_reply = true;
1061
1062         return 0;
1063 }
1064
1065
1066
1067 int32_t ctdb_control_enable_script(struct ctdb_context *ctdb, TDB_DATA indata)
1068 {
1069         const char *script;
1070         struct stat st;
1071         char *filename;
1072         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
1073
1074         script = (char *)indata.dptr;
1075         if (indata.dsize == 0) {
1076                 DEBUG(DEBUG_ERR,(__location__ " No script specified.\n"));
1077                 talloc_free(tmp_ctx);
1078                 return -1;
1079         }
1080         if (indata.dptr[indata.dsize - 1] != '\0') {
1081                 DEBUG(DEBUG_ERR,(__location__ " String is not null terminated.\n"));
1082                 talloc_free(tmp_ctx);
1083                 return -1;
1084         }
1085         if (index(script,'/') != NULL) {
1086                 DEBUG(DEBUG_ERR,(__location__ " Script name contains '/'. Failed to enable script %s\n", script));
1087                 talloc_free(tmp_ctx);
1088                 return -1;
1089         }
1090
1091
1092         if (stat(ctdb->event_script_dir, &st) != 0 && 
1093             errno == ENOENT) {
1094                 DEBUG(DEBUG_CRIT,("No event script directory found at '%s'\n", ctdb->event_script_dir));
1095                 talloc_free(tmp_ctx);
1096                 return -1;
1097         }
1098
1099
1100         filename = talloc_asprintf(tmp_ctx, "%s/%s", ctdb->event_script_dir, script);
1101         if (filename == NULL) {
1102                 DEBUG(DEBUG_ERR,(__location__ " Failed to create script path\n"));
1103                 talloc_free(tmp_ctx);
1104                 return -1;
1105         }
1106
1107         if (stat(filename, &st) != 0) {
1108                 DEBUG(DEBUG_ERR,("Could not stat event script %s. Failed to enable script.\n", filename));
1109                 talloc_free(tmp_ctx);
1110                 return -1;
1111         }
1112
1113         if (chmod(filename, st.st_mode | S_IXUSR) == -1) {
1114                 DEBUG(DEBUG_ERR,("Could not chmod %s. Failed to enable script.\n", filename));
1115                 talloc_free(tmp_ctx);
1116                 return -1;
1117         }
1118
1119         talloc_free(tmp_ctx);
1120         return 0;
1121 }
1122
1123 int32_t ctdb_control_disable_script(struct ctdb_context *ctdb, TDB_DATA indata)
1124 {
1125         const char *script;
1126         struct stat st;
1127         char *filename;
1128         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
1129
1130         script = (char *)indata.dptr;
1131         if (indata.dsize == 0) {
1132                 DEBUG(DEBUG_ERR,(__location__ " No script specified.\n"));
1133                 talloc_free(tmp_ctx);
1134                 return -1;
1135         }
1136         if (indata.dptr[indata.dsize - 1] != '\0') {
1137                 DEBUG(DEBUG_ERR,(__location__ " String is not null terminated.\n"));
1138                 talloc_free(tmp_ctx);
1139                 return -1;
1140         }
1141         if (index(script,'/') != NULL) {
1142                 DEBUG(DEBUG_ERR,(__location__ " Script name contains '/'. Failed to disable script %s\n", script));
1143                 talloc_free(tmp_ctx);
1144                 return -1;
1145         }
1146
1147
1148         if (stat(ctdb->event_script_dir, &st) != 0 && 
1149             errno == ENOENT) {
1150                 DEBUG(DEBUG_CRIT,("No event script directory found at '%s'\n", ctdb->event_script_dir));
1151                 talloc_free(tmp_ctx);
1152                 return -1;
1153         }
1154
1155
1156         filename = talloc_asprintf(tmp_ctx, "%s/%s", ctdb->event_script_dir, script);
1157         if (filename == NULL) {
1158                 DEBUG(DEBUG_ERR,(__location__ " Failed to create script path\n"));
1159                 talloc_free(tmp_ctx);
1160                 return -1;
1161         }
1162
1163         if (stat(filename, &st) != 0) {
1164                 DEBUG(DEBUG_ERR,("Could not stat event script %s. Failed to disable script.\n", filename));
1165                 talloc_free(tmp_ctx);
1166                 return -1;
1167         }
1168
1169         if (chmod(filename, st.st_mode & ~(S_IXUSR|S_IXGRP|S_IXOTH)) == -1) {
1170                 DEBUG(DEBUG_ERR,("Could not chmod %s. Failed to disable script.\n", filename));
1171                 talloc_free(tmp_ctx);
1172                 return -1;
1173         }
1174
1175         talloc_free(tmp_ctx);
1176         return 0;
1177 }