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