ctdb: Drop unnecessary defines of TEVENT_DEPRECATED
[sfrench/samba-autobuild/.git] / ctdb / tools / ctdb.c
1 /* 
2    ctdb control tool
3
4    Copyright (C) Andrew Tridgell  2007
5    Copyright (C) Ronnie Sahlberg  2007
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11    
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16    
17    You should have received a copy of the GNU General Public License
18    along with this program; if not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include "replace.h"
22 #include "system/time.h"
23 #include "system/filesys.h"
24 #include "system/network.h"
25 #include "system/locale.h"
26
27 #include <popt.h>
28 #include <talloc.h>
29 #include <tevent.h>
30 #include <tdb.h>
31
32 #include "lib/tdb_wrap/tdb_wrap.h"
33 #include "lib/util/dlinklist.h"
34 #include "lib/util/debug.h"
35 #include "lib/util/substitute.h"
36 #include "lib/util/time.h"
37
38 #include "ctdb_version.h"
39 #include "ctdb_private.h"
40 #include "ctdb_client.h"
41
42 #include "common/cmdline.h"
43 #include "common/rb_tree.h"
44 #include "common/system.h"
45 #include "common/common.h"
46 #include "common/logging.h"
47
48 #define ERR_TIMEOUT     20      /* timed out trying to reach node */
49 #define ERR_NONODE      21      /* node does not exist */
50 #define ERR_DISNODE     22      /* node is disconnected */
51
52 static void usage(void);
53
54 static struct {
55         int timelimit;
56         uint32_t pnn;
57         uint32_t *nodes;
58         int machinereadable;
59         const char *machineseparator;
60         int verbose;
61         int maxruntime;
62         int printemptyrecords;
63         int printdatasize;
64         int printlmaster;
65         int printhash;
66         int printrecordflags;
67 } options;
68
69 #define LONGTIMEOUT options.timelimit*10
70
71 #define TIMELIMIT() timeval_current_ofs(options.timelimit, 0)
72 #define LONGTIMELIMIT() timeval_current_ofs(LONGTIMEOUT, 0)
73
74 static double timeval_delta(struct timeval *tv2, struct timeval *tv)
75 {
76         return (tv2->tv_sec - tv->tv_sec) +
77                 (tv2->tv_usec - tv->tv_usec)*1.0e-6;
78 }
79
80 static int control_version(struct ctdb_context *ctdb, int argc, const char **argv)
81 {
82         printf("CTDB version: %s\n", CTDB_VERSION_STRING);
83         return 0;
84 }
85
86 /* Like printf(3) but substitute for separator in format */
87 static int printm(const char *format, ...) PRINTF_ATTRIBUTE(1,2);
88 static int printm(const char *format, ...)
89 {
90         va_list ap;
91         int ret;
92         size_t len = strlen(format);
93         char new_format[len+1];
94
95         strcpy(new_format, format);
96
97         if (options.machineseparator[0] != ':') {
98                 all_string_sub(new_format,
99                                ":", options.machineseparator, len + 1);
100         }
101
102         va_start(ap, format);
103         ret = vprintf(new_format, ap);
104         va_end(ap);
105
106         return ret;
107 }
108
109 #define CTDB_NOMEM_ABORT(p) do { if (!(p)) {                            \
110                 DEBUG(DEBUG_ALERT,("ctdb fatal error: %s\n",            \
111                                    "Out of memory in " __location__ )); \
112                 abort();                                                \
113         }} while (0)
114
115 static uint32_t getpnn(struct ctdb_context *ctdb)
116 {
117         if ((options.pnn == CTDB_BROADCAST_ALL) ||
118             (options.pnn == CTDB_MULTICAST)) {
119                 DEBUG(DEBUG_ERR,
120                       ("Cannot get PNN for node %u\n", options.pnn));
121                 exit(1);
122         }
123
124         if (options.pnn == CTDB_CURRENT_NODE) {
125                 return ctdb_get_pnn(ctdb);
126         } else {
127                 return options.pnn;
128         }
129 }
130
131 static void assert_single_node_only(void)
132 {
133         if ((options.pnn == CTDB_BROADCAST_ALL) ||
134             (options.pnn == CTDB_MULTICAST)) {
135                 DEBUG(DEBUG_ERR,
136                       ("This control can not be applied to multiple PNNs\n"));
137                 exit(1);
138         }
139 }
140
141 static void assert_current_node_only(struct ctdb_context *ctdb)
142 {
143         if (options.pnn != ctdb_get_pnn(ctdb)) {
144                 DEBUG(DEBUG_ERR,
145                       ("This control can only be applied to the current node\n"));
146                 exit(1);
147         }
148 }
149
150 /* Pretty print the flags to a static buffer in human-readable format.
151  * This never returns NULL!
152  */
153 static const char *pretty_print_flags(uint32_t flags)
154 {
155         int j;
156         static const struct {
157                 uint32_t flag;
158                 const char *name;
159         } flag_names[] = {
160                 { NODE_FLAGS_DISCONNECTED,          "DISCONNECTED" },
161                 { NODE_FLAGS_PERMANENTLY_DISABLED,  "DISABLED" },
162                 { NODE_FLAGS_BANNED,                "BANNED" },
163                 { NODE_FLAGS_UNHEALTHY,             "UNHEALTHY" },
164                 { NODE_FLAGS_DELETED,               "DELETED" },
165                 { NODE_FLAGS_STOPPED,               "STOPPED" },
166                 { NODE_FLAGS_INACTIVE,              "INACTIVE" },
167         };
168         static char flags_str[512]; /* Big enough to contain all flag names */
169
170         flags_str[0] = '\0';
171         for (j=0;j<ARRAY_SIZE(flag_names);j++) {
172                 if (flags & flag_names[j].flag) {
173                         if (flags_str[0] == '\0') {
174                                 (void) strcpy(flags_str, flag_names[j].name);
175                         } else {
176                                 (void) strncat(flags_str, "|", sizeof(flags_str)-1);
177                                 (void) strncat(flags_str, flag_names[j].name,
178                                                sizeof(flags_str)-1);
179                         }
180                 }
181         }
182         if (flags_str[0] == '\0') {
183                 (void) strcpy(flags_str, "OK");
184         }
185
186         return flags_str;
187 }
188
189 static int h2i(char h)
190 {
191         if (h >= 'a' && h <= 'f') return h - 'a' + 10;
192         if (h >= 'A' && h <= 'F') return h - 'f' + 10;
193         return h - '0';
194 }
195
196 static TDB_DATA hextodata(TALLOC_CTX *mem_ctx, const char *str, size_t len)
197 {
198         int i;
199         TDB_DATA key = {NULL, 0};
200
201         if (len & 0x01) {
202                 DEBUG(DEBUG_ERR,("Key specified with odd number of hexadecimal digits\n"));
203                 return key;
204         }
205
206         key.dsize = len>>1;
207         key.dptr  = talloc_size(mem_ctx, key.dsize);
208
209         for (i=0; i < len/2; i++) {
210                 key.dptr[i] = h2i(str[i*2]) << 4 | h2i(str[i*2+1]);
211         }
212         return key;
213 }
214
215 static TDB_DATA strtodata(TALLOC_CTX *mem_ctx, const char *str, size_t len)
216 {
217         TDB_DATA key;
218
219         if (!strncmp(str, "0x", 2)) {
220                 key = hextodata(mem_ctx, str + 2, len - 2);
221         } else {
222                 key.dptr  = talloc_memdup(mem_ctx, str, len);
223                 key.dsize = len;
224         }
225
226         return key;
227 }
228
229 /* Parse a nodestring.  Parameter dd_ok controls what happens to nodes
230  * that are disconnected or deleted.  If dd_ok is true those nodes are
231  * included in the output list of nodes.  If dd_ok is false, those
232  * nodes are filtered from the "all" case and cause an error if
233  * explicitly specified.
234  */
235 static bool parse_nodestring(struct ctdb_context *ctdb,
236                              TALLOC_CTX *mem_ctx,
237                              const char * nodestring,
238                              uint32_t current_pnn,
239                              bool dd_ok,
240                              uint32_t **nodes,
241                              uint32_t *pnn_mode)
242 {
243         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
244         int n;
245         uint32_t i;
246         struct ctdb_node_map_old *nodemap;
247         int ret;
248
249         *nodes = NULL;
250
251         ret = ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE, tmp_ctx, &nodemap);
252         if (ret != 0) {
253                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from local node\n"));
254                 talloc_free(tmp_ctx);
255                 exit(10);
256         }
257
258         if (nodestring != NULL) {
259                 *nodes = talloc_array(mem_ctx, uint32_t, 0);
260                 if (*nodes == NULL) {
261                         goto failed;
262                 }
263
264                 n = 0;
265
266                 if (strcmp(nodestring, "all") == 0) {
267                         *pnn_mode = CTDB_BROADCAST_ALL;
268
269                         /* all */
270                         for (i = 0; i < nodemap->num; i++) {
271                                 if ((nodemap->nodes[i].flags &
272                                      (NODE_FLAGS_DISCONNECTED |
273                                       NODE_FLAGS_DELETED)) && !dd_ok) {
274                                         continue;
275                                 }
276                                 *nodes = talloc_realloc(mem_ctx, *nodes,
277                                                         uint32_t, n+1);
278                                 if (*nodes == NULL) {
279                                         goto failed;
280                                 }
281                                 (*nodes)[n] = i;
282                                 n++;
283                         }
284                 } else {
285                         /* x{,y...} */
286                         char *ns, *tok;
287
288                         ns = talloc_strdup(tmp_ctx, nodestring);
289                         tok = strtok(ns, ",");
290                         while (tok != NULL) {
291                                 uint32_t pnn;
292                                 char *endptr;
293                                 i = (uint32_t)strtoul(tok, &endptr, 0);
294                                 if (i == 0 && tok == endptr) {
295                                         DEBUG(DEBUG_ERR,
296                                               ("Invalid node %s\n", tok));
297                                         talloc_free(tmp_ctx);
298                                         exit(ERR_NONODE);
299                                 }
300                                 if (i >= nodemap->num) {
301                                         DEBUG(DEBUG_ERR, ("Node %u does not exist\n", i));
302                                         talloc_free(tmp_ctx);
303                                         exit(ERR_NONODE);
304                                 }
305                                 if ((nodemap->nodes[i].flags & 
306                                      (NODE_FLAGS_DISCONNECTED |
307                                       NODE_FLAGS_DELETED)) && !dd_ok) {
308                                         DEBUG(DEBUG_ERR, ("Node %u has status %s\n", i, pretty_print_flags(nodemap->nodes[i].flags)));
309                                         talloc_free(tmp_ctx);
310                                         exit(ERR_DISNODE);
311                                 }
312                                 if ((pnn = ctdb_ctrl_getpnn(ctdb, TIMELIMIT(), i)) < 0) {
313                                         DEBUG(DEBUG_ERR, ("Can not access node %u. Node is not operational.\n", i));
314                                         talloc_free(tmp_ctx);
315                                         exit(10);
316                                 }
317
318                                 *nodes = talloc_realloc(mem_ctx, *nodes,
319                                                         uint32_t, n+1);
320                                 if (*nodes == NULL) {
321                                         goto failed;
322                                 }
323
324                                 (*nodes)[n] = i;
325                                 n++;
326
327                                 tok = strtok(NULL, ",");
328                         }
329                         talloc_free(ns);
330
331                         if (n == 1) {
332                                 *pnn_mode = (*nodes)[0];
333                         } else {
334                                 *pnn_mode = CTDB_MULTICAST;
335                         }
336                 }
337         } else {
338                 /* default - no nodes specified */
339                 *nodes = talloc_array(mem_ctx, uint32_t, 1);
340                 if (*nodes == NULL) {
341                         goto failed;
342                 }
343                 *pnn_mode = CTDB_CURRENT_NODE;
344
345                 if (((*nodes)[0] = ctdb_ctrl_getpnn(ctdb, TIMELIMIT(), current_pnn)) < 0) {
346                         goto failed;
347                 }
348         }
349
350         talloc_free(tmp_ctx);
351         return true;
352
353 failed:
354         talloc_free(tmp_ctx);
355         return false;
356 }
357
358 /*
359  check if a database exists
360 */
361 static bool db_exists(struct ctdb_context *ctdb, const char *dbarg,
362                       uint32_t *dbid, const char **dbname, uint8_t *flags)
363 {
364         int i, ret;
365         struct ctdb_dbid_map_old *dbmap=NULL;
366         bool dbid_given = false, found = false;
367         uint32_t id;
368         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
369         const char *name = NULL;
370
371         ret = ctdb_ctrl_getdbmap(ctdb, TIMELIMIT(), options.pnn, tmp_ctx, &dbmap);
372         if (ret != 0) {
373                 DEBUG(DEBUG_ERR, ("Unable to get dbids from node %u\n", options.pnn));
374                 goto fail;
375         }
376
377         if (strncmp(dbarg, "0x", 2) == 0) {
378                 id = strtoul(dbarg, NULL, 0);
379                 dbid_given = true;
380         }
381
382         for(i=0; i<dbmap->num; i++) {
383                 if (dbid_given) {
384                         if (id == dbmap->dbs[i].db_id) {
385                                 found = true;
386                                 break;
387                         }
388                 } else {
389                         ret = ctdb_ctrl_getdbname(ctdb, TIMELIMIT(), options.pnn, dbmap->dbs[i].db_id, tmp_ctx, &name);
390                         if (ret != 0) {
391                                 DEBUG(DEBUG_ERR, ("Unable to get dbname from dbid %u\n", dbmap->dbs[i].db_id));
392                                 goto fail;
393                         }
394
395                         if (strcmp(name, dbarg) == 0) {
396                                 id = dbmap->dbs[i].db_id;
397                                 found = true;
398                                 break;
399                         }
400                 }
401         }
402
403         if (found && dbid_given && dbname != NULL) {
404                 ret = ctdb_ctrl_getdbname(ctdb, TIMELIMIT(), options.pnn, dbmap->dbs[i].db_id, tmp_ctx, &name);
405                 if (ret != 0) {
406                         DEBUG(DEBUG_ERR, ("Unable to get dbname from dbid %u\n", dbmap->dbs[i].db_id));
407                         found = false;
408                         goto fail;
409                 }
410         }
411
412         if (found) {
413                 if (dbid) *dbid = id;
414                 if (dbname) *dbname = talloc_strdup(ctdb, name);
415                 if (flags) *flags = dbmap->dbs[i].flags;
416         } else {
417                 DEBUG(DEBUG_ERR,("No database matching '%s' found\n", dbarg));
418         }
419
420 fail:
421         talloc_free(tmp_ctx);
422         return found;
423 }
424
425 /*
426   see if a process exists
427  */
428 static int control_process_exists(struct ctdb_context *ctdb, int argc, const char **argv)
429 {
430         uint32_t pnn, pid;
431         int ret;
432         if (argc < 1) {
433                 usage();
434         }
435
436         if (sscanf(argv[0], "%u:%u", &pnn, &pid) != 2) {
437                 DEBUG(DEBUG_ERR, ("Badly formed pnn:pid\n"));
438                 return -1;
439         }
440
441         ret = ctdb_ctrl_process_exists(ctdb, pnn, pid);
442         if (ret == 0) {
443                 printf("%u:%u exists\n", pnn, pid);
444         } else {
445                 printf("%u:%u does not exist\n", pnn, pid);
446         }
447         return ret;
448 }
449
450 /*
451   display statistics structure
452  */
453 static void show_statistics(struct ctdb_statistics *s, int show_header)
454 {
455         TALLOC_CTX *tmp_ctx = talloc_new(NULL);
456         int i;
457         const char *prefix=NULL;
458         int preflen=0;
459         int tmp, days, hours, minutes, seconds;
460         const struct {
461                 const char *name;
462                 uint32_t offset;
463         } fields[] = {
464 #define STATISTICS_FIELD(n) { #n, offsetof(struct ctdb_statistics, n) }
465                 STATISTICS_FIELD(num_clients),
466                 STATISTICS_FIELD(frozen),
467                 STATISTICS_FIELD(recovering),
468                 STATISTICS_FIELD(num_recoveries),
469                 STATISTICS_FIELD(client_packets_sent),
470                 STATISTICS_FIELD(client_packets_recv),
471                 STATISTICS_FIELD(node_packets_sent),
472                 STATISTICS_FIELD(node_packets_recv),
473                 STATISTICS_FIELD(keepalive_packets_sent),
474                 STATISTICS_FIELD(keepalive_packets_recv),
475                 STATISTICS_FIELD(node.req_call),
476                 STATISTICS_FIELD(node.reply_call),
477                 STATISTICS_FIELD(node.req_dmaster),
478                 STATISTICS_FIELD(node.reply_dmaster),
479                 STATISTICS_FIELD(node.reply_error),
480                 STATISTICS_FIELD(node.req_message),
481                 STATISTICS_FIELD(node.req_control),
482                 STATISTICS_FIELD(node.reply_control),
483                 STATISTICS_FIELD(client.req_call),
484                 STATISTICS_FIELD(client.req_message),
485                 STATISTICS_FIELD(client.req_control),
486                 STATISTICS_FIELD(timeouts.call),
487                 STATISTICS_FIELD(timeouts.control),
488                 STATISTICS_FIELD(timeouts.traverse),
489                 STATISTICS_FIELD(locks.num_calls),
490                 STATISTICS_FIELD(locks.num_current),
491                 STATISTICS_FIELD(locks.num_pending),
492                 STATISTICS_FIELD(locks.num_failed),
493                 STATISTICS_FIELD(total_calls),
494                 STATISTICS_FIELD(pending_calls),
495                 STATISTICS_FIELD(childwrite_calls),
496                 STATISTICS_FIELD(pending_childwrite_calls),
497                 STATISTICS_FIELD(memory_used),
498                 STATISTICS_FIELD(max_hop_count),
499                 STATISTICS_FIELD(total_ro_delegations),
500                 STATISTICS_FIELD(total_ro_revokes),
501         };
502         
503         tmp = s->statistics_current_time.tv_sec - s->statistics_start_time.tv_sec;
504         seconds = tmp%60;
505         tmp    /= 60;
506         minutes = tmp%60;
507         tmp    /= 60;
508         hours   = tmp%24;
509         tmp    /= 24;
510         days    = tmp;
511
512         if (options.machinereadable){
513                 if (show_header) {
514                         printm("CTDB version:");
515                         printm("Current time of statistics:");
516                         printm("Statistics collected since:");
517                         for (i=0;i<ARRAY_SIZE(fields);i++) {
518                                 printm("%s:", fields[i].name);
519                         }
520                         printm("num_reclock_ctdbd_latency:");
521                         printm("min_reclock_ctdbd_latency:");
522                         printm("avg_reclock_ctdbd_latency:");
523                         printm("max_reclock_ctdbd_latency:");
524
525                         printm("num_reclock_recd_latency:");
526                         printm("min_reclock_recd_latency:");
527                         printm("avg_reclock_recd_latency:");
528                         printm("max_reclock_recd_latency:");
529
530                         printm("num_call_latency:");
531                         printm("min_call_latency:");
532                         printm("avg_call_latency:");
533                         printm("max_call_latency:");
534
535                         printm("num_lockwait_latency:");
536                         printm("min_lockwait_latency:");
537                         printm("avg_lockwait_latency:");
538                         printm("max_lockwait_latency:");
539
540                         printm("num_childwrite_latency:");
541                         printm("min_childwrite_latency:");
542                         printm("avg_childwrite_latency:");
543                         printm("max_childwrite_latency:");
544                         printm("\n");
545                 }
546                 printm("%d:", CTDB_PROTOCOL);
547                 printm("%d:", (int)s->statistics_current_time.tv_sec);
548                 printm("%d:", (int)s->statistics_start_time.tv_sec);
549                 for (i=0;i<ARRAY_SIZE(fields);i++) {
550                         printm("%d:", *(uint32_t *)(fields[i].offset+(uint8_t *)s));
551                 }
552                 printm("%d:", s->reclock.ctdbd.num);
553                 printm("%.6f:", s->reclock.ctdbd.min);
554                 printm("%.6f:", s->reclock.ctdbd.num?s->reclock.ctdbd.total/s->reclock.ctdbd.num:0.0);
555                 printm("%.6f:", s->reclock.ctdbd.max);
556
557                 printm("%d:", s->reclock.recd.num);
558                 printm("%.6f:", s->reclock.recd.min);
559                 printm("%.6f:", s->reclock.recd.num?s->reclock.recd.total/s->reclock.recd.num:0.0);
560                 printm("%.6f:", s->reclock.recd.max);
561
562                 printm("%d:", s->call_latency.num);
563                 printm("%.6f:", s->call_latency.min);
564                 printm("%.6f:", s->call_latency.num?s->call_latency.total/s->call_latency.num:0.0);
565                 printm("%.6f:", s->call_latency.max);
566
567                 printm("%d:", s->childwrite_latency.num);
568                 printm("%.6f:", s->childwrite_latency.min);
569                 printm("%.6f:", s->childwrite_latency.num?s->childwrite_latency.total/s->childwrite_latency.num:0.0);
570                 printm("%.6f:", s->childwrite_latency.max);
571                 printm("\n");
572         } else {
573                 printf("CTDB version %u\n", CTDB_PROTOCOL);
574                 printf("Current time of statistics  :                %s", ctime(&s->statistics_current_time.tv_sec));
575                 printf("Statistics collected since  : (%03d %02d:%02d:%02d) %s", days, hours, minutes, seconds, ctime(&s->statistics_start_time.tv_sec));
576
577                 for (i=0;i<ARRAY_SIZE(fields);i++) {
578                         if (strchr(fields[i].name, '.')) {
579                                 preflen = strcspn(fields[i].name, ".")+1;
580                                 if (!prefix || strncmp(prefix, fields[i].name, preflen) != 0) {
581                                         prefix = fields[i].name;
582                                         printf(" %*.*s\n", preflen-1, preflen-1, fields[i].name);
583                                 }
584                         } else {
585                                 preflen = 0;
586                         }
587                         printf(" %*s%-22s%*s%10u\n", 
588                                preflen?4:0, "",
589                                fields[i].name+preflen, 
590                                preflen?0:4, "",
591                                *(uint32_t *)(fields[i].offset+(uint8_t *)s));
592                 }
593                 printf(" hop_count_buckets:");
594                 for (i=0;i<MAX_COUNT_BUCKETS;i++) {
595                         printf(" %d", s->hop_count_bucket[i]);
596                 }
597                 printf("\n");
598                 printf(" lock_buckets:");
599                 for (i=0; i<MAX_COUNT_BUCKETS; i++) {
600                         printf(" %d", s->locks.buckets[i]);
601                 }
602                 printf("\n");
603                 printf(" %-30s     %.6f/%.6f/%.6f sec out of %d\n", "locks_latency      MIN/AVG/MAX", s->locks.latency.min, s->locks.latency.num?s->locks.latency.total/s->locks.latency.num:0.0, s->locks.latency.max, s->locks.latency.num);
604
605                 printf(" %-30s     %.6f/%.6f/%.6f sec out of %d\n", "reclock_ctdbd      MIN/AVG/MAX", s->reclock.ctdbd.min, s->reclock.ctdbd.num?s->reclock.ctdbd.total/s->reclock.ctdbd.num:0.0, s->reclock.ctdbd.max, s->reclock.ctdbd.num);
606
607                 printf(" %-30s     %.6f/%.6f/%.6f sec out of %d\n", "reclock_recd       MIN/AVG/MAX", s->reclock.recd.min, s->reclock.recd.num?s->reclock.recd.total/s->reclock.recd.num:0.0, s->reclock.recd.max, s->reclock.recd.num);
608
609                 printf(" %-30s     %.6f/%.6f/%.6f sec out of %d\n", "call_latency       MIN/AVG/MAX", s->call_latency.min, s->call_latency.num?s->call_latency.total/s->call_latency.num:0.0, s->call_latency.max, s->call_latency.num);
610                 printf(" %-30s     %.6f/%.6f/%.6f sec out of %d\n", "childwrite_latency MIN/AVG/MAX", s->childwrite_latency.min, s->childwrite_latency.num?s->childwrite_latency.total/s->childwrite_latency.num:0.0, s->childwrite_latency.max, s->childwrite_latency.num);
611         }
612
613         talloc_free(tmp_ctx);
614 }
615
616 /*
617   display remote ctdb statistics combined from all nodes
618  */
619 static int control_statistics_all(struct ctdb_context *ctdb)
620 {
621         int ret, i;
622         struct ctdb_statistics statistics;
623         uint32_t *nodes;
624         uint32_t num_nodes;
625
626         nodes = ctdb_get_connected_nodes(ctdb, TIMELIMIT(), ctdb, &num_nodes);
627         CTDB_NO_MEMORY(ctdb, nodes);
628         
629         ZERO_STRUCT(statistics);
630
631         for (i=0;i<num_nodes;i++) {
632                 struct ctdb_statistics s1;
633                 int j;
634                 uint32_t *v1 = (uint32_t *)&s1;
635                 uint32_t *v2 = (uint32_t *)&statistics;
636                 uint32_t num_ints = 
637                         offsetof(struct ctdb_statistics, __last_counter) / sizeof(uint32_t);
638                 ret = ctdb_ctrl_statistics(ctdb, nodes[i], &s1);
639                 if (ret != 0) {
640                         DEBUG(DEBUG_ERR, ("Unable to get statistics from node %u\n", nodes[i]));
641                         return ret;
642                 }
643                 for (j=0;j<num_ints;j++) {
644                         v2[j] += v1[j];
645                 }
646                 statistics.max_hop_count = 
647                         MAX(statistics.max_hop_count, s1.max_hop_count);
648                 statistics.call_latency.max = 
649                         MAX(statistics.call_latency.max, s1.call_latency.max);
650         }
651         talloc_free(nodes);
652         printf("Gathered statistics for %u nodes\n", num_nodes);
653         show_statistics(&statistics, 1);
654         return 0;
655 }
656
657 /*
658   display remote ctdb statistics
659  */
660 static int control_statistics(struct ctdb_context *ctdb, int argc, const char **argv)
661 {
662         int ret;
663         struct ctdb_statistics statistics;
664
665         if (options.pnn == CTDB_BROADCAST_ALL) {
666                 return control_statistics_all(ctdb);
667         }
668
669         ret = ctdb_ctrl_statistics(ctdb, options.pnn, &statistics);
670         if (ret != 0) {
671                 DEBUG(DEBUG_ERR, ("Unable to get statistics from node %u\n", options.pnn));
672                 return ret;
673         }
674         show_statistics(&statistics, 1);
675         return 0;
676 }
677
678
679 /*
680   reset remote ctdb statistics
681  */
682 static int control_statistics_reset(struct ctdb_context *ctdb, int argc, const char **argv)
683 {
684         int ret;
685
686         ret = ctdb_statistics_reset(ctdb, options.pnn);
687         if (ret != 0) {
688                 DEBUG(DEBUG_ERR, ("Unable to reset statistics on node %u\n", options.pnn));
689                 return ret;
690         }
691         return 0;
692 }
693
694
695 /*
696   display remote ctdb rolling statistics
697  */
698 static int control_stats(struct ctdb_context *ctdb, int argc, const char **argv)
699 {
700         int ret;
701         struct ctdb_statistics_list_old *stats;
702         int i, num_records = -1;
703
704         assert_single_node_only();
705
706         if (argc ==1) {
707                 num_records = atoi(argv[0]) - 1;
708         }
709
710         ret = ctdb_ctrl_getstathistory(ctdb, TIMELIMIT(), options.pnn, ctdb, &stats);
711         if (ret != 0) {
712                 DEBUG(DEBUG_ERR, ("Unable to get rolling statistics from node %u\n", options.pnn));
713                 return ret;
714         }
715         for (i=0;i<stats->num;i++) {
716                 if (stats->stats[i].statistics_start_time.tv_sec == 0) {
717                         continue;
718                 }
719                 show_statistics(&stats->stats[i], i==0);
720                 if (i == num_records) {
721                         break;
722                 }
723         }
724         return 0;
725 }
726
727
728 /*
729   display remote ctdb db statistics
730  */
731 static int control_dbstatistics(struct ctdb_context *ctdb, int argc, const char **argv)
732 {
733         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
734         struct ctdb_db_statistics_old *dbstat;
735         int i;
736         uint32_t db_id;
737         int num_hot_keys;
738         int ret;
739
740         if (argc < 1) {
741                 usage();
742         }
743
744         if (!db_exists(ctdb, argv[0], &db_id, NULL, NULL)) {
745                 return -1;
746         }
747
748         ret = ctdb_ctrl_dbstatistics(ctdb, options.pnn, db_id, tmp_ctx, &dbstat);
749         if (ret != 0) {
750                 DEBUG(DEBUG_ERR,("Failed to read db statistics from node\n"));
751                 talloc_free(tmp_ctx);
752                 return -1;
753         }
754
755         printf("DB Statistics: %s\n", argv[0]);
756         printf(" %*s%-22s%*s%10u\n", 0, "", "ro_delegations", 4, "",
757                 dbstat->db_ro_delegations);
758         printf(" %*s%-22s%*s%10u\n", 0, "", "ro_revokes", 4, "",
759                 dbstat->db_ro_delegations);
760         printf(" %s\n", "locks");
761         printf(" %*s%-22s%*s%10u\n", 4, "", "total", 0, "",
762                 dbstat->locks.num_calls);
763         printf(" %*s%-22s%*s%10u\n", 4, "", "failed", 0, "",
764                 dbstat->locks.num_failed);
765         printf(" %*s%-22s%*s%10u\n", 4, "", "current", 0, "",
766                 dbstat->locks.num_current);
767         printf(" %*s%-22s%*s%10u\n", 4, "", "pending", 0, "",
768                 dbstat->locks.num_pending);
769         printf(" %s", "hop_count_buckets:");
770         for (i=0; i<MAX_COUNT_BUCKETS; i++) {
771                 printf(" %d", dbstat->hop_count_bucket[i]);
772         }
773         printf("\n");
774         printf(" %s", "lock_buckets:");
775         for (i=0; i<MAX_COUNT_BUCKETS; i++) {
776                 printf(" %d", dbstat->locks.buckets[i]);
777         }
778         printf("\n");
779         printf(" %-30s     %.6f/%.6f/%.6f sec out of %d\n",
780                 "locks_latency      MIN/AVG/MAX",
781                 dbstat->locks.latency.min,
782                 (dbstat->locks.latency.num ?
783                  dbstat->locks.latency.total /dbstat->locks.latency.num :
784                  0.0),
785                 dbstat->locks.latency.max,
786                 dbstat->locks.latency.num);
787         printf(" %-30s     %.6f/%.6f/%.6f sec out of %d\n",
788                 "vacuum_latency     MIN/AVG/MAX",
789                 dbstat->vacuum.latency.min,
790                 (dbstat->vacuum.latency.num ?
791                  dbstat->vacuum.latency.total /dbstat->vacuum.latency.num :
792                  0.0),
793                 dbstat->vacuum.latency.max,
794                 dbstat->vacuum.latency.num);
795         num_hot_keys = 0;
796         for (i=0; i<dbstat->num_hot_keys; i++) {
797                 if (dbstat->hot_keys[i].count > 0) {
798                         num_hot_keys++;
799                 }
800         }
801         dbstat->num_hot_keys = num_hot_keys;
802
803         printf(" Num Hot Keys:     %d\n", dbstat->num_hot_keys);
804         for (i = 0; i < dbstat->num_hot_keys; i++) {
805                 int j;
806                 printf("     Count:%d Key:", dbstat->hot_keys[i].count);
807                 for (j = 0; j < dbstat->hot_keys[i].key.dsize; j++) {
808                         printf("%02x", dbstat->hot_keys[i].key.dptr[j]&0xff);
809                 }
810                 printf("\n");
811         }
812
813         talloc_free(tmp_ctx);
814         return 0;
815 }
816
817 /*
818   display uptime of remote node
819  */
820 static int control_uptime(struct ctdb_context *ctdb, int argc, const char **argv)
821 {
822         int ret;
823         struct ctdb_uptime *uptime = NULL;
824         int tmp, days, hours, minutes, seconds;
825
826         ret = ctdb_ctrl_uptime(ctdb, ctdb, TIMELIMIT(), options.pnn, &uptime);
827         if (ret != 0) {
828                 DEBUG(DEBUG_ERR, ("Unable to get uptime from node %u\n", options.pnn));
829                 return ret;
830         }
831
832         if (options.machinereadable){
833                 printm(":Current Node Time:Ctdb Start Time:Last Recovery/Failover Time:Last Recovery/IPFailover Duration:\n");
834                 printm(":%u:%u:%u:%lf\n",
835                         (unsigned int)uptime->current_time.tv_sec,
836                         (unsigned int)uptime->ctdbd_start_time.tv_sec,
837                         (unsigned int)uptime->last_recovery_finished.tv_sec,
838                         timeval_delta(&uptime->last_recovery_finished,
839                                       &uptime->last_recovery_started)
840                 );
841                 return 0;
842         }
843
844         printf("Current time of node          :                %s", ctime(&uptime->current_time.tv_sec));
845
846         tmp = uptime->current_time.tv_sec - uptime->ctdbd_start_time.tv_sec;
847         seconds = tmp%60;
848         tmp    /= 60;
849         minutes = tmp%60;
850         tmp    /= 60;
851         hours   = tmp%24;
852         tmp    /= 24;
853         days    = tmp;
854         printf("Ctdbd start time              : (%03d %02d:%02d:%02d) %s", days, hours, minutes, seconds, ctime(&uptime->ctdbd_start_time.tv_sec));
855
856         tmp = uptime->current_time.tv_sec - uptime->last_recovery_finished.tv_sec;
857         seconds = tmp%60;
858         tmp    /= 60;
859         minutes = tmp%60;
860         tmp    /= 60;
861         hours   = tmp%24;
862         tmp    /= 24;
863         days    = tmp;
864         printf("Time of last recovery/failover: (%03d %02d:%02d:%02d) %s", days, hours, minutes, seconds, ctime(&uptime->last_recovery_finished.tv_sec));
865         
866         printf("Duration of last recovery/failover: %lf seconds\n",
867                 timeval_delta(&uptime->last_recovery_finished,
868                               &uptime->last_recovery_started));
869
870         return 0;
871 }
872
873 /*
874   show the PNN of the current node
875  */
876 static int control_pnn(struct ctdb_context *ctdb, int argc, const char **argv)
877 {
878         uint32_t mypnn;
879
880         mypnn = getpnn(ctdb);
881
882         printf("PNN:%d\n", mypnn);
883         return 0;
884 }
885
886
887 static struct ctdb_node_map_old *read_nodes_file(TALLOC_CTX *mem_ctx)
888 {
889         const char *nodes_list;
890
891         /* read the nodes file */
892         nodes_list = getenv("CTDB_NODES");
893         if (nodes_list == NULL) {
894                 nodes_list = talloc_asprintf(mem_ctx, "%s/nodes",
895                                              getenv("CTDB_BASE"));
896                 if (nodes_list == NULL) {
897                         DEBUG(DEBUG_ALERT,(__location__ " Out of memory\n"));
898                         exit(1);
899                 }
900         }
901
902         return ctdb_read_nodes_file(mem_ctx, nodes_list);
903 }
904
905 /*
906   show the PNN of the current node
907   discover the pnn by loading the nodes file and try to bind to all
908   addresses one at a time until the ip address is found.
909  */
910 static int find_node_xpnn(void)
911 {
912         TALLOC_CTX *mem_ctx = talloc_new(NULL);
913         struct ctdb_node_map_old *node_map;
914         int i, pnn;
915
916         node_map = read_nodes_file(mem_ctx);
917         if (node_map == NULL) {
918                 talloc_free(mem_ctx);
919                 return -1;
920         }
921
922         for (i = 0; i < node_map->num; i++) {
923                 if (node_map->nodes[i].flags & NODE_FLAGS_DELETED) {
924                         continue;
925                 }
926                 if (ctdb_sys_have_ip(&node_map->nodes[i].addr)) {
927                         pnn = node_map->nodes[i].pnn;
928                         talloc_free(mem_ctx);
929                         return pnn;
930                 }
931         }
932
933         printf("Failed to detect which PNN this node is\n");
934         talloc_free(mem_ctx);
935         return -1;
936 }
937
938 static int control_xpnn(struct ctdb_context *ctdb, int argc, const char **argv)
939 {
940         uint32_t pnn;
941
942         assert_single_node_only();
943
944         pnn = find_node_xpnn();
945         if (pnn == -1) {
946                 return -1;
947         }
948
949         printf("PNN:%d\n", pnn);
950         return 0;
951 }
952
953 /* Helpers for ctdb status
954  */
955 static bool is_partially_online(struct ctdb_context *ctdb, struct ctdb_node_and_flags *node)
956 {
957         TALLOC_CTX *tmp_ctx = talloc_new(NULL);
958         int j;
959         bool ret = false;
960
961         if (node->flags == 0) {
962                 struct ctdb_iface_list_old *ifaces;
963
964                 if (ctdb_ctrl_get_ifaces(ctdb, TIMELIMIT(), node->pnn,
965                                          tmp_ctx, &ifaces) == 0) {
966                         for (j=0; j < ifaces->num; j++) {
967                                 if (ifaces->ifaces[j].link_state != 0) {
968                                         continue;
969                                 }
970                                 ret = true;
971                                 break;
972                         }
973                 }
974         }
975         talloc_free(tmp_ctx);
976
977         return ret;
978 }
979
980 static void control_status_header_machine(void)
981 {
982         printm(":Node:IP:Disconnected:Banned:Disabled:Unhealthy:Stopped"
983                ":Inactive:PartiallyOnline:ThisNode:\n");
984 }
985
986 static int control_status_1_machine(struct ctdb_context *ctdb, int mypnn,
987                                     struct ctdb_node_and_flags *node)
988 {
989         printm(":%d:%s:%d:%d:%d:%d:%d:%d:%d:%c:\n", node->pnn,
990                ctdb_addr_to_str(&node->addr),
991                !!(node->flags&NODE_FLAGS_DISCONNECTED),
992                !!(node->flags&NODE_FLAGS_BANNED),
993                !!(node->flags&NODE_FLAGS_PERMANENTLY_DISABLED),
994                !!(node->flags&NODE_FLAGS_UNHEALTHY),
995                !!(node->flags&NODE_FLAGS_STOPPED),
996                !!(node->flags&NODE_FLAGS_INACTIVE),
997                is_partially_online(ctdb, node) ? 1 : 0,
998                (node->pnn == mypnn)?'Y':'N');
999
1000         return node->flags;
1001 }
1002
1003 static int control_status_1_human(struct ctdb_context *ctdb, int mypnn,
1004                                   struct ctdb_node_and_flags *node)
1005 {
1006        printf("pnn:%d %-16s %s%s\n", node->pnn,
1007               ctdb_addr_to_str(&node->addr),
1008               is_partially_online(ctdb, node) ? "PARTIALLYONLINE" : pretty_print_flags(node->flags),
1009               node->pnn == mypnn?" (THIS NODE)":"");
1010
1011        return node->flags;
1012 }
1013
1014 /*
1015   display remote ctdb status
1016  */
1017 static int control_status(struct ctdb_context *ctdb, int argc, const char **argv)
1018 {
1019         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
1020         int i;
1021         struct ctdb_vnn_map *vnnmap=NULL;
1022         struct ctdb_node_map_old *nodemap=NULL;
1023         uint32_t recmode, recmaster, mypnn;
1024         int num_deleted_nodes = 0;
1025         int ret;
1026
1027         mypnn = getpnn(ctdb);
1028
1029         ret = ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), options.pnn, tmp_ctx, &nodemap);
1030         if (ret != 0) {
1031                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from node %u\n", options.pnn));
1032                 talloc_free(tmp_ctx);
1033                 return -1;
1034         }
1035
1036         if (options.machinereadable) {
1037                 control_status_header_machine();
1038                 for (i=0;i<nodemap->num;i++) {
1039                         if (nodemap->nodes[i].flags & NODE_FLAGS_DELETED) {
1040                                 continue;
1041                         }
1042                         (void) control_status_1_machine(ctdb, mypnn,
1043                                                         &nodemap->nodes[i]);
1044                 }
1045                 talloc_free(tmp_ctx);
1046                 return 0;
1047         }
1048
1049         for (i=0; i<nodemap->num; i++) {
1050                 if (nodemap->nodes[i].flags & NODE_FLAGS_DELETED) {
1051                         num_deleted_nodes++;
1052                 }
1053         }
1054         if (num_deleted_nodes == 0) {
1055                 printf("Number of nodes:%d\n", nodemap->num);
1056         } else {
1057                 printf("Number of nodes:%d (including %d deleted nodes)\n",
1058                        nodemap->num, num_deleted_nodes);
1059         }
1060         for(i=0;i<nodemap->num;i++){
1061                 if (nodemap->nodes[i].flags & NODE_FLAGS_DELETED) {
1062                         continue;
1063                 }
1064                 (void) control_status_1_human(ctdb, mypnn, &nodemap->nodes[i]);
1065         }
1066
1067         ret = ctdb_ctrl_getvnnmap(ctdb, TIMELIMIT(), options.pnn, tmp_ctx, &vnnmap);
1068         if (ret != 0) {
1069                 DEBUG(DEBUG_ERR, ("Unable to get vnnmap from node %u\n", options.pnn));
1070                 talloc_free(tmp_ctx);
1071                 return -1;
1072         }
1073         if (vnnmap->generation == INVALID_GENERATION) {
1074                 printf("Generation:INVALID\n");
1075         } else {
1076                 printf("Generation:%d\n",vnnmap->generation);
1077         }
1078         printf("Size:%d\n",vnnmap->size);
1079         for(i=0;i<vnnmap->size;i++){
1080                 printf("hash:%d lmaster:%d\n", i, vnnmap->map[i]);
1081         }
1082
1083         ret = ctdb_ctrl_getrecmode(ctdb, tmp_ctx, TIMELIMIT(), options.pnn, &recmode);
1084         if (ret != 0) {
1085                 DEBUG(DEBUG_ERR, ("Unable to get recmode from node %u\n", options.pnn));
1086                 talloc_free(tmp_ctx);
1087                 return -1;
1088         }
1089         printf("Recovery mode:%s (%d)\n",recmode==CTDB_RECOVERY_NORMAL?"NORMAL":"RECOVERY",recmode);
1090
1091         ret = ctdb_ctrl_getrecmaster(ctdb, tmp_ctx, TIMELIMIT(), options.pnn, &recmaster);
1092         if (ret != 0) {
1093                 DEBUG(DEBUG_ERR, ("Unable to get recmaster from node %u\n", options.pnn));
1094                 talloc_free(tmp_ctx);
1095                 return -1;
1096         }
1097         printf("Recovery master:%d\n",recmaster);
1098
1099         talloc_free(tmp_ctx);
1100         return 0;
1101 }
1102
1103 static int control_nodestatus(struct ctdb_context *ctdb, int argc, const char **argv)
1104 {
1105         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
1106         int i, ret;
1107         struct ctdb_node_map_old *nodemap=NULL;
1108         uint32_t * nodes;
1109         uint32_t pnn_mode, mypnn;
1110
1111         if (argc > 1) {
1112                 usage();
1113         }
1114
1115         if (!parse_nodestring(ctdb, tmp_ctx, argc == 1 ? argv[0] : NULL,
1116                               options.pnn, true, &nodes, &pnn_mode)) {
1117                 return -1;
1118         }
1119
1120         if (options.machinereadable) {
1121                 control_status_header_machine();
1122         } else if (pnn_mode == CTDB_BROADCAST_ALL) {
1123                 printf("Number of nodes:%d\n", (int) talloc_array_length(nodes));
1124         }
1125
1126         mypnn = getpnn(ctdb);
1127
1128         ret = ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), options.pnn, tmp_ctx, &nodemap);
1129         if (ret != 0) {
1130                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from node %u\n", options.pnn));
1131                 talloc_free(tmp_ctx);
1132                 return -1;
1133         }
1134
1135         ret = 0;
1136
1137         for (i = 0; i < talloc_array_length(nodes); i++) {
1138                 if (options.machinereadable) {
1139                         ret |= control_status_1_machine(ctdb, mypnn,
1140                                                         &nodemap->nodes[nodes[i]]);
1141                 } else {
1142                         ret |= control_status_1_human(ctdb, mypnn,
1143                                                       &nodemap->nodes[nodes[i]]);
1144                 }
1145         }
1146
1147         talloc_free(tmp_ctx);
1148         return ret;
1149 }
1150
1151 /* talloc off the existing nodemap... */
1152 static struct ctdb_node_map_old *talloc_nodemap(struct ctdb_node_map_old *nodemap)
1153 {
1154         return talloc_zero_size(nodemap,
1155                                 offsetof(struct ctdb_node_map_old, nodes) +
1156                                 nodemap->num * sizeof(struct ctdb_node_and_flags));
1157 }
1158
1159 static struct ctdb_node_map_old *
1160 filter_nodemap_by_capabilities(struct ctdb_context *ctdb,
1161                                struct ctdb_node_map_old *nodemap,
1162                                uint32_t required_capabilities,
1163                                bool first_only)
1164 {
1165         int i;
1166         uint32_t capabilities;
1167         struct ctdb_node_map_old *ret;
1168
1169         ret = talloc_nodemap(nodemap);
1170         CTDB_NO_MEMORY_NULL(ctdb, ret);
1171
1172         ret->num = 0;
1173
1174         for (i = 0; i < nodemap->num; i++) {
1175                 int res;
1176
1177                 /* Disconnected nodes have no capabilities! */
1178                 if (nodemap->nodes[i].flags & NODE_FLAGS_DISCONNECTED) {
1179                         continue;
1180                 }
1181
1182                 res = ctdb_ctrl_getcapabilities(ctdb, TIMELIMIT(),
1183                                                 nodemap->nodes[i].pnn,
1184                                                 &capabilities);
1185                 if (res != 0) {
1186                         DEBUG(DEBUG_ERR, ("Unable to get capabilities from node %u\n",
1187                                           nodemap->nodes[i].pnn));
1188                         talloc_free(ret);
1189                         return NULL;
1190                 }
1191                 if (!(capabilities & required_capabilities)) {
1192                         continue;
1193                 }
1194
1195                 ret->nodes[ret->num] = nodemap->nodes[i];
1196                 ret->num++;
1197                 if (first_only) {
1198                         break;
1199                 }
1200         }
1201
1202         return ret;
1203 }
1204
1205 static struct ctdb_node_map_old *
1206 filter_nodemap_by_flags(struct ctdb_context *ctdb,
1207                         struct ctdb_node_map_old *nodemap,
1208                         uint32_t flags_mask)
1209 {
1210         int i;
1211         struct ctdb_node_map_old *ret;
1212
1213         ret = talloc_nodemap(nodemap);
1214         CTDB_NO_MEMORY_NULL(ctdb, ret);
1215
1216         ret->num = 0;
1217
1218         for (i = 0; i < nodemap->num; i++) {
1219                 if (nodemap->nodes[i].flags & flags_mask) {
1220                         continue;
1221                 }
1222
1223                 ret->nodes[ret->num] = nodemap->nodes[i];
1224                 ret->num++;
1225         }
1226
1227         return ret;
1228 }
1229
1230 /*
1231   display the list of nodes belonging to this natgw configuration
1232  */
1233 static int control_natgwlist(struct ctdb_context *ctdb, int argc, const char **argv)
1234 {
1235         static char prog[PATH_MAX+1] = "";
1236
1237         if (argc != 0) {
1238                 usage();
1239         }
1240
1241         if (!ctdb_set_helper("NAT gateway helper", prog, sizeof(prog),
1242                              "CTDB_NATGW_HELPER", CTDB_HELPER_BINDIR,
1243                              "ctdb_natgw")) {
1244                 DEBUG(DEBUG_ERR, ("Unable to set NAT gateway helper\n"));
1245                 exit(1);
1246         }
1247
1248         execl(prog, prog, "natgwlist", NULL);
1249
1250         DEBUG(DEBUG_ERR,
1251               ("Unable to run NAT gateway helper %s\n", strerror(errno)));
1252         exit(1);
1253 }
1254
1255 /*
1256   display the status of the scripts for monitoring (or other events)
1257  */
1258 static int control_one_scriptstatus(struct ctdb_context *ctdb,
1259                                     enum ctdb_event type)
1260 {
1261         struct ctdb_script_list_old *script_status;
1262         int ret, i;
1263
1264         ret = ctdb_ctrl_getscriptstatus(ctdb, TIMELIMIT(), options.pnn, ctdb, type, &script_status);
1265         if (ret != 0) {
1266                 DEBUG(DEBUG_ERR, ("Unable to get script status from node %u\n", options.pnn));
1267                 return ret;
1268         }
1269
1270         if (script_status == NULL) {
1271                 if (!options.machinereadable) {
1272                         printf("%s cycle never run\n",
1273                                ctdb_eventscript_call_names[type]);
1274                 }
1275                 return 0;
1276         }
1277
1278         if (!options.machinereadable) {
1279                 int num_run = 0;
1280                 for (i=0; i<script_status->num_scripts; i++) {
1281                         if (script_status->scripts[i].status != -ENOEXEC) {
1282                                 num_run++;
1283                         }
1284                 }
1285                 printf("%d scripts were executed last %s cycle\n",
1286                        num_run,
1287                        ctdb_eventscript_call_names[type]);
1288         }
1289         for (i=0; i<script_status->num_scripts; i++) {
1290                 const char *status = NULL;
1291
1292                 /* The ETIME status is ignored for certain events.
1293                  * In that case the status is 0, but endtime is not set.
1294                  */
1295                 if (script_status->scripts[i].status == 0 &&
1296                     timeval_is_zero(&script_status->scripts[i].finished)) {
1297                         script_status->scripts[i].status = -ETIME;
1298                 }
1299
1300                 switch (script_status->scripts[i].status) {
1301                 case -ETIME:
1302                         status = "TIMEDOUT";
1303                         break;
1304                 case -ENOEXEC:
1305                         status = "DISABLED";
1306                         break;
1307                 case 0:
1308                         status = "OK";
1309                         break;
1310                 default:
1311                         if (script_status->scripts[i].status > 0)
1312                                 status = "ERROR";
1313                         break;
1314                 }
1315                 if (options.machinereadable) {
1316                         printm(":%s:%s:%i:%s:%lu.%06lu:%lu.%06lu:%s:\n",
1317                                ctdb_eventscript_call_names[type],
1318                                script_status->scripts[i].name,
1319                                script_status->scripts[i].status,
1320                                status,
1321                                (long)script_status->scripts[i].start.tv_sec,
1322                                (long)script_status->scripts[i].start.tv_usec,
1323                                (long)script_status->scripts[i].finished.tv_sec,
1324                                (long)script_status->scripts[i].finished.tv_usec,
1325                                script_status->scripts[i].output);
1326                         continue;
1327                 }
1328                 if (status)
1329                         printf("%-20s Status:%s    ",
1330                                script_status->scripts[i].name, status);
1331                 else
1332                         /* Some other error, eg from stat. */
1333                         printf("%-20s Status:CANNOT RUN (%s)",
1334                                script_status->scripts[i].name,
1335                                strerror(-script_status->scripts[i].status));
1336
1337                 if (script_status->scripts[i].status >= 0) {
1338                         printf("Duration:%.3lf ",
1339                         timeval_delta(&script_status->scripts[i].finished,
1340                               &script_status->scripts[i].start));
1341                 }
1342                 if (script_status->scripts[i].status != -ENOEXEC) {
1343                         printf("%s",
1344                                ctime(&script_status->scripts[i].start.tv_sec));
1345                         if (script_status->scripts[i].status != 0) {
1346                                 printf("   OUTPUT:%s\n",
1347                                        script_status->scripts[i].output);
1348                         }
1349                 } else {
1350                         printf("\n");
1351                 }
1352         }
1353         return 0;
1354 }
1355
1356
1357 static int control_scriptstatus(struct ctdb_context *ctdb,
1358                                 int argc, const char **argv)
1359 {
1360         int ret;
1361         enum ctdb_event type, min, max;
1362         const char *arg;
1363
1364         if (argc > 1) {
1365                 DEBUG(DEBUG_ERR, ("Unknown arguments to scriptstatus\n"));
1366                 return -1;
1367         }
1368
1369         if (argc == 0)
1370                 arg = ctdb_eventscript_call_names[CTDB_EVENT_MONITOR];
1371         else
1372                 arg = argv[0];
1373
1374         for (type = 0; type < CTDB_EVENT_MAX; type++) {
1375                 if (strcmp(arg, ctdb_eventscript_call_names[type]) == 0) {
1376                         min = type;
1377                         max = type+1;
1378                         break;
1379                 }
1380         }
1381         if (type == CTDB_EVENT_MAX) {
1382                 if (strcmp(arg, "all") == 0) {
1383                         min = 0;
1384                         max = CTDB_EVENT_MAX;
1385                 } else {
1386                         DEBUG(DEBUG_ERR, ("Unknown event type %s\n", argv[0]));
1387                         return -1;
1388                 }
1389         }
1390
1391         if (options.machinereadable) {
1392                 printm(":Type:Name:Code:Status:Start:End:Error Output...:\n");
1393         }
1394
1395         for (type = min; type < max; type++) {
1396                 ret = control_one_scriptstatus(ctdb, type);
1397                 if (ret != 0) {
1398                         return ret;
1399                 }
1400         }
1401
1402         return 0;
1403 }
1404
1405 /*
1406   enable an eventscript
1407  */
1408 static int control_enablescript(struct ctdb_context *ctdb, int argc, const char **argv)
1409 {
1410         int ret;
1411
1412         if (argc < 1) {
1413                 usage();
1414         }
1415
1416         ret = ctdb_ctrl_enablescript(ctdb, TIMELIMIT(), options.pnn, argv[0]);
1417         if (ret != 0) {
1418           DEBUG(DEBUG_ERR, ("Unable to enable script %s on node %u\n", argv[0], options.pnn));
1419                 return ret;
1420         }
1421
1422         return 0;
1423 }
1424
1425 /*
1426   disable an eventscript
1427  */
1428 static int control_disablescript(struct ctdb_context *ctdb, int argc, const char **argv)
1429 {
1430         int ret;
1431
1432         if (argc < 1) {
1433                 usage();
1434         }
1435
1436         ret = ctdb_ctrl_disablescript(ctdb, TIMELIMIT(), options.pnn, argv[0]);
1437         if (ret != 0) {
1438           DEBUG(DEBUG_ERR, ("Unable to disable script %s on node %u\n", argv[0], options.pnn));
1439                 return ret;
1440         }
1441
1442         return 0;
1443 }
1444
1445 /*
1446   display the pnn of the recovery master
1447  */
1448 static int control_recmaster(struct ctdb_context *ctdb, int argc, const char **argv)
1449 {
1450         uint32_t recmaster;
1451         int ret;
1452
1453         ret = ctdb_ctrl_getrecmaster(ctdb, ctdb, TIMELIMIT(), options.pnn, &recmaster);
1454         if (ret != 0) {
1455                 DEBUG(DEBUG_ERR, ("Unable to get recmaster from node %u\n", options.pnn));
1456                 return -1;
1457         }
1458         printf("%d\n",recmaster);
1459
1460         return 0;
1461 }
1462
1463 /*
1464   add a tickle to a public address
1465  */
1466 static int control_add_tickle(struct ctdb_context *ctdb, int argc, const char **argv)
1467 {
1468         struct ctdb_connection t;
1469         TDB_DATA data;
1470         int ret;
1471
1472         assert_single_node_only();
1473
1474         if (argc < 2) {
1475                 usage();
1476         }
1477
1478         if (parse_ip_port(argv[0], &t.src) == 0) {
1479                 DEBUG(DEBUG_ERR,("Wrongly formed ip address '%s'\n", argv[0]));
1480                 return -1;
1481         }
1482         if (parse_ip_port(argv[1], &t.dst) == 0) {
1483                 DEBUG(DEBUG_ERR,("Wrongly formed ip address '%s'\n", argv[1]));
1484                 return -1;
1485         }
1486
1487         data.dptr = (uint8_t *)&t;
1488         data.dsize = sizeof(t);
1489
1490         /* tell all nodes about this tcp connection */
1491         ret = ctdb_control(ctdb, options.pnn, 0, CTDB_CONTROL_TCP_ADD_DELAYED_UPDATE,
1492                            0, data, ctdb, NULL, NULL, NULL, NULL);
1493         if (ret != 0) {
1494                 DEBUG(DEBUG_ERR,("Failed to add tickle\n"));
1495                 return -1;
1496         }
1497         
1498         return 0;
1499 }
1500
1501
1502 /*
1503   delete a tickle from a node
1504  */
1505 static int control_del_tickle(struct ctdb_context *ctdb, int argc, const char **argv)
1506 {
1507         struct ctdb_connection t;
1508         TDB_DATA data;
1509         int ret;
1510
1511         assert_single_node_only();
1512
1513         if (argc < 2) {
1514                 usage();
1515         }
1516
1517         if (parse_ip_port(argv[0], &t.src) == 0) {
1518                 DEBUG(DEBUG_ERR,("Wrongly formed ip address '%s'\n", argv[0]));
1519                 return -1;
1520         }
1521         if (parse_ip_port(argv[1], &t.dst) == 0) {
1522                 DEBUG(DEBUG_ERR,("Wrongly formed ip address '%s'\n", argv[1]));
1523                 return -1;
1524         }
1525
1526         data.dptr = (uint8_t *)&t;
1527         data.dsize = sizeof(t);
1528
1529         /* tell all nodes about this tcp connection */
1530         ret = ctdb_control(ctdb, options.pnn, 0, CTDB_CONTROL_TCP_REMOVE,
1531                            0, data, ctdb, NULL, NULL, NULL, NULL);
1532         if (ret != 0) {
1533                 DEBUG(DEBUG_ERR,("Failed to remove tickle\n"));
1534                 return -1;
1535         }
1536         
1537         return 0;
1538 }
1539
1540
1541 /*
1542   get a list of all tickles for this pnn
1543  */
1544 static int control_get_tickles(struct ctdb_context *ctdb, int argc, const char **argv)
1545 {
1546         struct ctdb_tickle_list_old *list;
1547         ctdb_sock_addr addr;
1548         int i, ret;
1549         unsigned port = 0;
1550
1551         assert_single_node_only();
1552
1553         if (argc < 1) {
1554                 usage();
1555         }
1556
1557         if (argc == 2) {
1558                 port = atoi(argv[1]);
1559         }
1560
1561         if (parse_ip(argv[0], NULL, 0, &addr) == 0) {
1562                 DEBUG(DEBUG_ERR,("Wrongly formed ip address '%s'\n", argv[0]));
1563                 return -1;
1564         }
1565
1566         ret = ctdb_ctrl_get_tcp_tickles(ctdb, TIMELIMIT(), options.pnn, ctdb, &addr, &list);
1567         if (ret == -1) {
1568                 DEBUG(DEBUG_ERR, ("Unable to list tickles\n"));
1569                 return -1;
1570         }
1571
1572         if (options.machinereadable){
1573                 printm(":source ip:port:destination ip:port:\n");
1574                 for (i=0;i<list->num;i++) {
1575                         if (port && port != ntohs(list->connections[i].dst.ip.sin_port)) {
1576                                 continue;
1577                         }
1578                         printm(":%s:%u", ctdb_addr_to_str(&list->connections[i].src), ntohs(list->connections[i].src.ip.sin_port));
1579                         printm(":%s:%u:\n", ctdb_addr_to_str(&list->connections[i].dst), ntohs(list->connections[i].dst.ip.sin_port));
1580                 }
1581         } else {
1582                 printf("Tickles for ip:%s\n", ctdb_addr_to_str(&list->addr));
1583                 printf("Num tickles:%u\n", list->num);
1584                 for (i=0;i<list->num;i++) {
1585                         if (port && port != ntohs(list->connections[i].dst.ip.sin_port)) {
1586                                 continue;
1587                         }
1588                         printf("SRC: %s:%u   ", ctdb_addr_to_str(&list->connections[i].src), ntohs(list->connections[i].src.ip.sin_port));
1589                         printf("DST: %s:%u\n", ctdb_addr_to_str(&list->connections[i].dst), ntohs(list->connections[i].dst.ip.sin_port));
1590                 }
1591         }
1592
1593         talloc_free(list);
1594         
1595         return 0;
1596 }
1597
1598
1599 static int move_ip(struct ctdb_context *ctdb, ctdb_sock_addr *addr, uint32_t pnn)
1600 {
1601         struct ctdb_public_ip_list_old *ips;
1602         struct ctdb_public_ip ip;
1603         int i, ret;
1604         uint32_t *nodes;
1605         uint32_t disable_time;
1606         TDB_DATA data;
1607         struct ctdb_node_map_old *nodemap=NULL;
1608         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
1609
1610         disable_time = 30;
1611         data.dptr  = (uint8_t*)&disable_time;
1612         data.dsize = sizeof(disable_time);
1613         ret = ctdb_client_send_message(ctdb, CTDB_BROADCAST_CONNECTED, CTDB_SRVID_DISABLE_IP_CHECK, data);
1614         if (ret != 0) {
1615                 DEBUG(DEBUG_ERR,("Failed to send message to disable ipcheck\n"));
1616                 return -1;
1617         }
1618
1619
1620
1621         /* read the public ip list from the node */
1622         ret = ctdb_ctrl_get_public_ips(ctdb, TIMELIMIT(), pnn, ctdb, &ips);
1623         if (ret != 0) {
1624                 DEBUG(DEBUG_ERR, ("Unable to get public ip list from node %u\n", pnn));
1625                 talloc_free(tmp_ctx);
1626                 return -1;
1627         }
1628
1629         for (i=0;i<ips->num;i++) {
1630                 if (ctdb_same_ip(addr, &ips->ips[i].addr)) {
1631                         break;
1632                 }
1633         }
1634         if (i==ips->num) {
1635                 DEBUG(DEBUG_ERR, ("Node %u can not host ip address '%s'\n",
1636                         pnn, ctdb_addr_to_str(addr)));
1637                 talloc_free(tmp_ctx);
1638                 return -1;
1639         }
1640
1641         ip.pnn  = pnn;
1642         ip.addr = *addr;
1643
1644         data.dptr  = (uint8_t *)&ip;
1645         data.dsize = sizeof(ip);
1646
1647         ret = ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), options.pnn, tmp_ctx, &nodemap);
1648         if (ret != 0) {
1649                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from node %u\n", options.pnn));
1650                 talloc_free(tmp_ctx);
1651                 return ret;
1652         }
1653
1654         nodes = list_of_nodes(ctdb, nodemap, tmp_ctx, NODE_FLAGS_INACTIVE, pnn);
1655         ret = ctdb_client_async_control(ctdb, CTDB_CONTROL_RELEASE_IP,
1656                                         nodes, 0,
1657                                         LONGTIMELIMIT(),
1658                                         false, data,
1659                                         NULL, NULL,
1660                                         NULL);
1661         if (ret != 0) {
1662                 DEBUG(DEBUG_ERR,("Failed to release IP on nodes\n"));
1663                 talloc_free(tmp_ctx);
1664                 return -1;
1665         }
1666
1667         ret = ctdb_ctrl_takeover_ip(ctdb, LONGTIMELIMIT(), pnn, &ip);
1668         if (ret != 0) {
1669                 DEBUG(DEBUG_ERR,("Failed to take over IP on node %d\n", pnn));
1670                 talloc_free(tmp_ctx);
1671                 return -1;
1672         }
1673
1674         /* update the recovery daemon so it now knows to expect the new
1675            node assignment for this ip.
1676         */
1677         ret = ctdb_client_send_message(ctdb, CTDB_BROADCAST_CONNECTED, CTDB_SRVID_RECD_UPDATE_IP, data);
1678         if (ret != 0) {
1679                 DEBUG(DEBUG_ERR,("Failed to send message to update the ip on the recovery master.\n"));
1680                 return -1;
1681         }
1682
1683         talloc_free(tmp_ctx);
1684         return 0;
1685 }
1686
1687
1688 /* 
1689  * scans all other nodes and returns a pnn for another node that can host this 
1690  * ip address or -1
1691  */
1692 static int
1693 find_other_host_for_public_ip(struct ctdb_context *ctdb, ctdb_sock_addr *addr)
1694 {
1695         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
1696         struct ctdb_public_ip_list_old *ips;
1697         struct ctdb_node_map_old *nodemap=NULL;
1698         int i, j, ret;
1699         int pnn;
1700
1701         ret = ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE, tmp_ctx, &nodemap);
1702         if (ret != 0) {
1703                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from node %u\n", options.pnn));
1704                 talloc_free(tmp_ctx);
1705                 return ret;
1706         }
1707
1708         for(i=0;i<nodemap->num;i++){
1709                 if (nodemap->nodes[i].flags & NODE_FLAGS_INACTIVE) {
1710                         continue;
1711                 }
1712                 if (nodemap->nodes[i].pnn == options.pnn) {
1713                         continue;
1714                 }
1715
1716                 /* read the public ip list from this node */
1717                 ret = ctdb_ctrl_get_public_ips(ctdb, TIMELIMIT(), nodemap->nodes[i].pnn, tmp_ctx, &ips);
1718                 if (ret != 0) {
1719                         DEBUG(DEBUG_ERR, ("Unable to get public ip list from node %u\n", nodemap->nodes[i].pnn));
1720                         return -1;
1721                 }
1722
1723                 for (j=0;j<ips->num;j++) {
1724                         if (ctdb_same_ip(addr, &ips->ips[j].addr)) {
1725                                 pnn = nodemap->nodes[i].pnn;
1726                                 talloc_free(tmp_ctx);
1727                                 return pnn;
1728                         }
1729                 }
1730                 talloc_free(ips);
1731         }
1732
1733         talloc_free(tmp_ctx);
1734         return -1;
1735 }
1736
1737 /* If pnn is -1 then try to find a node to move IP to... */
1738 static bool try_moveip(struct ctdb_context *ctdb, ctdb_sock_addr *addr, uint32_t pnn)
1739 {
1740         bool pnn_specified = (pnn == -1 ? false : true);
1741         int retries = 0;
1742
1743         while (retries < 5) {
1744                 if (!pnn_specified) {
1745                         pnn = find_other_host_for_public_ip(ctdb, addr);
1746                         if (pnn == -1) {
1747                                 return false;
1748                         }
1749                         DEBUG(DEBUG_NOTICE,
1750                               ("Trying to move public IP to node %u\n", pnn));
1751                 }
1752
1753                 if (move_ip(ctdb, addr, pnn) == 0) {
1754                         return true;
1755                 }
1756
1757                 sleep(3);
1758                 retries++;
1759         }
1760
1761         return false;
1762 }
1763
1764
1765 /*
1766   move/failover an ip address to a specific node
1767  */
1768 static int control_moveip(struct ctdb_context *ctdb, int argc, const char **argv)
1769 {
1770         uint32_t pnn;
1771         ctdb_sock_addr addr;
1772
1773         assert_single_node_only();
1774
1775         if (argc < 2) {
1776                 usage();
1777                 return -1;
1778         }
1779
1780         if (parse_ip(argv[0], NULL, 0, &addr) == 0) {
1781                 DEBUG(DEBUG_ERR,("Wrongly formed ip address '%s'\n", argv[0]));
1782                 return -1;
1783         }
1784
1785
1786         if (sscanf(argv[1], "%u", &pnn) != 1) {
1787                 DEBUG(DEBUG_ERR, ("Badly formed pnn\n"));
1788                 return -1;
1789         }
1790
1791         if (!try_moveip(ctdb, &addr, pnn)) {
1792                 DEBUG(DEBUG_ERR,("Failed to move IP to node %d.\n", pnn));
1793                 return -1;
1794         }
1795
1796         return 0;
1797 }
1798
1799 static int rebalance_node(struct ctdb_context *ctdb, uint32_t pnn)
1800 {
1801         TDB_DATA data;
1802
1803         data.dptr  = (uint8_t *)&pnn;
1804         data.dsize = sizeof(uint32_t);
1805         if (ctdb_client_send_message(ctdb, CTDB_BROADCAST_CONNECTED, CTDB_SRVID_REBALANCE_NODE, data) != 0) {
1806                 DEBUG(DEBUG_ERR,
1807                       ("Failed to send message to force node %u to be a rebalancing target\n",
1808                        pnn));
1809                 return -1;
1810         }
1811
1812         return 0;
1813 }
1814
1815
1816 /*
1817   rebalance a node by setting it to allow failback and triggering a
1818   takeover run
1819  */
1820 static int control_rebalancenode(struct ctdb_context *ctdb, int argc, const char **argv)
1821 {
1822         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
1823         uint32_t *nodes;
1824         uint32_t pnn_mode;
1825         int i, ret;
1826
1827         assert_single_node_only();
1828
1829         if (argc > 1) {
1830                 usage();
1831         }
1832
1833         /* Determine the nodes where IPs need to be reloaded */
1834         if (!parse_nodestring(ctdb, tmp_ctx, argc == 1 ? argv[0] : NULL,
1835                               options.pnn, true, &nodes, &pnn_mode)) {
1836                 ret = -1;
1837                 goto done;
1838         }
1839
1840         for (i = 0; i < talloc_array_length(nodes); i++) {
1841                 if (!rebalance_node(ctdb, nodes[i])) {
1842                         ret = -1;
1843                 }
1844         }
1845
1846 done:
1847         talloc_free(tmp_ctx);
1848         return ret;
1849 }
1850
1851 static int rebalance_ip(struct ctdb_context *ctdb, ctdb_sock_addr *addr)
1852 {
1853         struct ctdb_public_ip ip;
1854         int ret;
1855         uint32_t *nodes;
1856         uint32_t disable_time;
1857         TDB_DATA data;
1858         struct ctdb_node_map_old *nodemap=NULL;
1859         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
1860
1861         disable_time = 30;
1862         data.dptr  = (uint8_t*)&disable_time;
1863         data.dsize = sizeof(disable_time);
1864         ret = ctdb_client_send_message(ctdb, CTDB_BROADCAST_CONNECTED, CTDB_SRVID_DISABLE_IP_CHECK, data);
1865         if (ret != 0) {
1866                 DEBUG(DEBUG_ERR,("Failed to send message to disable ipcheck\n"));
1867                 return -1;
1868         }
1869
1870         ip.pnn  = -1;
1871         ip.addr = *addr;
1872
1873         data.dptr  = (uint8_t *)&ip;
1874         data.dsize = sizeof(ip);
1875
1876         ret = ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), options.pnn, tmp_ctx, &nodemap);
1877         if (ret != 0) {
1878                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from node %u\n", options.pnn));
1879                 talloc_free(tmp_ctx);
1880                 return ret;
1881         }
1882
1883         nodes = list_of_active_nodes(ctdb, nodemap, tmp_ctx, true);
1884         ret = ctdb_client_async_control(ctdb, CTDB_CONTROL_RELEASE_IP,
1885                                         nodes, 0,
1886                                         LONGTIMELIMIT(),
1887                                         false, data,
1888                                         NULL, NULL,
1889                                         NULL);
1890         if (ret != 0) {
1891                 DEBUG(DEBUG_ERR,("Failed to release IP on nodes\n"));
1892                 talloc_free(tmp_ctx);
1893                 return -1;
1894         }
1895
1896         talloc_free(tmp_ctx);
1897         return 0;
1898 }
1899
1900 /*
1901   release an ip form all nodes and have it re-assigned by recd
1902  */
1903 static int control_rebalanceip(struct ctdb_context *ctdb, int argc, const char **argv)
1904 {
1905         ctdb_sock_addr addr;
1906
1907         assert_single_node_only();
1908
1909         if (argc < 1) {
1910                 usage();
1911                 return -1;
1912         }
1913
1914         if (parse_ip(argv[0], NULL, 0, &addr) == 0) {
1915                 DEBUG(DEBUG_ERR,("Wrongly formed ip address '%s'\n", argv[0]));
1916                 return -1;
1917         }
1918
1919         if (rebalance_ip(ctdb, &addr) != 0) {
1920                 DEBUG(DEBUG_ERR,("Error when trying to reassign ip\n"));
1921                 return -1;
1922         }
1923
1924         return 0;
1925 }
1926
1927 static int getips_store_callback(void *param, void *data)
1928 {
1929         struct ctdb_public_ip *node_ip = (struct ctdb_public_ip *)data;
1930         struct ctdb_public_ip_list_old *ips = param;
1931         int i;
1932
1933         i = ips->num++;
1934         ips->ips[i].pnn  = node_ip->pnn;
1935         ips->ips[i].addr = node_ip->addr;
1936         return 0;
1937 }
1938
1939 static int getips_count_callback(void *param, void *data)
1940 {
1941         uint32_t *count = param;
1942
1943         (*count)++;
1944         return 0;
1945 }
1946
1947 #define IP_KEYLEN       4
1948 static uint32_t *ip_key(ctdb_sock_addr *ip)
1949 {
1950         static uint32_t key[IP_KEYLEN];
1951
1952         bzero(key, sizeof(key));
1953
1954         switch (ip->sa.sa_family) {
1955         case AF_INET:
1956                 key[0]  = ip->ip.sin_addr.s_addr;
1957                 break;
1958         case AF_INET6: {
1959                 uint32_t *s6_a32 = (uint32_t *)&(ip->ip6.sin6_addr.s6_addr);
1960                 key[0]  = s6_a32[3];
1961                 key[1]  = s6_a32[2];
1962                 key[2]  = s6_a32[1];
1963                 key[3]  = s6_a32[0];
1964                 break;
1965         }
1966         default:
1967                 DEBUG(DEBUG_ERR, (__location__ " ERROR, unknown family passed :%u\n", ip->sa.sa_family));
1968                 return key;
1969         }
1970
1971         return key;
1972 }
1973
1974 static void *add_ip_callback(void *parm, void *data)
1975 {
1976         return parm;
1977 }
1978
1979 static int
1980 control_get_all_public_ips(struct ctdb_context *ctdb, TALLOC_CTX *tmp_ctx, struct ctdb_public_ip_list_old **ips)
1981 {
1982         struct ctdb_public_ip_list_old *tmp_ips;
1983         struct ctdb_node_map_old *nodemap=NULL;
1984         trbt_tree_t *ip_tree;
1985         int i, j, len, ret;
1986         uint32_t count;
1987
1988         ret = ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE, tmp_ctx, &nodemap);
1989         if (ret != 0) {
1990                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from node %u\n", options.pnn));
1991                 return ret;
1992         }
1993
1994         ip_tree = trbt_create(tmp_ctx, 0);
1995
1996         for(i=0;i<nodemap->num;i++){
1997                 if (nodemap->nodes[i].flags & NODE_FLAGS_DELETED) {
1998                         continue;
1999                 }
2000                 if (nodemap->nodes[i].flags & NODE_FLAGS_DISCONNECTED) {
2001                         continue;
2002                 }
2003
2004                 /* read the public ip list from this node */
2005                 ret = ctdb_ctrl_get_public_ips(ctdb, TIMELIMIT(), nodemap->nodes[i].pnn, tmp_ctx, &tmp_ips);
2006                 if (ret != 0) {
2007                         DEBUG(DEBUG_ERR, ("Unable to get public ip list from node %u\n", nodemap->nodes[i].pnn));
2008                         return -1;
2009                 }
2010         
2011                 for (j=0; j<tmp_ips->num;j++) {
2012                         struct ctdb_public_ip *node_ip;
2013
2014                         node_ip = talloc(tmp_ctx, struct ctdb_public_ip);
2015                         node_ip->pnn  = tmp_ips->ips[j].pnn;
2016                         node_ip->addr = tmp_ips->ips[j].addr;
2017
2018                         trbt_insertarray32_callback(ip_tree,
2019                                 IP_KEYLEN, ip_key(&tmp_ips->ips[j].addr),
2020                                 add_ip_callback,
2021                                 node_ip);
2022                 }
2023                 talloc_free(tmp_ips);
2024         }
2025
2026         /* traverse */
2027         count = 0;
2028         trbt_traversearray32(ip_tree, IP_KEYLEN, getips_count_callback, &count);
2029
2030         len = offsetof(struct ctdb_public_ip_list_old, ips) +
2031                 count*sizeof(struct ctdb_public_ip);
2032         tmp_ips = talloc_zero_size(tmp_ctx, len);
2033         trbt_traversearray32(ip_tree, IP_KEYLEN, getips_store_callback, tmp_ips);
2034
2035         *ips = tmp_ips;
2036
2037         return 0;
2038 }
2039
2040
2041 static void ctdb_every_second(struct tevent_context *ev,
2042                               struct tevent_timer *te,
2043                               struct timeval t, void *p)
2044 {
2045         struct ctdb_context *ctdb = talloc_get_type(p, struct ctdb_context);
2046
2047         tevent_add_timer(ctdb->ev, ctdb, timeval_current_ofs(1, 0),
2048                          ctdb_every_second, ctdb);
2049 }
2050
2051 struct srvid_reply_handler_data {
2052         bool done;
2053         bool wait_for_all;
2054         uint32_t *nodes;
2055         const char *srvid_str;
2056 };
2057
2058 static void srvid_broadcast_reply_handler(uint64_t srvid, TDB_DATA data,
2059                                          void *private_data)
2060 {
2061         struct srvid_reply_handler_data *d =
2062                 (struct srvid_reply_handler_data *)private_data;
2063         int i;
2064         int32_t ret;
2065
2066         if (data.dsize != sizeof(ret)) {
2067                 DEBUG(DEBUG_ERR, (__location__ " Wrong reply size\n"));
2068                 return;
2069         }
2070
2071         /* ret will be a PNN (i.e. >=0) on success, or negative on error */
2072         ret = *(int32_t *)data.dptr;
2073         if (ret < 0) {
2074                 DEBUG(DEBUG_ERR,
2075                       ("%s failed with result %d\n", d->srvid_str, ret));
2076                 return;
2077         }
2078
2079         if (!d->wait_for_all) {
2080                 d->done = true;
2081                 return;
2082         }
2083
2084         /* Wait for all replies */
2085         d->done = true;
2086         for (i = 0; i < talloc_array_length(d->nodes); i++) {
2087                 if (d->nodes[i] == ret) {
2088                         DEBUG(DEBUG_DEBUG,
2089                               ("%s reply received from node %u\n",
2090                                d->srvid_str, ret));
2091                         d->nodes[i] = -1;
2092                 }
2093                 if (d->nodes[i] != -1) {
2094                         /* Found a node that hasn't yet replied */
2095                         d->done = false;
2096                 }
2097         }
2098 }
2099
2100 /* Broadcast the given SRVID to all connected nodes.  Wait for 1 reply
2101  * or replies from all connected nodes.  arg is the data argument to
2102  * pass in the srvid_request structure - pass 0 if this isn't needed.
2103  */
2104 static int srvid_broadcast(struct ctdb_context *ctdb,
2105                            uint64_t srvid, uint32_t *arg,
2106                            const char *srvid_str, bool wait_for_all)
2107 {
2108         int ret;
2109         TDB_DATA data;
2110         uint32_t pnn;
2111         uint64_t reply_srvid;
2112         struct ctdb_srvid_message request;
2113         struct ctdb_disable_message request_data;
2114         struct srvid_reply_handler_data reply_data;
2115         struct timeval tv;
2116
2117         ZERO_STRUCT(request);
2118
2119         /* Time ticks to enable timeouts to be processed */
2120         tevent_add_timer(ctdb->ev, ctdb, timeval_current_ofs(1, 0),
2121                          ctdb_every_second, ctdb);
2122
2123         pnn = ctdb_get_pnn(ctdb);
2124         reply_srvid = getpid();
2125
2126         if (arg == NULL) {
2127                 request.pnn = pnn;
2128                 request.srvid = reply_srvid;
2129
2130                 data.dptr = (uint8_t *)&request;
2131                 data.dsize = sizeof(request);
2132         } else {
2133                 request_data.pnn = pnn;
2134                 request_data.srvid = reply_srvid;
2135                 request_data.timeout = *arg;
2136
2137                 data.dptr = (uint8_t *)&request_data;
2138                 data.dsize = sizeof(request_data);
2139         }
2140
2141         /* Register message port for reply from recovery master */
2142         ctdb_client_set_message_handler(ctdb, reply_srvid,
2143                                         srvid_broadcast_reply_handler,
2144                                         &reply_data);
2145
2146         reply_data.wait_for_all = wait_for_all;
2147         reply_data.nodes = NULL;
2148         reply_data.srvid_str = srvid_str;
2149
2150 again:
2151         reply_data.done = false;
2152
2153         if (wait_for_all) {
2154                 struct ctdb_node_map_old *nodemap;
2155
2156                 ret = ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(),
2157                                            CTDB_CURRENT_NODE, ctdb, &nodemap);
2158                 if (ret != 0) {
2159                         DEBUG(DEBUG_ERR,
2160                               ("Unable to get nodemap from current node, try again\n"));
2161                         sleep(1);
2162                         goto again;
2163                 }
2164
2165                 if (reply_data.nodes != NULL) {
2166                         talloc_free(reply_data.nodes);
2167                 }
2168                 reply_data.nodes = list_of_connected_nodes(ctdb, nodemap,
2169                                                            NULL, true);
2170
2171                 talloc_free(nodemap);
2172         }
2173
2174         /* Send to all connected nodes. Only recmaster replies */
2175         ret = ctdb_client_send_message(ctdb, CTDB_BROADCAST_CONNECTED,
2176                                        srvid, data);
2177         if (ret != 0) {
2178                 /* This can only happen if the socket is closed and
2179                  * there's no way to recover from that, so don't try
2180                  * again.
2181                  */
2182                 DEBUG(DEBUG_ERR,
2183                       ("Failed to send %s request to connected nodes\n",
2184                        srvid_str));
2185                 return -1;
2186         }
2187
2188         tv = timeval_current();
2189         /* This loop terminates the reply is received */
2190         while (timeval_elapsed(&tv) < 5.0 && !reply_data.done) {
2191                 tevent_loop_once(ctdb->ev);
2192         }
2193
2194         if (!reply_data.done) {
2195                 DEBUG(DEBUG_NOTICE,
2196                       ("Still waiting for confirmation of %s\n", srvid_str));
2197                 sleep(1);
2198                 goto again;
2199         }
2200
2201         ctdb_client_remove_message_handler(ctdb, reply_srvid, &reply_data);
2202
2203         talloc_free(reply_data.nodes);
2204
2205         return 0;
2206 }
2207
2208 static int ipreallocate(struct ctdb_context *ctdb)
2209 {
2210         return srvid_broadcast(ctdb, CTDB_SRVID_TAKEOVER_RUN, NULL,
2211                                "IP reallocation", false);
2212 }
2213
2214
2215 static int control_ipreallocate(struct ctdb_context *ctdb, int argc, const char **argv)
2216 {
2217         return ipreallocate(ctdb);
2218 }
2219
2220 /*
2221   add a public ip address to a node
2222  */
2223 static int control_addip(struct ctdb_context *ctdb, int argc, const char **argv)
2224 {
2225         int i, ret;
2226         int len, retries = 0;
2227         unsigned mask;
2228         ctdb_sock_addr addr;
2229         struct ctdb_addr_info_old *pub;
2230         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
2231         struct ctdb_public_ip_list_old *ips;
2232
2233
2234         if (argc != 2) {
2235                 talloc_free(tmp_ctx);
2236                 usage();
2237         }
2238
2239         if (!parse_ip_mask(argv[0], argv[1], &addr, &mask)) {
2240                 DEBUG(DEBUG_ERR, ("Badly formed ip/mask : %s\n", argv[0]));
2241                 talloc_free(tmp_ctx);
2242                 return -1;
2243         }
2244
2245         /* read the public ip list from the node */
2246         ret = ctdb_ctrl_get_public_ips(ctdb, TIMELIMIT(), options.pnn, tmp_ctx, &ips);
2247         if (ret != 0) {
2248                 DEBUG(DEBUG_ERR, ("Unable to get public ip list from node %u\n", options.pnn));
2249                 talloc_free(tmp_ctx);
2250                 return -1;
2251         }
2252         for (i=0;i<ips->num;i++) {
2253                 if (ctdb_same_ip(&addr, &ips->ips[i].addr)) {
2254                         DEBUG(DEBUG_ERR,("Can not add ip to node. Node already hosts this ip\n"));
2255                         return 0;
2256                 }
2257         }
2258
2259
2260
2261         /* Dont timeout. This command waits for an ip reallocation
2262            which sometimes can take wuite a while if there has
2263            been a recent recovery
2264         */
2265         alarm(0);
2266
2267         len = offsetof(struct ctdb_addr_info_old, iface) + strlen(argv[1]) + 1;
2268         pub = talloc_size(tmp_ctx, len); 
2269         CTDB_NO_MEMORY(ctdb, pub);
2270
2271         pub->addr  = addr;
2272         pub->mask  = mask;
2273         pub->len   = strlen(argv[1])+1;
2274         memcpy(&pub->iface[0], argv[1], strlen(argv[1])+1);
2275
2276         do {
2277                 ret = ctdb_ctrl_add_public_ip(ctdb, TIMELIMIT(), options.pnn, pub);
2278                 if (ret != 0) {
2279                         DEBUG(DEBUG_ERR, ("Unable to add public ip to node %u. Wait 3 seconds and try again.\n", options.pnn));
2280                         sleep(3);
2281                         retries++;
2282                 }
2283         } while (retries < 5 && ret != 0);
2284         if (ret != 0) {
2285                 DEBUG(DEBUG_ERR, ("Unable to add public ip to node %u. Giving up.\n", options.pnn));
2286                 talloc_free(tmp_ctx);
2287                 return ret;
2288         }
2289
2290         if (rebalance_node(ctdb, options.pnn) != 0) {
2291                 DEBUG(DEBUG_ERR,("Error when trying to rebalance node\n"));
2292                 return ret;
2293         }
2294
2295         talloc_free(tmp_ctx);
2296         return 0;
2297 }
2298
2299 /*
2300   add a public ip address to a node
2301  */
2302 static int control_ipiface(struct ctdb_context *ctdb, int argc, const char **argv)
2303 {
2304         ctdb_sock_addr addr;
2305         char *iface = NULL;
2306
2307         if (argc != 1) {
2308                 usage();
2309         }
2310
2311         if (!parse_ip(argv[0], NULL, 0, &addr)) {
2312                 printf("Badly formed ip : %s\n", argv[0]);
2313                 return -1;
2314         }
2315
2316         iface = ctdb_sys_find_ifname(&addr);
2317         if (iface == NULL) {
2318                 printf("Failed to get interface name for ip: %s", argv[0]);
2319                 return -1;
2320         }
2321
2322         printf("IP on interface %s\n", iface);
2323
2324         free(iface);
2325
2326         return 0;
2327 }
2328
2329 static int control_delip(struct ctdb_context *ctdb, int argc, const char **argv);
2330
2331 static int control_delip_all(struct ctdb_context *ctdb, int argc, const char **argv, ctdb_sock_addr *addr)
2332 {
2333         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
2334         struct ctdb_node_map_old *nodemap=NULL;
2335         struct ctdb_public_ip_list_old *ips;
2336         int ret, i, j;
2337
2338         ret = ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE, tmp_ctx, &nodemap);
2339         if (ret != 0) {
2340                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from current node\n"));
2341                 return ret;
2342         }
2343
2344         /* remove it from the nodes that are not hosting the ip currently */
2345         for(i=0;i<nodemap->num;i++){
2346                 if (nodemap->nodes[i].flags & NODE_FLAGS_INACTIVE) {
2347                         continue;
2348                 }
2349                 ret = ctdb_ctrl_get_public_ips(ctdb, TIMELIMIT(), nodemap->nodes[i].pnn, tmp_ctx, &ips);
2350                 if (ret != 0) {
2351                         DEBUG(DEBUG_ERR, ("Unable to get public ip list from node %d\n", nodemap->nodes[i].pnn));
2352                         continue;
2353                 }
2354
2355                 for (j=0;j<ips->num;j++) {
2356                         if (ctdb_same_ip(addr, &ips->ips[j].addr)) {
2357                                 break;
2358                         }
2359                 }
2360                 if (j==ips->num) {
2361                         continue;
2362                 }
2363
2364                 if (ips->ips[j].pnn == nodemap->nodes[i].pnn) {
2365                         continue;
2366                 }
2367
2368                 options.pnn = nodemap->nodes[i].pnn;
2369                 control_delip(ctdb, argc, argv);
2370         }
2371
2372
2373         /* remove it from every node (also the one hosting it) */
2374         for(i=0;i<nodemap->num;i++){
2375                 if (nodemap->nodes[i].flags & NODE_FLAGS_INACTIVE) {
2376                         continue;
2377                 }
2378                 ret = ctdb_ctrl_get_public_ips(ctdb, TIMELIMIT(), nodemap->nodes[i].pnn, tmp_ctx, &ips);
2379                 if (ret != 0) {
2380                         DEBUG(DEBUG_ERR, ("Unable to get public ip list from node %d\n", nodemap->nodes[i].pnn));
2381                         continue;
2382                 }
2383
2384                 for (j=0;j<ips->num;j++) {
2385                         if (ctdb_same_ip(addr, &ips->ips[j].addr)) {
2386                                 break;
2387                         }
2388                 }
2389                 if (j==ips->num) {
2390                         continue;
2391                 }
2392
2393                 options.pnn = nodemap->nodes[i].pnn;
2394                 control_delip(ctdb, argc, argv);
2395         }
2396
2397         talloc_free(tmp_ctx);
2398         return 0;
2399 }
2400         
2401 /*
2402   delete a public ip address from a node
2403  */
2404 static int control_delip(struct ctdb_context *ctdb, int argc, const char **argv)
2405 {
2406         int i, ret;
2407         ctdb_sock_addr addr;
2408         struct ctdb_addr_info_old pub;
2409         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
2410         struct ctdb_public_ip_list_old *ips;
2411
2412         if (argc != 1) {
2413                 talloc_free(tmp_ctx);
2414                 usage();
2415         }
2416
2417         if (parse_ip(argv[0], NULL, 0, &addr) == 0) {
2418                 DEBUG(DEBUG_ERR,("Wrongly formed ip address '%s'\n", argv[0]));
2419                 return -1;
2420         }
2421
2422         if (options.pnn == CTDB_BROADCAST_ALL) {
2423                 return control_delip_all(ctdb, argc, argv, &addr);
2424         }
2425
2426         pub.addr  = addr;
2427         pub.mask  = 0;
2428         pub.len   = 0;
2429
2430         ret = ctdb_ctrl_get_public_ips(ctdb, TIMELIMIT(), options.pnn, tmp_ctx, &ips);
2431         if (ret != 0) {
2432                 DEBUG(DEBUG_ERR, ("Unable to get public ip list from cluster\n"));
2433                 talloc_free(tmp_ctx);
2434                 return ret;
2435         }
2436         
2437         for (i=0;i<ips->num;i++) {
2438                 if (ctdb_same_ip(&addr, &ips->ips[i].addr)) {
2439                         break;
2440                 }
2441         }
2442
2443         if (i==ips->num) {
2444                 DEBUG(DEBUG_ERR, ("This node does not support this public address '%s'\n",
2445                         ctdb_addr_to_str(&addr)));
2446                 talloc_free(tmp_ctx);
2447                 return -1;
2448         }
2449
2450         /* This is an optimisation.  If this node is hosting the IP
2451          * then try to move it somewhere else without invoking a full
2452          * takeover run.  We don't care if this doesn't work!
2453          */
2454         if (ips->ips[i].pnn == options.pnn) {
2455                 (void) try_moveip(ctdb, &addr, -1);
2456         }
2457
2458         ret = ctdb_ctrl_del_public_ip(ctdb, TIMELIMIT(), options.pnn, &pub);
2459         if (ret != 0) {
2460                 DEBUG(DEBUG_ERR, ("Unable to del public ip from node %u\n", options.pnn));
2461                 talloc_free(tmp_ctx);
2462                 return ret;
2463         }
2464
2465         talloc_free(tmp_ctx);
2466         return 0;
2467 }
2468
2469 static int kill_tcp_from_file(struct ctdb_context *ctdb,
2470                               int argc, const char **argv)
2471 {
2472         struct ctdb_connection *killtcp;
2473         int max_entries, current, i;
2474         struct timeval timeout;
2475         char line[128], src[128], dst[128];
2476         int linenum;
2477         TDB_DATA data;
2478         struct client_async_data *async_data;
2479         struct ctdb_client_control_state *state;
2480
2481         if (argc != 0) {
2482                 usage();
2483         }
2484
2485         linenum = 1;
2486         killtcp = NULL;
2487         max_entries = 0;
2488         current = 0;
2489         while (!feof(stdin)) {
2490                 if (fgets(line, sizeof(line), stdin) == NULL) {
2491                         continue;
2492                 }
2493
2494                 /* Silently skip empty lines */
2495                 if (line[0] == '\n') {
2496                         continue;
2497                 }
2498
2499                 if (sscanf(line, "%s %s\n", src, dst) != 2) {
2500                         DEBUG(DEBUG_ERR, ("Bad line [%d]: '%s'\n",
2501                                           linenum, line));
2502                         talloc_free(killtcp);
2503                         return -1;
2504                 }
2505
2506                 if (current >= max_entries) {
2507                         max_entries += 1024;
2508                         killtcp = talloc_realloc(ctdb, killtcp,
2509                                                  struct ctdb_connection,
2510                                                  max_entries);
2511                         CTDB_NO_MEMORY(ctdb, killtcp);
2512                 }
2513
2514                 if (!parse_ip_port(src, &killtcp[current].src)) {
2515                         DEBUG(DEBUG_ERR, ("Bad IP:port on line [%d]: '%s'\n",
2516                                           linenum, src));
2517                         talloc_free(killtcp);
2518                         return -1;
2519                 }
2520
2521                 if (!parse_ip_port(dst, &killtcp[current].dst)) {
2522                         DEBUG(DEBUG_ERR, ("Bad IP:port on line [%d]: '%s'\n",
2523                                           linenum, dst));
2524                         talloc_free(killtcp);
2525                         return -1;
2526                 }
2527
2528                 current++;
2529         }
2530
2531         async_data = talloc_zero(ctdb, struct client_async_data);
2532         if (async_data == NULL) {
2533                 talloc_free(killtcp);
2534                 return -1;
2535         }
2536
2537         for (i = 0; i < current; i++) {
2538
2539                 data.dsize = sizeof(struct ctdb_connection);
2540                 data.dptr  = (unsigned char *)&killtcp[i];
2541
2542                 timeout = TIMELIMIT();
2543                 state = ctdb_control_send(ctdb, options.pnn, 0,
2544                                           CTDB_CONTROL_KILL_TCP, 0, data,
2545                                           async_data, &timeout, NULL);
2546
2547                 if (state == NULL) {
2548                         DEBUG(DEBUG_ERR,
2549                               ("Failed to call async killtcp control to node %u\n",
2550                                options.pnn));
2551                         talloc_free(killtcp);
2552                         return -1;
2553                 }
2554                 
2555                 ctdb_client_async_add(async_data, state);
2556         }
2557
2558         if (ctdb_client_async_wait(ctdb, async_data) != 0) {
2559                 DEBUG(DEBUG_ERR,("killtcp failed\n"));
2560                 talloc_free(killtcp);
2561                 return -1;
2562         }
2563
2564         talloc_free(killtcp);
2565         return 0;
2566 }
2567
2568
2569 /*
2570   kill a tcp connection
2571  */
2572 static int kill_tcp(struct ctdb_context *ctdb, int argc, const char **argv)
2573 {
2574         int ret;
2575         struct ctdb_connection killtcp;
2576
2577         assert_single_node_only();
2578
2579         if (argc == 0) {
2580                 return kill_tcp_from_file(ctdb, argc, argv);
2581         }
2582
2583         if (argc < 2) {
2584                 usage();
2585         }
2586
2587         if (!parse_ip_port(argv[0], &killtcp.src)) {
2588                 DEBUG(DEBUG_ERR, ("Bad IP:port '%s'\n", argv[0]));
2589                 return -1;
2590         }
2591
2592         if (!parse_ip_port(argv[1], &killtcp.dst)) {
2593                 DEBUG(DEBUG_ERR, ("Bad IP:port '%s'\n", argv[1]));
2594                 return -1;
2595         }
2596
2597         ret = ctdb_ctrl_killtcp(ctdb, TIMELIMIT(), options.pnn, &killtcp);
2598         if (ret != 0) {
2599                 DEBUG(DEBUG_ERR, ("Unable to killtcp from node %u\n", options.pnn));
2600                 return ret;
2601         }
2602
2603         return 0;
2604 }
2605
2606
2607 /*
2608   send a gratious arp
2609  */
2610 static int control_gratious_arp(struct ctdb_context *ctdb, int argc, const char **argv)
2611 {
2612         int ret;
2613         ctdb_sock_addr addr;
2614
2615         assert_single_node_only();
2616
2617         if (argc < 2) {
2618                 usage();
2619         }
2620
2621         if (!parse_ip(argv[0], NULL, 0, &addr)) {
2622                 DEBUG(DEBUG_ERR, ("Bad IP '%s'\n", argv[0]));
2623                 return -1;
2624         }
2625
2626         ret = ctdb_ctrl_gratious_arp(ctdb, TIMELIMIT(), options.pnn, &addr, argv[1]);
2627         if (ret != 0) {
2628                 DEBUG(DEBUG_ERR, ("Unable to send gratious_arp from node %u\n", options.pnn));
2629                 return ret;
2630         }
2631
2632         return 0;
2633 }
2634
2635 /*
2636   register a server id
2637  */
2638 static int regsrvid(struct ctdb_context *ctdb, int argc, const char **argv)
2639 {
2640         int ret;
2641         struct ctdb_client_id server_id;
2642
2643         if (argc < 3) {
2644                 usage();
2645         }
2646
2647         server_id.pnn       = strtoul(argv[0], NULL, 0);
2648         server_id.type      = strtoul(argv[1], NULL, 0);
2649         server_id.server_id = strtoul(argv[2], NULL, 0);
2650
2651         ret = ctdb_ctrl_register_server_id(ctdb, TIMELIMIT(), &server_id);
2652         if (ret != 0) {
2653                 DEBUG(DEBUG_ERR, ("Unable to register server_id from node %u\n", options.pnn));
2654                 return ret;
2655         }
2656         DEBUG(DEBUG_ERR,("Srvid registered. Sleeping for 999 seconds\n"));
2657         sleep(999);
2658         return -1;
2659 }
2660
2661 /*
2662   unregister a server id
2663  */
2664 static int unregsrvid(struct ctdb_context *ctdb, int argc, const char **argv)
2665 {
2666         int ret;
2667         struct ctdb_client_id server_id;
2668
2669         if (argc < 3) {
2670                 usage();
2671         }
2672
2673         server_id.pnn       = strtoul(argv[0], NULL, 0);
2674         server_id.type      = strtoul(argv[1], NULL, 0);
2675         server_id.server_id = strtoul(argv[2], NULL, 0);
2676
2677         ret = ctdb_ctrl_unregister_server_id(ctdb, TIMELIMIT(), &server_id);
2678         if (ret != 0) {
2679                 DEBUG(DEBUG_ERR, ("Unable to unregister server_id from node %u\n", options.pnn));
2680                 return ret;
2681         }
2682         return -1;
2683 }
2684
2685 /*
2686   check if a server id exists
2687  */
2688 static int chksrvid(struct ctdb_context *ctdb, int argc, const char **argv)
2689 {
2690         uint32_t status = 0;
2691         int ret;
2692         struct ctdb_client_id server_id;
2693
2694         if (argc < 3) {
2695                 usage();
2696         }
2697
2698         server_id.pnn       = strtoul(argv[0], NULL, 0);
2699         server_id.type      = strtoul(argv[1], NULL, 0);
2700         server_id.server_id = strtoul(argv[2], NULL, 0);
2701
2702         ret = ctdb_ctrl_check_server_id(ctdb, TIMELIMIT(), options.pnn, &server_id, &status);
2703         if (ret != 0) {
2704                 DEBUG(DEBUG_ERR, ("Unable to check server_id from node %u\n", options.pnn));
2705                 return ret;
2706         }
2707
2708         if (status) {
2709                 printf("Server id %d:%d:%d EXISTS\n", server_id.pnn, server_id.type, server_id.server_id);
2710         } else {
2711                 printf("Server id %d:%d:%d does NOT exist\n", server_id.pnn, server_id.type, server_id.server_id);
2712         }
2713         return 0;
2714 }
2715
2716 /*
2717   get a list of all server ids that are registered on a node
2718  */
2719 static int getsrvids(struct ctdb_context *ctdb, int argc, const char **argv)
2720 {
2721         int i, ret;
2722         struct ctdb_client_id_list_old *server_ids;
2723
2724         ret = ctdb_ctrl_get_server_id_list(ctdb, ctdb, TIMELIMIT(), options.pnn, &server_ids);
2725         if (ret != 0) {
2726                 DEBUG(DEBUG_ERR, ("Unable to get server_id list from node %u\n", options.pnn));
2727                 return ret;
2728         }
2729
2730         for (i=0; i<server_ids->num; i++) {
2731                 printf("Server id %d:%d:%d\n", 
2732                         server_ids->server_ids[i].pnn, 
2733                         server_ids->server_ids[i].type, 
2734                         server_ids->server_ids[i].server_id); 
2735         }
2736
2737         return -1;
2738 }
2739
2740 /*
2741   check if a server id exists
2742  */
2743 static int check_srvids(struct ctdb_context *ctdb, int argc, const char **argv)
2744 {
2745         TALLOC_CTX *tmp_ctx = talloc_new(NULL);
2746         uint64_t *ids;
2747         uint8_t *result;
2748         int i;
2749
2750         if (argc < 1) {
2751                 talloc_free(tmp_ctx);
2752                 usage();
2753         }
2754
2755         ids    = talloc_array(tmp_ctx, uint64_t, argc);
2756         result = talloc_array(tmp_ctx, uint8_t, argc);
2757
2758         for (i = 0; i < argc; i++) {
2759                 ids[i] = strtoull(argv[i], NULL, 0);
2760         }
2761
2762         if (!ctdb_client_check_message_handlers(ctdb, ids, argc, result)) {
2763                 DEBUG(DEBUG_ERR, ("Unable to check server_id from node %u\n",
2764                                   options.pnn));
2765                 talloc_free(tmp_ctx);
2766                 return -1;
2767         }
2768
2769         for (i=0; i < argc; i++) {
2770                 printf("Server id %d:%llu %s\n", options.pnn, (long long)ids[i],
2771                        result[i] ? "exists" : "does not exist");
2772         }
2773
2774         talloc_free(tmp_ctx);
2775         return 0;
2776 }
2777
2778 /*
2779   send a tcp tickle ack
2780  */
2781 static int tickle_tcp(struct ctdb_context *ctdb, int argc, const char **argv)
2782 {
2783         int ret;
2784         ctdb_sock_addr  src, dst;
2785
2786         if (argc < 2) {
2787                 usage();
2788         }
2789
2790         if (!parse_ip_port(argv[0], &src)) {
2791                 DEBUG(DEBUG_ERR, ("Bad IP:port '%s'\n", argv[0]));
2792                 return -1;
2793         }
2794
2795         if (!parse_ip_port(argv[1], &dst)) {
2796                 DEBUG(DEBUG_ERR, ("Bad IP:port '%s'\n", argv[1]));
2797                 return -1;
2798         }
2799
2800         ret = ctdb_sys_send_tcp(&src, &dst, 0, 0, 0);
2801         if (ret==0) {
2802                 return 0;
2803         }
2804         DEBUG(DEBUG_ERR, ("Error while sending tickle ack\n"));
2805
2806         return -1;
2807 }
2808
2809
2810 /*
2811   display public ip status
2812  */
2813 static int control_ip(struct ctdb_context *ctdb, int argc, const char **argv)
2814 {
2815         int i, ret;
2816         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
2817         struct ctdb_public_ip_list_old *ips;
2818
2819         if (argc == 1 && strcmp(argv[0], "all") == 0) {
2820                 options.pnn = CTDB_BROADCAST_ALL;
2821         }
2822
2823         if (options.pnn == CTDB_BROADCAST_ALL) {
2824                 /* read the list of public ips from all nodes */
2825                 ret = control_get_all_public_ips(ctdb, tmp_ctx, &ips);
2826         } else {
2827                 /* read the public ip list from this node */
2828                 ret = ctdb_ctrl_get_public_ips(ctdb, TIMELIMIT(), options.pnn, tmp_ctx, &ips);
2829         }
2830         if (ret != 0) {
2831                 DEBUG(DEBUG_ERR, ("Unable to get public ips from node %u\n", options.pnn));
2832                 talloc_free(tmp_ctx);
2833                 return ret;
2834         }
2835
2836         if (options.machinereadable){
2837                 printm(":Public IP:Node:");
2838                 if (options.verbose){
2839                         printm("ActiveInterface:AvailableInterfaces:ConfiguredInterfaces:");
2840                 }
2841                 printm("\n");
2842         } else {
2843                 if (options.pnn == CTDB_BROADCAST_ALL) {
2844                         printf("Public IPs on ALL nodes\n");
2845                 } else {
2846                         printf("Public IPs on node %u\n", options.pnn);
2847                 }
2848         }
2849
2850         for (i=1;i<=ips->num;i++) {
2851                 struct ctdb_public_ip_info_old *info = NULL;
2852                 int32_t pnn;
2853                 char *aciface = NULL;
2854                 char *avifaces = NULL;
2855                 char *cifaces = NULL;
2856
2857                 if (options.pnn == CTDB_BROADCAST_ALL) {
2858                         pnn = ips->ips[ips->num-i].pnn;
2859                 } else {
2860                         pnn = options.pnn;
2861                 }
2862
2863                 if (pnn != -1) {
2864                         ret = ctdb_ctrl_get_public_ip_info(ctdb, TIMELIMIT(), pnn, ctdb,
2865                                                    &ips->ips[ips->num-i].addr, &info);
2866                 } else {
2867                         ret = -1;
2868                 }
2869
2870                 if (ret == 0) {
2871                         int j;
2872                         for (j=0; j < info->num; j++) {
2873                                 if (cifaces == NULL) {
2874                                         cifaces = talloc_strdup(info,
2875                                                                 info->ifaces[j].name);
2876                                 } else {
2877                                         cifaces = talloc_asprintf_append(cifaces,
2878                                                                          ",%s",
2879                                                                          info->ifaces[j].name);
2880                                 }
2881
2882                                 if (info->active_idx == j) {
2883                                         aciface = info->ifaces[j].name;
2884                                 }
2885
2886                                 if (info->ifaces[j].link_state == 0) {
2887                                         continue;
2888                                 }
2889
2890                                 if (avifaces == NULL) {
2891                                         avifaces = talloc_strdup(info, info->ifaces[j].name);
2892                                 } else {
2893                                         avifaces = talloc_asprintf_append(avifaces,
2894                                                                           ",%s",
2895                                                                           info->ifaces[j].name);
2896                                 }
2897                         }
2898                 }
2899
2900                 if (options.machinereadable){
2901                         printm(":%s:%d:",
2902                                 ctdb_addr_to_str(&ips->ips[ips->num-i].addr),
2903                                 ips->ips[ips->num-i].pnn);
2904                         if (options.verbose){
2905                                 printm("%s:%s:%s:",
2906                                         aciface?aciface:"",
2907                                         avifaces?avifaces:"",
2908                                         cifaces?cifaces:"");
2909                         }
2910                         printf("\n");
2911                 } else {
2912                         if (options.verbose) {
2913                                 printf("%s node[%d] active[%s] available[%s] configured[%s]\n",
2914                                         ctdb_addr_to_str(&ips->ips[ips->num-i].addr),
2915                                         ips->ips[ips->num-i].pnn,
2916                                         aciface?aciface:"",
2917                                         avifaces?avifaces:"",
2918                                         cifaces?cifaces:"");
2919                         } else {
2920                                 printf("%s %d\n",
2921                                         ctdb_addr_to_str(&ips->ips[ips->num-i].addr),
2922                                         ips->ips[ips->num-i].pnn);
2923                         }
2924                 }
2925                 talloc_free(info);
2926         }
2927
2928         talloc_free(tmp_ctx);
2929         return 0;
2930 }
2931
2932 /*
2933   public ip info
2934  */
2935 static int control_ipinfo(struct ctdb_context *ctdb, int argc, const char **argv)
2936 {
2937         int i, ret;
2938         ctdb_sock_addr addr;
2939         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
2940         struct ctdb_public_ip_info_old *info;
2941
2942         if (argc != 1) {
2943                 talloc_free(tmp_ctx);
2944                 usage();
2945         }
2946
2947         if (parse_ip(argv[0], NULL, 0, &addr) == 0) {
2948                 DEBUG(DEBUG_ERR,("Wrongly formed ip address '%s'\n", argv[0]));
2949                 return -1;
2950         }
2951
2952         /* read the public ip info from this node */
2953         ret = ctdb_ctrl_get_public_ip_info(ctdb, TIMELIMIT(), options.pnn,
2954                                            tmp_ctx, &addr, &info);
2955         if (ret != 0) {
2956                 DEBUG(DEBUG_ERR, ("Unable to get public ip[%s]info from node %u\n",
2957                                   argv[0], options.pnn));
2958                 talloc_free(tmp_ctx);
2959                 return ret;
2960         }
2961
2962         printf("Public IP[%s] info on node %u\n",
2963                ctdb_addr_to_str(&info->ip.addr),
2964                options.pnn);
2965
2966         printf("IP:%s\nCurrentNode:%d\nNumInterfaces:%u\n",
2967                ctdb_addr_to_str(&info->ip.addr),
2968                info->ip.pnn, info->num);
2969
2970         for (i=0; i<info->num; i++) {
2971                 info->ifaces[i].name[CTDB_IFACE_SIZE] = '\0';
2972
2973                 printf("Interface[%u]: Name:%s Link:%s References:%u%s\n",
2974                        i+1, info->ifaces[i].name,
2975                        info->ifaces[i].link_state?"up":"down",
2976                        (unsigned int)info->ifaces[i].references,
2977                        (i==info->active_idx)?" (active)":"");
2978         }
2979
2980         talloc_free(tmp_ctx);
2981         return 0;
2982 }
2983
2984 /*
2985   display interfaces status
2986  */
2987 static int control_ifaces(struct ctdb_context *ctdb, int argc, const char **argv)
2988 {
2989         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
2990         int i;
2991         struct ctdb_iface_list_old *ifaces;
2992         int ret;
2993
2994         /* read the public ip list from this node */
2995         ret = ctdb_ctrl_get_ifaces(ctdb, TIMELIMIT(), options.pnn, tmp_ctx, &ifaces);
2996         if (ret != 0) {
2997                 DEBUG(DEBUG_ERR, ("Unable to get interfaces from node %u\n",
2998                                   options.pnn));
2999                 talloc_free(tmp_ctx);
3000                 return -1;
3001         }
3002
3003         if (options.machinereadable){
3004                 printm(":Name:LinkStatus:References:\n");
3005         } else {
3006                 printf("Interfaces on node %u\n", options.pnn);
3007         }
3008
3009         for (i=0; i<ifaces->num; i++) {
3010                 if (options.machinereadable){
3011                         printm(":%s:%s:%u:\n",
3012                                ifaces->ifaces[i].name,
3013                                ifaces->ifaces[i].link_state?"1":"0",
3014                                (unsigned int)ifaces->ifaces[i].references);
3015                 } else {
3016                         printf("name:%s link:%s references:%u\n",
3017                                ifaces->ifaces[i].name,
3018                                ifaces->ifaces[i].link_state?"up":"down",
3019                                (unsigned int)ifaces->ifaces[i].references);
3020                 }
3021         }
3022
3023         talloc_free(tmp_ctx);
3024         return 0;
3025 }
3026
3027
3028 /*
3029   set link status of an interface
3030  */
3031 static int control_setifacelink(struct ctdb_context *ctdb, int argc, const char **argv)
3032 {
3033         int ret;
3034         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
3035         struct ctdb_iface info;
3036
3037         ZERO_STRUCT(info);
3038
3039         if (argc != 2) {
3040                 usage();
3041         }
3042
3043         if (strlen(argv[0]) > CTDB_IFACE_SIZE) {
3044                 DEBUG(DEBUG_ERR, ("interfaces name '%s' too long\n",
3045                                   argv[0]));
3046                 talloc_free(tmp_ctx);
3047                 return -1;
3048         }
3049         strcpy(info.name, argv[0]);
3050
3051         if (strcmp(argv[1], "up") == 0) {
3052                 info.link_state = 1;
3053         } else if (strcmp(argv[1], "down") == 0) {
3054                 info.link_state = 0;
3055         } else {
3056                 DEBUG(DEBUG_ERR, ("link state invalid '%s' should be 'up' or 'down'\n",
3057                                   argv[1]));
3058                 talloc_free(tmp_ctx);
3059                 return -1;
3060         }
3061
3062         /* read the public ip list from this node */
3063         ret = ctdb_ctrl_set_iface_link(ctdb, TIMELIMIT(), options.pnn,
3064                                    tmp_ctx, &info);
3065         if (ret != 0) {
3066                 DEBUG(DEBUG_ERR, ("Unable to set link state for interfaces %s node %u\n",
3067                                   argv[0], options.pnn));
3068                 talloc_free(tmp_ctx);
3069                 return ret;
3070         }
3071
3072         talloc_free(tmp_ctx);
3073         return 0;
3074 }
3075
3076 /*
3077   display pid of a ctdb daemon
3078  */
3079 static int control_getpid(struct ctdb_context *ctdb, int argc, const char **argv)
3080 {
3081         uint32_t pid;
3082         int ret;
3083
3084         ret = ctdb_ctrl_getpid(ctdb, TIMELIMIT(), options.pnn, &pid);
3085         if (ret != 0) {
3086                 DEBUG(DEBUG_ERR, ("Unable to get daemon pid from node %u\n", options.pnn));
3087                 return ret;
3088         }
3089         printf("Pid:%d\n", pid);
3090
3091         return 0;
3092 }
3093
3094 typedef bool update_flags_handler_t(struct ctdb_context *ctdb, void *data);
3095
3096 static int update_flags_and_ipreallocate(struct ctdb_context *ctdb,
3097                                               void *data,
3098                                               update_flags_handler_t handler,
3099                                               uint32_t flag,
3100                                               const char *desc,
3101                                               bool set_flag)
3102 {
3103         struct ctdb_node_map_old *nodemap = NULL;
3104         bool flag_is_set;
3105         int ret;
3106
3107         /* Check if the node is already in the desired state */
3108         ret = ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE, ctdb, &nodemap);
3109         if (ret != 0) {
3110                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from local node\n"));
3111                 exit(10);
3112         }
3113         flag_is_set = nodemap->nodes[options.pnn].flags & flag;
3114         if (set_flag == flag_is_set) {
3115                 DEBUG(DEBUG_NOTICE, ("Node %d is %s %s\n", options.pnn,
3116                                      (set_flag ? "already" : "not"), desc));
3117                 return 0;
3118         }
3119
3120         do {
3121                 if (!handler(ctdb, data)) {
3122                         DEBUG(DEBUG_WARNING,
3123                               ("Failed to send control to set state %s on node %u, try again\n",
3124                                desc, options.pnn));
3125                 }
3126
3127                 sleep(1);
3128
3129                 /* Read the nodemap and verify the change took effect.
3130                  * Even if the above control/hanlder timed out then it
3131                  * could still have worked!
3132                  */
3133                 ret = ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE,
3134                                          ctdb, &nodemap);
3135                 if (ret != 0) {
3136                         DEBUG(DEBUG_WARNING,
3137                               ("Unable to get nodemap from local node, try again\n"));
3138                 }
3139                 flag_is_set = nodemap->nodes[options.pnn].flags & flag;
3140         } while (nodemap == NULL || (set_flag != flag_is_set));
3141
3142         return ipreallocate(ctdb);
3143 }
3144
3145 /* Administratively disable a node */
3146 static bool update_flags_disabled(struct ctdb_context *ctdb, void *data)
3147 {
3148         int ret;
3149
3150         ret = ctdb_ctrl_modflags(ctdb, TIMELIMIT(), options.pnn,
3151                                  NODE_FLAGS_PERMANENTLY_DISABLED, 0);
3152         return ret == 0;
3153 }
3154
3155 static int control_disable(struct ctdb_context *ctdb, int argc, const char **argv)
3156 {
3157         return update_flags_and_ipreallocate(ctdb, NULL,
3158                                                   update_flags_disabled,
3159                                                   NODE_FLAGS_PERMANENTLY_DISABLED,
3160                                                   "disabled",
3161                                                   true /* set_flag*/);
3162 }
3163
3164 /* Administratively re-enable a node */
3165 static bool update_flags_not_disabled(struct ctdb_context *ctdb, void *data)
3166 {
3167         int ret;
3168
3169         ret = ctdb_ctrl_modflags(ctdb, TIMELIMIT(), options.pnn,
3170                                  0, NODE_FLAGS_PERMANENTLY_DISABLED);
3171         return ret == 0;
3172 }
3173
3174 static int control_enable(struct ctdb_context *ctdb,  int argc, const char **argv)
3175 {
3176         return update_flags_and_ipreallocate(ctdb, NULL,
3177                                                   update_flags_not_disabled,
3178                                                   NODE_FLAGS_PERMANENTLY_DISABLED,
3179                                                   "disabled",
3180                                                   false /* set_flag*/);
3181 }
3182
3183 /* Stop a node */
3184 static bool update_flags_stopped(struct ctdb_context *ctdb, void *data)
3185 {
3186         int ret;
3187
3188         ret = ctdb_ctrl_stop_node(ctdb, TIMELIMIT(), options.pnn);
3189
3190         return ret == 0;
3191 }
3192
3193 static int control_stop(struct ctdb_context *ctdb, int argc, const char **argv)
3194 {
3195         return update_flags_and_ipreallocate(ctdb, NULL,
3196                                                   update_flags_stopped,
3197                                                   NODE_FLAGS_STOPPED,
3198                                                   "stopped",
3199                                                   true /* set_flag*/);
3200 }
3201
3202 /* Continue a stopped node */
3203 static bool update_flags_not_stopped(struct ctdb_context *ctdb, void *data)
3204 {
3205         int ret;
3206
3207         ret = ctdb_ctrl_continue_node(ctdb, TIMELIMIT(), options.pnn);
3208
3209         return ret == 0;
3210 }
3211
3212 static int control_continue(struct ctdb_context *ctdb, int argc, const char **argv)
3213 {
3214         return update_flags_and_ipreallocate(ctdb, NULL,
3215                                                   update_flags_not_stopped,
3216                                                   NODE_FLAGS_STOPPED,
3217                                                   "stopped",
3218                                                   false /* set_flag */);
3219 }
3220
3221 static uint32_t get_generation(struct ctdb_context *ctdb)
3222 {
3223         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
3224         struct ctdb_vnn_map *vnnmap=NULL;
3225         int ret;
3226         uint32_t generation;
3227
3228         /* wait until the recmaster is not in recovery mode */
3229         while (1) {
3230                 uint32_t recmode, recmaster;
3231                 
3232                 if (vnnmap != NULL) {
3233                         talloc_free(vnnmap);
3234                         vnnmap = NULL;
3235                 }
3236
3237                 /* get the recmaster */
3238                 ret = ctdb_ctrl_getrecmaster(ctdb, tmp_ctx, TIMELIMIT(), CTDB_CURRENT_NODE, &recmaster);
3239                 if (ret != 0) {
3240                         DEBUG(DEBUG_ERR, ("Unable to get recmaster from node %u\n", options.pnn));
3241                         talloc_free(tmp_ctx);
3242                         exit(10);
3243                 }
3244
3245                 /* get recovery mode */
3246                 ret = ctdb_ctrl_getrecmode(ctdb, tmp_ctx, TIMELIMIT(), recmaster, &recmode);
3247                 if (ret != 0) {
3248                         DEBUG(DEBUG_ERR, ("Unable to get recmode from node %u\n", options.pnn));
3249                         talloc_free(tmp_ctx);
3250                         exit(10);
3251                 }
3252
3253                 /* get the current generation number */
3254                 ret = ctdb_ctrl_getvnnmap(ctdb, TIMELIMIT(), recmaster, tmp_ctx, &vnnmap);
3255                 if (ret != 0) {
3256                         DEBUG(DEBUG_ERR, ("Unable to get vnnmap from recmaster (%u)\n", recmaster));
3257                         talloc_free(tmp_ctx);
3258                         exit(10);
3259                 }
3260
3261                 if ((recmode == CTDB_RECOVERY_NORMAL) && (vnnmap->generation != 1)) {
3262                         generation = vnnmap->generation;
3263                         talloc_free(tmp_ctx);
3264                         return generation;
3265                 }
3266                 sleep(1);
3267         }
3268 }
3269
3270 /* Ban a node */
3271 static bool update_state_banned(struct ctdb_context *ctdb, void *data)
3272 {
3273         struct ctdb_ban_state *bantime = (struct ctdb_ban_state *)data;
3274         int ret;
3275
3276         ret = ctdb_ctrl_set_ban(ctdb, TIMELIMIT(), options.pnn, bantime);
3277
3278         return ret == 0;
3279 }
3280
3281 static int control_ban(struct ctdb_context *ctdb, int argc, const char **argv)
3282 {
3283         struct ctdb_ban_state bantime;
3284
3285         if (argc < 1) {
3286                 usage();
3287         }
3288         
3289         bantime.pnn  = options.pnn;
3290         bantime.time = strtoul(argv[0], NULL, 0);
3291
3292         if (bantime.time == 0) {
3293                 DEBUG(DEBUG_ERR, ("Invalid ban time specified - must be >0\n"));
3294                 return -1;
3295         }
3296
3297         return update_flags_and_ipreallocate(ctdb, &bantime,
3298                                                   update_state_banned,
3299                                                   NODE_FLAGS_BANNED,
3300                                                   "banned",
3301                                                   true /* set_flag*/);
3302 }
3303
3304
3305 /* Unban a node */
3306 static int control_unban(struct ctdb_context *ctdb, int argc, const char **argv)
3307 {
3308         struct ctdb_ban_state bantime;
3309
3310         bantime.pnn  = options.pnn;
3311         bantime.time = 0;
3312
3313         return update_flags_and_ipreallocate(ctdb, &bantime,
3314                                                   update_state_banned,
3315                                                   NODE_FLAGS_BANNED,
3316                                                   "banned",
3317                                                   false /* set_flag*/);
3318 }
3319
3320 /*
3321   show ban information for a node
3322  */
3323 static int control_showban(struct ctdb_context *ctdb, int argc, const char **argv)
3324 {
3325         int ret;
3326         struct ctdb_node_map_old *nodemap=NULL;
3327         struct ctdb_ban_state *bantime;
3328
3329         /* verify the node exists */
3330         ret = ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE, ctdb, &nodemap);
3331         if (ret != 0) {
3332                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from local node\n"));
3333                 return ret;
3334         }
3335
3336         ret = ctdb_ctrl_get_ban(ctdb, TIMELIMIT(), options.pnn, ctdb, &bantime);
3337         if (ret != 0) {
3338                 DEBUG(DEBUG_ERR,("Showing ban info for node %d failed.\n", options.pnn));
3339                 return -1;
3340         }       
3341
3342         if (bantime->time == 0) {
3343                 printf("Node %u is not banned\n", bantime->pnn);
3344         } else {
3345                 printf("Node %u is banned, %d seconds remaining\n",
3346                        bantime->pnn, bantime->time);
3347         }
3348
3349         return 0;
3350 }
3351
3352 /*
3353   shutdown a daemon
3354  */
3355 static int control_shutdown(struct ctdb_context *ctdb, int argc, const char **argv)
3356 {
3357         int ret;
3358
3359         ret = ctdb_ctrl_shutdown(ctdb, TIMELIMIT(), options.pnn);
3360         if (ret != 0) {
3361                 DEBUG(DEBUG_ERR, ("Unable to shutdown node %u\n", options.pnn));
3362                 return ret;
3363         }
3364
3365         return 0;
3366 }
3367
3368 /*
3369   trigger a recovery
3370  */
3371 static int control_recover(struct ctdb_context *ctdb, int argc, const char **argv)
3372 {
3373         int ret;
3374         uint32_t generation, next_generation;
3375
3376         /* record the current generation number */
3377         generation = get_generation(ctdb);
3378
3379         ret = ctdb_ctrl_setrecmode(ctdb, TIMELIMIT(), options.pnn, CTDB_RECOVERY_ACTIVE);
3380         if (ret != 0) {
3381                 DEBUG(DEBUG_ERR, ("Unable to set recovery mode\n"));
3382                 return ret;
3383         }
3384
3385         /* wait until we are in a new generation */
3386         while (1) {
3387                 next_generation = get_generation(ctdb);
3388                 if (next_generation != generation) {
3389                         return 0;
3390                 }
3391                 sleep(1);
3392         }
3393
3394         return 0;
3395 }
3396
3397
3398 /*
3399   display monitoring mode of a remote node
3400  */
3401 static int control_getmonmode(struct ctdb_context *ctdb, int argc, const char **argv)
3402 {
3403         uint32_t monmode;
3404         int ret;
3405
3406         ret = ctdb_ctrl_getmonmode(ctdb, TIMELIMIT(), options.pnn, &monmode);
3407         if (ret != 0) {
3408                 DEBUG(DEBUG_ERR, ("Unable to get monmode from node %u\n", options.pnn));
3409                 return ret;
3410         }
3411         if (!options.machinereadable){
3412                 printf("Monitoring mode:%s (%d)\n",monmode==CTDB_MONITORING_ACTIVE?"ACTIVE":"DISABLED",monmode);
3413         } else {
3414                 printm(":mode:\n");
3415                 printm(":%d:\n",monmode);
3416         }
3417         return 0;
3418 }
3419
3420
3421 /*
3422   display capabilities of a remote node
3423  */
3424 static int control_getcapabilities(struct ctdb_context *ctdb, int argc, const char **argv)
3425 {
3426         uint32_t capabilities;
3427         int ret;
3428
3429         ret = ctdb_ctrl_getcapabilities(ctdb, TIMELIMIT(), options.pnn, &capabilities);
3430         if (ret != 0) {
3431                 DEBUG(DEBUG_ERR, ("Unable to get capabilities from node %u\n", options.pnn));
3432                 return -1;
3433         }
3434
3435         if (!options.machinereadable){
3436                 printf("RECMASTER: %s\n", (capabilities&CTDB_CAP_RECMASTER)?"YES":"NO");
3437                 printf("LMASTER: %s\n", (capabilities&CTDB_CAP_LMASTER)?"YES":"NO");
3438                 printf("LVS: %s\n", (capabilities&CTDB_CAP_LVS)?"YES":"NO");
3439         } else {
3440                 printm(":RECMASTER:LMASTER:LVS:\n");
3441                 printm(":%d:%d:%d:\n",
3442                         !!(capabilities&CTDB_CAP_RECMASTER),
3443                         !!(capabilities&CTDB_CAP_LMASTER),
3444                         !!(capabilities&CTDB_CAP_LVS));
3445         }
3446         return 0;
3447 }
3448
3449 /*
3450   display lvs configuration
3451  */
3452
3453 static uint32_t lvs_exclude_flags[] = {
3454         /* Look for a nice healthy node */
3455         NODE_FLAGS_INACTIVE|NODE_FLAGS_DISABLED,
3456         /* If not found, an UNHEALTHY node will do */
3457         NODE_FLAGS_INACTIVE|NODE_FLAGS_PERMANENTLY_DISABLED,
3458         0,
3459 };
3460
3461 static int control_lvs(struct ctdb_context *ctdb, int argc, const char **argv)
3462 {
3463         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
3464         struct ctdb_node_map_old *orig_nodemap=NULL;
3465         struct ctdb_node_map_old *nodemap;
3466         int i, ret;
3467
3468         ret = ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), options.pnn,
3469                                    tmp_ctx, &orig_nodemap);
3470         if (ret != 0) {
3471                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from node %u\n", options.pnn));
3472                 talloc_free(tmp_ctx);
3473                 return -1;
3474         }
3475
3476         nodemap = filter_nodemap_by_capabilities(ctdb, orig_nodemap,
3477                                                  CTDB_CAP_LVS, false);
3478         if (nodemap == NULL) {
3479                 /* No memory */
3480                 ret = -1;
3481                 goto done;
3482         }
3483
3484         ret = 0;
3485
3486         for (i = 0; lvs_exclude_flags[i] != 0; i++) {
3487                 struct ctdb_node_map_old *t =
3488                         filter_nodemap_by_flags(ctdb, nodemap,
3489                                                 lvs_exclude_flags[i]);
3490                 if (t == NULL) {
3491                         /* No memory */
3492                         ret = -1;
3493                         goto done;
3494                 }
3495                 if (t->num > 0) {
3496                         /* At least 1 node without excluded flags */
3497                         int j;
3498                         for (j = 0; j < t->num; j++) {
3499                                 printf("%d:%s\n", t->nodes[j].pnn, 
3500                                        ctdb_addr_to_str(&t->nodes[j].addr));
3501                         }
3502                         goto done;
3503                 }
3504                 talloc_free(t);
3505         }
3506 done:
3507         talloc_free(tmp_ctx);
3508         return ret;
3509 }
3510
3511 /*
3512   display who is the lvs master
3513  */
3514 static int control_lvsmaster(struct ctdb_context *ctdb, int argc, const char **argv)
3515 {
3516         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
3517         struct ctdb_node_map_old *nodemap=NULL;
3518         int i, ret;
3519
3520         ret = ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), options.pnn,
3521                                    tmp_ctx, &nodemap);
3522         if (ret != 0) {
3523                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from node %u\n", options.pnn));
3524                 talloc_free(tmp_ctx);
3525                 return -1;
3526         }
3527
3528         for (i = 0; lvs_exclude_flags[i] != 0; i++) {
3529                 struct ctdb_node_map_old *t =
3530                         filter_nodemap_by_flags(ctdb, nodemap,
3531                                                 lvs_exclude_flags[i]);
3532                 if (t == NULL) {
3533                         /* No memory */
3534                         ret = -1;
3535                         goto done;
3536                 }
3537                 if (t->num > 0) {
3538                         struct ctdb_node_map_old *n;
3539                         n = filter_nodemap_by_capabilities(ctdb,
3540                                                            t,
3541                                                            CTDB_CAP_LVS,
3542                                                            true);
3543                         if (n == NULL) {
3544                                 /* No memory */
3545                                 ret = -1;
3546                                 goto done;
3547                         }
3548                         if (n->num > 0) {
3549                                 ret = 0;
3550                                 if (options.machinereadable) {
3551                                         printm("%d\n", n->nodes[0].pnn);
3552                                 } else {
3553                                         printf("Node %d is LVS master\n", n->nodes[0].pnn);
3554                                 }
3555                                 goto done;
3556                         }
3557                 }
3558                 talloc_free(t);
3559         }
3560
3561         printf("There is no LVS master\n");
3562         ret = 255;
3563 done:
3564         talloc_free(tmp_ctx);
3565         return ret;
3566 }
3567
3568 /*
3569   disable monitoring on a  node
3570  */
3571 static int control_disable_monmode(struct ctdb_context *ctdb, int argc, const char **argv)
3572 {
3573         
3574         int ret;
3575
3576         ret = ctdb_ctrl_disable_monmode(ctdb, TIMELIMIT(), options.pnn);
3577         if (ret != 0) {
3578                 DEBUG(DEBUG_ERR, ("Unable to disable monmode on node %u\n", options.pnn));
3579                 return ret;
3580         }
3581         printf("Monitoring mode:%s\n","DISABLED");
3582
3583         return 0;
3584 }
3585
3586 /*
3587   enable monitoring on a  node
3588  */
3589 static int control_enable_monmode(struct ctdb_context *ctdb, int argc, const char **argv)
3590 {
3591         
3592         int ret;
3593
3594         ret = ctdb_ctrl_enable_monmode(ctdb, TIMELIMIT(), options.pnn);
3595         if (ret != 0) {
3596                 DEBUG(DEBUG_ERR, ("Unable to enable monmode on node %u\n", options.pnn));
3597                 return ret;
3598         }
3599         printf("Monitoring mode:%s\n","ACTIVE");
3600
3601         return 0;
3602 }
3603
3604 /*
3605   display remote list of keys/data for a db
3606  */
3607 static int control_catdb(struct ctdb_context *ctdb, int argc, const char **argv)
3608 {
3609         const char *db_name;
3610         struct ctdb_db_context *ctdb_db;
3611         int ret;
3612         struct ctdb_dump_db_context c;
3613         uint8_t flags;
3614
3615         if (argc < 1) {
3616                 usage();
3617         }
3618
3619         if (!db_exists(ctdb, argv[0], NULL, &db_name, &flags)) {
3620                 return -1;
3621         }
3622
3623         ctdb_db = ctdb_attach(ctdb, TIMELIMIT(), db_name, flags & CTDB_DB_FLAGS_PERSISTENT, 0);
3624         if (ctdb_db == NULL) {
3625                 DEBUG(DEBUG_ERR,("Unable to attach to database '%s'\n", db_name));
3626                 return -1;
3627         }
3628
3629         if (options.printlmaster) {
3630                 ret = ctdb_ctrl_getvnnmap(ctdb, TIMELIMIT(), options.pnn,
3631                                           ctdb, &ctdb->vnn_map);
3632                 if (ret != 0) {
3633                         DEBUG(DEBUG_ERR, ("Unable to get vnnmap from node %u\n",
3634                                           options.pnn));
3635                         return ret;
3636                 }
3637         }
3638
3639         ZERO_STRUCT(c);
3640         c.ctdb = ctdb;
3641         c.f = stdout;
3642         c.printemptyrecords = (bool)options.printemptyrecords;
3643         c.printdatasize = (bool)options.printdatasize;
3644         c.printlmaster = (bool)options.printlmaster;
3645         c.printhash = (bool)options.printhash;
3646         c.printrecordflags = (bool)options.printrecordflags;
3647
3648         /* traverse and dump the cluster tdb */
3649         ret = ctdb_dump_db(ctdb_db, &c);
3650         if (ret == -1) {
3651                 DEBUG(DEBUG_ERR, ("Unable to dump database\n"));
3652                 DEBUG(DEBUG_ERR, ("Maybe try 'ctdb getdbstatus %s'"
3653                                   " and 'ctdb getvar AllowUnhealthyDBRead'\n",
3654                                   db_name));
3655                 return -1;
3656         }
3657         talloc_free(ctdb_db);
3658
3659         printf("Dumped %d records\n", ret);
3660         return 0;
3661 }
3662
3663 struct cattdb_data {
3664         struct ctdb_context *ctdb;
3665         uint32_t count;
3666 };
3667
3668 static int cattdb_traverse(struct tdb_context *tdb, TDB_DATA key, TDB_DATA data, void *private_data)
3669 {
3670         struct cattdb_data *d = private_data;
3671         struct ctdb_dump_db_context c;
3672
3673         d->count++;
3674
3675         ZERO_STRUCT(c);
3676         c.ctdb = d->ctdb;
3677         c.f = stdout;
3678         c.printemptyrecords = (bool)options.printemptyrecords;
3679         c.printdatasize = (bool)options.printdatasize;
3680         c.printlmaster = false;
3681         c.printhash = (bool)options.printhash;
3682         c.printrecordflags = true;
3683
3684         return ctdb_dumpdb_record(key, data, &c);
3685 }
3686
3687 /*
3688   cat the local tdb database using same format as catdb
3689  */
3690 static int control_cattdb(struct ctdb_context *ctdb, int argc, const char **argv)
3691 {
3692         const char *db_name;
3693         struct ctdb_db_context *ctdb_db;
3694         struct cattdb_data d;
3695         uint8_t flags;
3696
3697         if (argc < 1) {
3698                 usage();
3699         }
3700
3701         if (!db_exists(ctdb, argv[0], NULL, &db_name, &flags)) {
3702                 return -1;
3703         }
3704
3705         ctdb_db = ctdb_attach(ctdb, TIMELIMIT(), db_name, flags & CTDB_DB_FLAGS_PERSISTENT, 0);
3706         if (ctdb_db == NULL) {
3707                 DEBUG(DEBUG_ERR,("Unable to attach to database '%s'\n", db_name));
3708                 return -1;
3709         }
3710
3711         /* traverse the local tdb */
3712         d.count = 0;
3713         d.ctdb  = ctdb;
3714         if (tdb_traverse_read(ctdb_db->ltdb->tdb, cattdb_traverse, &d) == -1) {
3715                 printf("Failed to cattdb data\n");
3716                 exit(10);
3717         }
3718         talloc_free(ctdb_db);
3719
3720         printf("Dumped %d records\n", d.count);
3721         return 0;
3722 }
3723
3724 /*
3725   display the content of a database key
3726  */
3727 static int control_readkey(struct ctdb_context *ctdb, int argc, const char **argv)
3728 {
3729         const char *db_name;
3730         struct ctdb_db_context *ctdb_db;
3731         struct ctdb_record_handle *h;
3732         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
3733         TDB_DATA key, data;
3734         uint8_t flags;
3735
3736         if (argc < 2) {
3737                 usage();
3738         }
3739
3740         if (!db_exists(ctdb, argv[0], NULL, &db_name, &flags)) {
3741                 return -1;
3742         }
3743
3744         ctdb_db = ctdb_attach(ctdb, TIMELIMIT(), db_name, flags & CTDB_DB_FLAGS_PERSISTENT, 0);
3745         if (ctdb_db == NULL) {
3746                 DEBUG(DEBUG_ERR,("Unable to attach to database '%s'\n", db_name));
3747                 return -1;
3748         }
3749
3750         key.dptr  = discard_const(argv[1]);
3751         key.dsize = strlen((char *)key.dptr);
3752
3753         h = ctdb_fetch_lock(ctdb_db, tmp_ctx, key, &data);
3754         if (h == NULL) {
3755                 printf("Failed to fetch record '%s' on node %d\n", 
3756                         (const char *)key.dptr, ctdb_get_pnn(ctdb));
3757                 talloc_free(tmp_ctx);
3758                 exit(10);
3759         }
3760
3761         printf("Data: size:%d ptr:[%.*s]\n", (int)data.dsize, (int)data.dsize, data.dptr);
3762
3763         talloc_free(tmp_ctx);
3764         talloc_free(ctdb_db);
3765         return 0;
3766 }
3767
3768 /*
3769   display the content of a database key
3770  */
3771 static int control_writekey(struct ctdb_context *ctdb, int argc, const char **argv)
3772 {
3773         const char *db_name;
3774         struct ctdb_db_context *ctdb_db;
3775         struct ctdb_record_handle *h;
3776         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
3777         TDB_DATA key, data;
3778         uint8_t flags;
3779
3780         if (argc < 3) {
3781                 usage();
3782         }
3783
3784         if (!db_exists(ctdb, argv[0], NULL, &db_name, &flags)) {
3785                 return -1;
3786         }
3787
3788         ctdb_db = ctdb_attach(ctdb, TIMELIMIT(), db_name, flags & CTDB_DB_FLAGS_PERSISTENT, 0);
3789         if (ctdb_db == NULL) {
3790                 DEBUG(DEBUG_ERR,("Unable to attach to database '%s'\n", db_name));
3791                 return -1;
3792         }
3793
3794         key.dptr  = discard_const(argv[1]);
3795         key.dsize = strlen((char *)key.dptr);
3796
3797         h = ctdb_fetch_lock(ctdb_db, tmp_ctx, key, &data);
3798         if (h == NULL) {
3799                 printf("Failed to fetch record '%s' on node %d\n", 
3800                         (const char *)key.dptr, ctdb_get_pnn(ctdb));
3801                 talloc_free(tmp_ctx);
3802                 exit(10);
3803         }
3804
3805         data.dptr  = discard_const(argv[2]);
3806         data.dsize = strlen((char *)data.dptr);
3807
3808         if (ctdb_record_store(h, data) != 0) {
3809                 printf("Failed to store record\n");
3810         }
3811
3812         talloc_free(h);
3813         talloc_free(tmp_ctx);
3814         talloc_free(ctdb_db);
3815         return 0;
3816 }
3817
3818 /*
3819   fetch a record from a persistent database
3820  */
3821 static int control_pfetch(struct ctdb_context *ctdb, int argc, const char **argv)
3822 {
3823         const char *db_name;
3824         struct ctdb_db_context *ctdb_db;
3825         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
3826         struct ctdb_transaction_handle *h;
3827         TDB_DATA key, data;
3828         int fd, ret;
3829         bool persistent;
3830         uint8_t flags;
3831
3832         if (argc < 2) {
3833                 talloc_free(tmp_ctx);
3834                 usage();
3835         }
3836
3837         if (!db_exists(ctdb, argv[0], NULL, &db_name, &flags)) {
3838                 talloc_free(tmp_ctx);
3839                 return -1;
3840         }
3841
3842         persistent = flags & CTDB_DB_FLAGS_PERSISTENT;
3843         if (!persistent) {
3844                 DEBUG(DEBUG_ERR,("Database '%s' is not persistent\n", db_name));
3845                 talloc_free(tmp_ctx);
3846                 return -1;
3847         }
3848
3849         ctdb_db = ctdb_attach(ctdb, TIMELIMIT(), db_name, persistent, 0);
3850         if (ctdb_db == NULL) {
3851                 DEBUG(DEBUG_ERR,("Unable to attach to database '%s'\n", db_name));
3852                 talloc_free(tmp_ctx);
3853                 return -1;
3854         }
3855
3856         h = ctdb_transaction_start(ctdb_db, tmp_ctx);
3857         if (h == NULL) {
3858                 DEBUG(DEBUG_ERR,("Failed to start transaction on database %s\n", db_name));
3859                 talloc_free(tmp_ctx);
3860                 return -1;
3861         }
3862
3863         key.dptr  = discard_const(argv[1]);
3864         key.dsize = strlen(argv[1]);
3865         ret = ctdb_transaction_fetch(h, tmp_ctx, key, &data);
3866         if (ret != 0) {
3867                 DEBUG(DEBUG_ERR,("Failed to fetch record\n"));
3868                 talloc_free(tmp_ctx);
3869                 return -1;
3870         }
3871
3872         if (data.dsize == 0 || data.dptr == NULL) {
3873                 DEBUG(DEBUG_ERR,("Record is empty\n"));
3874                 talloc_free(tmp_ctx);
3875                 return -1;
3876         }
3877
3878         if (argc == 3) {
3879           fd = open(argv[2], O_WRONLY|O_CREAT|O_TRUNC, 0600);
3880                 if (fd == -1) {
3881                         DEBUG(DEBUG_ERR,("Failed to open output file %s\n", argv[2]));
3882                         talloc_free(tmp_ctx);
3883                         return -1;
3884                 }
3885                 sys_write(fd, data.dptr, data.dsize);
3886                 close(fd);
3887         } else {
3888                 sys_write(1, data.dptr, data.dsize);
3889         }
3890
3891         /* abort the transaction */
3892         talloc_free(h);
3893
3894
3895         talloc_free(tmp_ctx);
3896         return 0;
3897 }
3898
3899 /*
3900   fetch a record from a tdb-file
3901  */
3902 static int control_tfetch(struct ctdb_context *ctdb, int argc, const char **argv)
3903 {
3904         const char *tdb_file;
3905         TDB_CONTEXT *tdb;
3906         TDB_DATA key, data;
3907         TALLOC_CTX *tmp_ctx = talloc_new(NULL);
3908         int fd;
3909
3910         if (argc < 2) {
3911                 usage();
3912         }
3913
3914         tdb_file = argv[0];
3915
3916         tdb = tdb_open(tdb_file, 0, 0, O_RDONLY, 0);
3917         if (tdb == NULL) {
3918                 printf("Failed to open TDB file %s\n", tdb_file);
3919                 return -1;
3920         }
3921
3922         key = strtodata(tmp_ctx, argv[1], strlen(argv[1]));
3923         if (key.dptr == NULL) {
3924                 printf("Failed to convert \"%s\" into a TDB_DATA\n", argv[1]);
3925                 return -1;
3926         }
3927
3928         data = tdb_fetch(tdb, key);
3929         if (data.dptr == NULL || data.dsize < sizeof(struct ctdb_ltdb_header)) {
3930                 printf("Failed to read record %s from tdb %s\n", argv[1], tdb_file);
3931                 tdb_close(tdb);
3932                 return -1;
3933         }
3934
3935         tdb_close(tdb);
3936
3937         if (argc == 3) {
3938           fd = open(argv[2], O_WRONLY|O_CREAT|O_TRUNC, 0600);
3939                 if (fd == -1) {
3940                         printf("Failed to open output file %s\n", argv[2]);
3941                         return -1;
3942                 }
3943                 if (options.verbose){
3944                         sys_write(fd, data.dptr, data.dsize);
3945                 } else {
3946                         sys_write(fd, data.dptr+sizeof(struct ctdb_ltdb_header), data.dsize-sizeof(struct ctdb_ltdb_header));
3947                 }
3948                 close(fd);
3949         } else {
3950                 if (options.verbose){
3951                         sys_write(1, data.dptr, data.dsize);
3952                 } else {
3953                         sys_write(1, data.dptr+sizeof(struct ctdb_ltdb_header), data.dsize-sizeof(struct ctdb_ltdb_header));
3954                 }
3955         }
3956
3957         talloc_free(tmp_ctx);
3958         return 0;
3959 }
3960
3961 /*
3962   store a record and header to a tdb-file
3963  */
3964 static int control_tstore(struct ctdb_context *ctdb, int argc, const char **argv)
3965 {
3966         const char *tdb_file;
3967         TDB_CONTEXT *tdb;
3968         TDB_DATA key, value, data;
3969         TALLOC_CTX *tmp_ctx = talloc_new(NULL);
3970         struct ctdb_ltdb_header header;
3971
3972         if (argc < 3) {
3973                 usage();
3974         }
3975
3976         tdb_file = argv[0];
3977
3978         tdb = tdb_open(tdb_file, 0, 0, O_RDWR, 0);
3979         if (tdb == NULL) {
3980                 printf("Failed to open TDB file %s\n", tdb_file);
3981                 return -1;
3982         }
3983
3984         key = strtodata(tmp_ctx, argv[1], strlen(argv[1]));
3985         if (key.dptr == NULL) {
3986                 printf("Failed to convert \"%s\" into a TDB_DATA\n", argv[1]);
3987                 return -1;
3988         }
3989
3990         value = strtodata(tmp_ctx, argv[2], strlen(argv[2]));
3991         if (value.dptr == NULL) {
3992                 printf("Failed to convert \"%s\" into a TDB_DATA\n", argv[2]);
3993                 return -1;
3994         }
3995
3996         ZERO_STRUCT(header);
3997         if (argc > 3) {
3998                 header.rsn = atoll(argv[3]);
3999         }
4000         if (argc > 4) {
4001                 header.dmaster = atoi(argv[4]);
4002         }
4003         if (argc > 5) {
4004                 header.flags = atoi(argv[5]);
4005         }
4006
4007         data.dsize = sizeof(struct ctdb_ltdb_header) + value.dsize;
4008         data.dptr = talloc_size(tmp_ctx, data.dsize);
4009         if (data.dptr == NULL) {
4010                 printf("Failed to allocate header+value\n");
4011                 return -1;
4012         }
4013
4014         *(struct ctdb_ltdb_header *)data.dptr = header;
4015         memcpy(data.dptr + sizeof(struct ctdb_ltdb_header), value.dptr, value.dsize);
4016
4017         if (tdb_store(tdb, key, data, TDB_REPLACE) != 0) {
4018                 printf("Failed to write record %s to tdb %s\n", argv[1], tdb_file);
4019                 tdb_close(tdb);
4020                 return -1;
4021         }
4022
4023         tdb_close(tdb);
4024
4025         talloc_free(tmp_ctx);
4026         return 0;
4027 }
4028
4029 /*
4030   write a record to a persistent database
4031  */
4032 static int control_pstore(struct ctdb_context *ctdb, int argc, const char **argv)
4033 {
4034         const char *db_name;
4035         struct ctdb_db_context *ctdb_db;
4036         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
4037         struct ctdb_transaction_handle *h;
4038         struct stat st;
4039         TDB_DATA key, data;
4040         int fd, ret;
4041
4042         if (argc < 3) {
4043                 talloc_free(tmp_ctx);
4044                 usage();
4045         }
4046
4047         fd = open(argv[2], O_RDONLY);
4048         if (fd == -1) {
4049                 DEBUG(DEBUG_ERR,("Failed to open file containing record data : %s  %s\n", argv[2], strerror(errno)));
4050                 talloc_free(tmp_ctx);
4051                 return -1;
4052         }
4053         
4054         ret = fstat(fd, &st);
4055         if (ret == -1) {
4056                 DEBUG(DEBUG_ERR,("fstat of file %s failed: %s\n", argv[2], strerror(errno)));
4057                 close(fd);
4058                 talloc_free(tmp_ctx);
4059                 return -1;
4060         }
4061
4062         if (!S_ISREG(st.st_mode)) {
4063                 DEBUG(DEBUG_ERR,("Not a regular file %s\n", argv[2]));
4064                 close(fd);
4065                 talloc_free(tmp_ctx);
4066                 return -1;
4067         }
4068
4069         data.dsize = st.st_size;
4070         if (data.dsize == 0) {
4071                 data.dptr  = NULL;
4072         } else {
4073                 data.dptr = talloc_size(tmp_ctx, data.dsize);
4074                 if (data.dptr == NULL) {
4075                         DEBUG(DEBUG_ERR,("Failed to talloc %d of memory to store record data\n", (int)data.dsize));
4076                         close(fd);
4077                         talloc_free(tmp_ctx);
4078                         return -1;
4079                 }
4080                 ret = sys_read(fd, data.dptr, data.dsize);
4081                 if (ret != data.dsize) {
4082                         DEBUG(DEBUG_ERR,("Failed to read %d bytes of record data\n", (int)data.dsize));
4083                         close(fd);
4084                         talloc_free(tmp_ctx);
4085                         return -1;
4086                 }
4087         }
4088         close(fd);
4089
4090
4091         db_name = argv[0];
4092
4093         ctdb_db = ctdb_attach(ctdb, TIMELIMIT(), db_name, true, 0);
4094         if (ctdb_db == NULL) {
4095                 DEBUG(DEBUG_ERR,("Unable to attach to database '%s'\n", db_name));
4096                 talloc_free(tmp_ctx);
4097                 return -1;
4098         }
4099
4100         h = ctdb_transaction_start(ctdb_db, tmp_ctx);
4101         if (h == NULL) {
4102                 DEBUG(DEBUG_ERR,("Failed to start transaction on database %s\n", db_name));
4103                 talloc_free(tmp_ctx);
4104                 return -1;
4105         }
4106
4107         key = strtodata(tmp_ctx, argv[1], strlen(argv[1]));
4108         if (key.dptr == NULL) {
4109                 printf("Failed to convert \"%s\" into a TDB_DATA\n", argv[1]);
4110                 return -1;
4111         }
4112
4113         ret = ctdb_transaction_store(h, key, data);
4114         if (ret != 0) {
4115                 DEBUG(DEBUG_ERR,("Failed to store record\n"));
4116                 talloc_free(tmp_ctx);
4117                 return -1;
4118         }
4119
4120         ret = ctdb_transaction_commit(h);
4121         if (ret != 0) {
4122                 DEBUG(DEBUG_ERR,("Failed to commit transaction\n"));
4123                 talloc_free(tmp_ctx);
4124                 return -1;
4125         }
4126
4127
4128         talloc_free(tmp_ctx);
4129         return 0;
4130 }
4131
4132 /*
4133  * delete a record from a persistent database
4134  */
4135 static int control_pdelete(struct ctdb_context *ctdb, int argc, const char **argv)
4136 {
4137         const char *db_name;
4138         struct ctdb_db_context *ctdb_db;
4139         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
4140         struct ctdb_transaction_handle *h;
4141         TDB_DATA key;
4142         int ret;
4143         bool persistent;
4144         uint8_t flags;
4145
4146         if (argc < 2) {
4147                 talloc_free(tmp_ctx);
4148                 usage();
4149         }
4150
4151         if (!db_exists(ctdb, argv[0], NULL, &db_name, &flags)) {
4152                 talloc_free(tmp_ctx);
4153                 return -1;
4154         }
4155
4156         persistent = flags & CTDB_DB_FLAGS_PERSISTENT;
4157         if (!persistent) {
4158                 DEBUG(DEBUG_ERR, ("Database '%s' is not persistent\n", db_name));
4159                 talloc_free(tmp_ctx);
4160                 return -1;
4161         }
4162
4163         ctdb_db = ctdb_attach(ctdb, TIMELIMIT(), db_name, persistent, 0);
4164         if (ctdb_db == NULL) {
4165                 DEBUG(DEBUG_ERR, ("Unable to attach to database '%s'\n", db_name));
4166                 talloc_free(tmp_ctx);
4167                 return -1;
4168         }
4169
4170         h = ctdb_transaction_start(ctdb_db, tmp_ctx);
4171         if (h == NULL) {
4172                 DEBUG(DEBUG_ERR, ("Failed to start transaction on database %s\n", db_name));
4173                 talloc_free(tmp_ctx);
4174                 return -1;
4175         }
4176
4177         key = strtodata(tmp_ctx, argv[1], strlen(argv[1]));
4178         if (key.dptr == NULL) {
4179                 printf("Failed to convert \"%s\" into a TDB_DATA\n", argv[1]);
4180                 return -1;
4181         }
4182
4183         ret = ctdb_transaction_store(h, key, tdb_null);
4184         if (ret != 0) {
4185                 DEBUG(DEBUG_ERR, ("Failed to delete record\n"));
4186                 talloc_free(tmp_ctx);
4187                 return -1;
4188         }
4189
4190         ret = ctdb_transaction_commit(h);
4191         if (ret != 0) {
4192                 DEBUG(DEBUG_ERR, ("Failed to commit transaction\n"));
4193                 talloc_free(tmp_ctx);
4194                 return -1;
4195         }
4196
4197         talloc_free(tmp_ctx);
4198         return 0;
4199 }
4200
4201 static const char *ptrans_parse_string(TALLOC_CTX *mem_ctx, const char *s,
4202                                        TDB_DATA *data)
4203 {
4204         const char *t;
4205         size_t n;
4206         const char *ret; /* Next byte after successfully parsed value */
4207
4208         /* Error, unless someone says otherwise */
4209         ret = NULL;
4210         /* Indicates no value to parse */
4211         *data = tdb_null;
4212
4213         /* Skip whitespace */
4214         n = strspn(s, " \t");
4215         t = s + n;
4216
4217         if (t[0] == '"') {
4218                 /* Quoted ASCII string - no wide characters! */
4219                 t++;
4220                 n = strcspn(t, "\"");
4221                 if (t[n] == '"') {
4222                         if (n > 0) {
4223                                 *data = strtodata(mem_ctx, t, n);
4224                                 CTDB_NOMEM_ABORT(data->dptr);
4225                         }
4226                         ret = t + n + 1;
4227                 } else {
4228                         DEBUG(DEBUG_WARNING,("Unmatched \" in input %s\n", s));
4229                 }
4230         } else {
4231                 DEBUG(DEBUG_WARNING,("Unsupported input format in %s\n", s));
4232         }
4233
4234         return ret;
4235 }
4236
4237 static bool ptrans_get_key_value(TALLOC_CTX *mem_ctx, FILE *file,
4238                                  TDB_DATA *key, TDB_DATA *value)
4239 {
4240         char line [1024]; /* FIXME: make this more flexible? */
4241         const char *t;
4242         char *ptr;
4243
4244         ptr = fgets(line, sizeof(line), file);
4245
4246         if (ptr == NULL) {
4247                 return false;
4248         }
4249
4250         /* Get key */
4251         t = ptrans_parse_string(mem_ctx, line, key);
4252         if (t == NULL || key->dptr == NULL) {
4253                 /* Line Ignored but not EOF */
4254                 return true;
4255         }
4256
4257         /* Get value */
4258         t = ptrans_parse_string(mem_ctx, t, value);
4259         if (t == NULL) {
4260                 /* Line Ignored but not EOF */
4261                 talloc_free(key->dptr);
4262                 *key = tdb_null;
4263                 return true;
4264         }
4265
4266         return true;
4267 }
4268
4269 /*
4270  * Update a persistent database as per file/stdin
4271  */
4272 static int control_ptrans(struct ctdb_context *ctdb,
4273                           int argc, const char **argv)
4274 {
4275         const char *db_name;
4276         struct ctdb_db_context *ctdb_db;
4277         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
4278         struct ctdb_transaction_handle *h;
4279         TDB_DATA key, value;
4280         FILE *file;
4281         int ret;
4282
4283         if (argc < 1) {
4284                 talloc_free(tmp_ctx);
4285                 usage();
4286         }
4287
4288         file = stdin;
4289         if (argc == 2) {
4290                 file = fopen(argv[1], "r");
4291                 if (file == NULL) {
4292                         DEBUG(DEBUG_ERR,("Unable to open file for reading '%s'\n", argv[1]));
4293                         talloc_free(tmp_ctx);
4294                         return -1;
4295                 }
4296         }
4297
4298         db_name = argv[0];
4299
4300         ctdb_db = ctdb_attach(ctdb, TIMELIMIT(), db_name, true, 0);
4301         if (ctdb_db == NULL) {
4302                 DEBUG(DEBUG_ERR,("Unable to attach to database '%s'\n", db_name));
4303                 goto error;
4304         }
4305
4306         h = ctdb_transaction_start(ctdb_db, tmp_ctx);
4307         if (h == NULL) {
4308                 DEBUG(DEBUG_ERR,("Failed to start transaction on database %s\n", db_name));
4309                 goto error;
4310         }
4311
4312         while (ptrans_get_key_value(tmp_ctx, file, &key, &value)) {
4313                 if (key.dsize != 0) {
4314                         ret = ctdb_transaction_store(h, key, value);
4315                         /* Minimise memory use */
4316                         talloc_free(key.dptr);
4317                         if (value.dptr != NULL) {
4318                                 talloc_free(value.dptr);
4319                         }
4320                         if (ret != 0) {
4321                                 DEBUG(DEBUG_ERR,("Failed to store record\n"));
4322                                 ctdb_transaction_cancel(h);
4323                                 goto error;
4324                         }
4325                 }
4326         }
4327
4328         ret = ctdb_transaction_commit(h);
4329         if (ret != 0) {
4330                 DEBUG(DEBUG_ERR,("Failed to commit transaction\n"));
4331                 goto error;
4332         }
4333
4334         if (file != stdin) {
4335                 fclose(file);
4336         }
4337         talloc_free(tmp_ctx);
4338         return 0;
4339
4340 error:
4341         if (file != stdin) {
4342                 fclose(file);
4343         }
4344
4345         talloc_free(tmp_ctx);
4346         return -1;
4347 }
4348
4349 /*
4350   check if a service is bound to a port or not
4351  */
4352 static int control_chktcpport(struct ctdb_context *ctdb, int argc, const char **argv)
4353 {
4354         int s, ret;
4355         int v;
4356         int port;
4357         struct sockaddr_in sin;
4358
4359         if (argc != 1) {
4360                 printf("Use: ctdb chktcport <port>\n");
4361                 return EINVAL;
4362         }
4363
4364         port = atoi(argv[0]);
4365
4366         s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
4367         if (s == -1) {
4368                 printf("Failed to open local socket\n");
4369                 return errno;
4370         }
4371
4372         v = fcntl(s, F_GETFL, 0);
4373         if (v == -1 || fcntl(s, F_SETFL, v | O_NONBLOCK) != 0) {
4374                 printf("Unable to set socket non-blocking: %s\n", strerror(errno));
4375         }
4376
4377         bzero(&sin, sizeof(sin));
4378         sin.sin_family = AF_INET;
4379         sin.sin_port   = htons(port);
4380         ret = bind(s, (struct sockaddr *)&sin, sizeof(sin));
4381         close(s);
4382         if (ret == -1) {
4383                 printf("Failed to bind to local socket: %d %s\n", errno, strerror(errno));
4384                 return errno;
4385         }
4386
4387         return 0;
4388 }
4389
4390
4391 /* Reload public IPs on a specified nodes */
4392 static int control_reloadips(struct ctdb_context *ctdb, int argc, const char **argv)
4393 {
4394         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
4395         uint32_t *nodes;
4396         uint32_t pnn_mode;
4397         uint32_t timeout;
4398         int ret;
4399
4400         assert_single_node_only();
4401
4402         if (argc > 1) {
4403                 usage();
4404         }
4405
4406         /* Determine the nodes where IPs need to be reloaded */
4407         if (!parse_nodestring(ctdb, tmp_ctx, argc == 1 ? argv[0] : NULL,
4408                               options.pnn, true, &nodes, &pnn_mode)) {
4409                 ret = -1;
4410                 goto done;
4411         }
4412
4413 again:
4414         /* Disable takeover runs on all connected nodes.  A reply
4415          * indicating success is needed from each node so all nodes
4416          * will need to be active.  This will retry until maxruntime
4417          * is exceeded, hence no error handling.
4418          * 
4419          * A check could be added to not allow reloading of IPs when
4420          * there are disconnected nodes.  However, this should
4421          * probably be left up to the administrator.
4422          */
4423         timeout = LONGTIMEOUT;
4424         srvid_broadcast(ctdb, CTDB_SRVID_DISABLE_TAKEOVER_RUNS, &timeout,
4425                         "Disable takeover runs", true);
4426
4427         /* Now tell all the desired nodes to reload their public IPs.
4428          * Keep trying this until it succeeds.  This assumes all
4429          * failures are transient, which might not be true...
4430          */
4431         if (ctdb_client_async_control(ctdb, CTDB_CONTROL_RELOAD_PUBLIC_IPS,
4432                                       nodes, 0, LONGTIMELIMIT(),
4433                                       false, tdb_null,
4434                                       NULL, NULL, NULL) != 0) {
4435                 DEBUG(DEBUG_ERR,
4436                       ("Unable to reload IPs on some nodes, try again.\n"));
4437                 goto again;
4438         }
4439
4440         /* It isn't strictly necessary to wait until takeover runs are
4441          * re-enabled but doing so can't hurt.
4442          */
4443         timeout = 0;
4444         srvid_broadcast(ctdb, CTDB_SRVID_DISABLE_TAKEOVER_RUNS, &timeout,
4445                         "Enable takeover runs", true);
4446
4447         ipreallocate(ctdb);
4448
4449         ret = 0;
4450 done:
4451         talloc_free(tmp_ctx);
4452         return ret;
4453 }
4454
4455 /*
4456   display a list of the databases on a remote ctdb
4457  */
4458 static int control_getdbmap(struct ctdb_context *ctdb, int argc, const char **argv)
4459 {
4460         int i, ret;
4461         struct ctdb_dbid_map_old *dbmap=NULL;
4462
4463         ret = ctdb_ctrl_getdbmap(ctdb, TIMELIMIT(), options.pnn, ctdb, &dbmap);
4464         if (ret != 0) {
4465                 DEBUG(DEBUG_ERR, ("Unable to get dbids from node %u\n", options.pnn));
4466                 return ret;
4467         }
4468
4469         if(options.machinereadable){
4470                 printm(":ID:Name:Path:Persistent:Sticky:Unhealthy:ReadOnly:\n");
4471                 for(i=0;i<dbmap->num;i++){
4472                         const char *path = NULL;
4473                         const char *name = NULL;
4474                         const char *health = NULL;
4475                         bool persistent;
4476                         bool readonly;
4477                         bool sticky;
4478
4479                         ctdb_ctrl_getdbpath(ctdb, TIMELIMIT(), options.pnn,
4480                                             dbmap->dbs[i].db_id, ctdb, &path);
4481                         ctdb_ctrl_getdbname(ctdb, TIMELIMIT(), options.pnn,
4482                                             dbmap->dbs[i].db_id, ctdb, &name);
4483                         ctdb_ctrl_getdbhealth(ctdb, TIMELIMIT(), options.pnn,
4484                                               dbmap->dbs[i].db_id, ctdb, &health);
4485                         persistent = dbmap->dbs[i].flags & CTDB_DB_FLAGS_PERSISTENT;
4486                         readonly   = dbmap->dbs[i].flags & CTDB_DB_FLAGS_READONLY;
4487                         sticky     = dbmap->dbs[i].flags & CTDB_DB_FLAGS_STICKY;
4488                         printm(":0x%08X:%s:%s:%d:%d:%d:%d:\n",
4489                                dbmap->dbs[i].db_id, name, path,
4490                                !!(persistent), !!(sticky),
4491                                !!(health), !!(readonly));
4492                 }
4493                 return 0;
4494         }
4495
4496         printf("Number of databases:%d\n", dbmap->num);
4497         for(i=0;i<dbmap->num;i++){
4498                 const char *path = NULL;
4499                 const char *name = NULL;
4500                 const char *health = NULL;
4501                 bool persistent;
4502                 bool readonly;
4503                 bool sticky;
4504
4505                 ctdb_ctrl_getdbpath(ctdb, TIMELIMIT(), options.pnn, dbmap->dbs[i].db_id, ctdb, &path);
4506                 ctdb_ctrl_getdbname(ctdb, TIMELIMIT(), options.pnn, dbmap->dbs[i].db_id, ctdb, &name);
4507                 ctdb_ctrl_getdbhealth(ctdb, TIMELIMIT(), options.pnn, dbmap->dbs[i].db_id, ctdb, &health);
4508                 persistent = dbmap->dbs[i].flags & CTDB_DB_FLAGS_PERSISTENT;
4509                 readonly   = dbmap->dbs[i].flags & CTDB_DB_FLAGS_READONLY;
4510                 sticky     = dbmap->dbs[i].flags & CTDB_DB_FLAGS_STICKY;
4511                 printf("dbid:0x%08x name:%s path:%s%s%s%s%s\n",
4512                        dbmap->dbs[i].db_id, name, path,
4513                        persistent?" PERSISTENT":"",
4514                        sticky?" STICKY":"",
4515                        readonly?" READONLY":"",
4516                        health?" UNHEALTHY":"");
4517         }
4518
4519         return 0;
4520 }
4521
4522 /*
4523   display the status of a database on a remote ctdb
4524  */
4525 static int control_getdbstatus(struct ctdb_context *ctdb, int argc, const char **argv)
4526 {
4527         const char *db_name;
4528         uint32_t db_id;
4529         uint8_t flags;
4530         const char *path = NULL;
4531         const char *health = NULL;
4532
4533         if (argc < 1) {
4534                 usage();
4535         }
4536
4537         if (!db_exists(ctdb, argv[0], &db_id, &db_name, &flags)) {
4538                 return -1;
4539         }
4540
4541         ctdb_ctrl_getdbpath(ctdb, TIMELIMIT(), options.pnn, db_id, ctdb, &path);
4542         ctdb_ctrl_getdbhealth(ctdb, TIMELIMIT(), options.pnn, db_id, ctdb, &health);
4543         printf("dbid: 0x%08x\nname: %s\npath: %s\nPERSISTENT: %s\nSTICKY: %s\nREADONLY: %s\nHEALTH: %s\n",
4544                db_id, db_name, path,
4545                (flags & CTDB_DB_FLAGS_PERSISTENT ? "yes" : "no"),
4546                (flags & CTDB_DB_FLAGS_STICKY ? "yes" : "no"),
4547                (flags & CTDB_DB_FLAGS_READONLY ? "yes" : "no"),
4548                (health ? health : "OK"));
4549
4550         return 0;
4551 }
4552
4553 /*
4554   check if the local node is recmaster or not
4555   it will return 1 if this node is the recmaster and 0 if it is not
4556   or if the local ctdb daemon could not be contacted
4557  */
4558 static int control_isnotrecmaster(struct ctdb_context *ctdb, int argc, const char **argv)
4559 {
4560         uint32_t mypnn, recmaster;
4561         int ret;
4562
4563         assert_single_node_only();
4564
4565         mypnn = getpnn(ctdb);
4566
4567         ret = ctdb_ctrl_getrecmaster(ctdb, ctdb, TIMELIMIT(), options.pnn, &recmaster);
4568         if (ret != 0) {
4569                 printf("Failed to get the recmaster\n");
4570                 return 1;
4571         }
4572
4573         if (recmaster != mypnn) {
4574                 printf("this node is not the recmaster\n");
4575                 return 1;
4576         }
4577
4578         printf("this node is the recmaster\n");
4579         return 0;
4580 }
4581
4582 /*
4583   ping a node
4584  */
4585 static int control_ping(struct ctdb_context *ctdb, int argc, const char **argv)
4586 {
4587         int ret;
4588         struct timeval tv = timeval_current();
4589         ret = ctdb_ctrl_ping(ctdb, options.pnn);
4590         if (ret == -1) {
4591                 printf("Unable to get ping response from node %u\n", options.pnn);
4592                 return -1;
4593         } else {
4594                 printf("response from %u time=%.6f sec  (%d clients)\n", 
4595                        options.pnn, timeval_elapsed(&tv), ret);
4596         }
4597         return 0;
4598 }
4599
4600
4601 /*
4602   get a node's runstate
4603  */
4604 static int control_runstate(struct ctdb_context *ctdb, int argc, const char **argv)
4605 {
4606         int ret;
4607         enum ctdb_runstate runstate;
4608
4609         ret = ctdb_ctrl_get_runstate(ctdb, TIMELIMIT(), options.pnn, &runstate);
4610         if (ret == -1) {
4611                 printf("Unable to get runstate response from node %u\n",
4612                        options.pnn);
4613                 return -1;
4614         } else {
4615                 bool found = true;
4616                 enum ctdb_runstate t;
4617                 int i;
4618                 for (i=0; i<argc; i++) {
4619                         found = false;
4620                         t = runstate_from_string(argv[i]);
4621                         if (t == CTDB_RUNSTATE_UNKNOWN) {
4622                                 printf("Invalid run state (%s)\n", argv[i]);
4623                                 return -1;
4624                         }
4625
4626                         if (t == runstate) {
4627                                 found = true;
4628                                 break;
4629                         }
4630                 }
4631
4632                 if (!found) {
4633                         printf("CTDB not in required run state (got %s)\n", 
4634                                runstate_to_string((enum ctdb_runstate)runstate));
4635                         return -1;
4636                 }
4637         }
4638
4639         printf("%s\n", runstate_to_string(runstate));
4640         return 0;
4641 }
4642
4643
4644 /*
4645   get a tunable
4646  */
4647 static int control_getvar(struct ctdb_context *ctdb, int argc, const char **argv)
4648 {
4649         const char *name;
4650         uint32_t value;
4651         int ret;
4652
4653         if (argc < 1) {
4654                 usage();
4655         }
4656
4657         name = argv[0];
4658         ret = ctdb_ctrl_get_tunable(ctdb, TIMELIMIT(), options.pnn, name, &value);
4659         if (ret != 0) {
4660                 DEBUG(DEBUG_ERR, ("Unable to get tunable variable '%s'\n", name));
4661                 return -1;
4662         }
4663
4664         printf("%-23s = %u\n", name, value);
4665         return 0;
4666 }
4667
4668 /*
4669   set a tunable
4670  */
4671 static int control_setvar(struct ctdb_context *ctdb, int argc, const char **argv)
4672 {
4673         const char *name;
4674         uint32_t value;
4675         int ret;
4676
4677         if (argc < 2) {
4678                 usage();
4679         }
4680
4681         name = argv[0];
4682         value = strtoul(argv[1], NULL, 0);
4683
4684         ret = ctdb_ctrl_set_tunable(ctdb, TIMELIMIT(), options.pnn, name, value);
4685         if (ret == -1) {
4686                 DEBUG(DEBUG_ERR, ("Unable to set tunable variable '%s'\n", name));
4687                 return -1;
4688         }
4689         if (ret == 1) {
4690                 DEBUG(DEBUG_WARNING,
4691                       ("Setting obsolete tunable variable '%s'\n",
4692                        name));
4693         }
4694         return 0;
4695 }
4696
4697 /*
4698   list all tunables
4699  */
4700 static int control_listvars(struct ctdb_context *ctdb, int argc, const char **argv)
4701 {
4702         uint32_t count;
4703         const char **list;
4704         int ret, i;
4705
4706         ret = ctdb_ctrl_list_tunables(ctdb, TIMELIMIT(), options.pnn, ctdb, &list, &count);
4707         if (ret == -1) {
4708                 DEBUG(DEBUG_ERR, ("Unable to list tunable variables\n"));
4709                 return -1;
4710         }
4711
4712         for (i=0;i<count;i++) {
4713                 control_getvar(ctdb, 1, &list[i]);
4714         }
4715
4716         talloc_free(list);
4717         
4718         return 0;
4719 }
4720
4721 /*
4722   display debug level on a node
4723  */
4724 static int control_getdebug(struct ctdb_context *ctdb, int argc, const char **argv)
4725 {
4726         int ret;
4727         int32_t level;
4728
4729         ret = ctdb_ctrl_get_debuglevel(ctdb, options.pnn, &level);
4730         if (ret != 0) {
4731                 DEBUG(DEBUG_ERR, ("Unable to get debuglevel response from node %u\n", options.pnn));
4732                 return ret;
4733         } else {
4734                 enum debug_level log_level = debug_level_from_int(level);
4735                 const char *desc = debug_level_to_string(log_level);
4736                 if (desc == NULL) {
4737                         /* This should never happen */
4738                         desc = "Unknown";
4739                 }
4740                 if (options.machinereadable){
4741                         printm(":Name:Level:\n");
4742                         printm(":%s:%d:\n", desc, level);
4743                 } else {
4744                         printf("Node %u is at debug level %s (%d)\n",
4745                                options.pnn, desc, level);
4746                 }
4747         }
4748         return 0;
4749 }
4750
4751 /*
4752   display reclock file of a node
4753  */
4754 static int control_getreclock(struct ctdb_context *ctdb, int argc, const char **argv)
4755 {
4756         int ret;
4757         const char *reclock;
4758
4759         ret = ctdb_ctrl_getreclock(ctdb, TIMELIMIT(), options.pnn, ctdb, &reclock);
4760         if (ret != 0) {
4761                 DEBUG(DEBUG_ERR, ("Unable to get reclock file from node %u\n", options.pnn));
4762                 return ret;
4763         } else {
4764                 if (options.machinereadable){
4765                         if (reclock != NULL) {
4766                                 printm("%s", reclock);
4767                         }
4768                 } else {
4769                         if (reclock == NULL) {
4770                                 printf("No reclock file used.\n");
4771                         } else {
4772                                 printf("Reclock file:%s\n", reclock);
4773                         }
4774                 }
4775         }
4776         return 0;
4777 }
4778
4779 /*
4780   set the reclock file of a node
4781  */
4782 static int control_setreclock(struct ctdb_context *ctdb, int argc, const char **argv)
4783 {
4784         int ret;
4785         const char *reclock = NULL;
4786
4787         if (argc == 0) {
4788                 reclock = NULL;
4789         } else if (argc == 1) {
4790                 reclock = argv[0];
4791         } else {
4792                 usage();
4793         }
4794
4795         ret = ctdb_ctrl_setreclock(ctdb, TIMELIMIT(), options.pnn, reclock);
4796         if (ret != 0) {
4797                 DEBUG(DEBUG_ERR, ("Unable to get reclock file from node %u\n", options.pnn));
4798                 return ret;
4799         }
4800         return 0;
4801 }
4802
4803 /*
4804   set the lmaster role on/off
4805  */
4806 static int control_setlmasterrole(struct ctdb_context *ctdb, int argc, const char **argv)
4807 {
4808         int ret;
4809         uint32_t lmasterrole = 0;
4810
4811         if (argc == 0) {
4812                 usage();
4813         }
4814
4815         if (!strcmp(argv[0], "on")) {
4816                 lmasterrole = 1;
4817         } else if (!strcmp(argv[0], "off")) {
4818                 lmasterrole = 0;
4819         } else {
4820                 usage();
4821         }
4822
4823         ret = ctdb_ctrl_setlmasterrole(ctdb, TIMELIMIT(), options.pnn, lmasterrole);
4824         if (ret != 0) {
4825                 DEBUG(DEBUG_ERR, ("Unable to set the lmaster role for node %u\n", options.pnn));
4826                 return ret;
4827         }
4828
4829         return 0;
4830 }
4831
4832 /*
4833   set the recmaster role on/off
4834  */
4835 static int control_setrecmasterrole(struct ctdb_context *ctdb, int argc, const char **argv)
4836 {
4837         int ret;
4838         uint32_t recmasterrole = 0;
4839
4840         if (argc == 0) {
4841                 usage();
4842         }
4843
4844         if (!strcmp(argv[0], "on")) {
4845                 recmasterrole = 1;
4846         } else if (!strcmp(argv[0], "off")) {
4847                 recmasterrole = 0;
4848         } else {
4849                 usage();
4850         }
4851
4852         ret = ctdb_ctrl_setrecmasterrole(ctdb, TIMELIMIT(), options.pnn, recmasterrole);
4853         if (ret != 0) {
4854                 DEBUG(DEBUG_ERR, ("Unable to set the recmaster role for node %u\n", options.pnn));
4855                 return ret;
4856         }
4857
4858         return 0;
4859 }
4860
4861 /*
4862   set debug level on a node or all nodes
4863  */
4864 static int control_setdebug(struct ctdb_context *ctdb, int argc, const char **argv)
4865 {
4866         int ret;
4867         int32_t level;
4868         enum debug_level log_level;
4869
4870         if (argc == 0) {
4871                 printf("You must specify the debug level. Valid levels are:\n");
4872                 printf("\tERROR | WARNING | NOTICE | INFO | DEBUG\n");
4873                 return 0;
4874         }
4875
4876         if (!debug_level_parse(argv[0], &log_level)) {
4877                 printf("Invalid debug level, must be one of\n");
4878                 printf("\tERROR | WARNING | NOTICE | INFO | DEBUG\n");
4879                 return -1;
4880         }
4881
4882         level = debug_level_to_int(log_level);
4883
4884         ret = ctdb_ctrl_set_debuglevel(ctdb, options.pnn, level);
4885         if (ret != 0) {
4886                 DEBUG(DEBUG_ERR, ("Unable to set debug level on node %u\n", options.pnn));
4887         }
4888         return 0;
4889 }
4890
4891
4892 /*
4893   thaw a node
4894  */
4895 static int control_thaw(struct ctdb_context *ctdb, int argc, const char **argv)
4896 {
4897         int ret;
4898         uint32_t priority;
4899         
4900         if (argc == 1) {
4901                 priority = strtol(argv[0], NULL, 0);
4902         } else {
4903                 priority = 0;
4904         }
4905         DEBUG(DEBUG_ERR,("Thaw by priority %u\n", priority));
4906
4907         ret = ctdb_ctrl_thaw_priority(ctdb, TIMELIMIT(), options.pnn, priority);
4908         if (ret != 0) {
4909                 DEBUG(DEBUG_ERR, ("Unable to thaw node %u\n", options.pnn));
4910         }               
4911         return 0;
4912 }
4913
4914
4915 /*
4916   attach to a database
4917  */
4918 static int control_attach(struct ctdb_context *ctdb, int argc, const char **argv)
4919 {
4920         const char *db_name;
4921         struct ctdb_db_context *ctdb_db;
4922         bool persistent = false;
4923
4924         if (argc < 1) {
4925                 usage();
4926         }
4927         db_name = argv[0];
4928         if (argc > 2) {
4929                 usage();
4930         }
4931         if (argc == 2) {
4932                 if (strcmp(argv[1], "persistent") != 0) {
4933                         usage();
4934                 }
4935                 persistent = true;
4936         }
4937
4938         ctdb_db = ctdb_attach(ctdb, TIMELIMIT(), db_name, persistent, 0);
4939         if (ctdb_db == NULL) {
4940                 DEBUG(DEBUG_ERR,("Unable to attach to database '%s'\n", db_name));
4941                 return -1;
4942         }
4943
4944         return 0;
4945 }
4946
4947 /*
4948  * detach from a database
4949  */
4950 static int control_detach(struct ctdb_context *ctdb, int argc,
4951                           const char **argv)
4952 {
4953         uint32_t db_id;
4954         uint8_t flags;
4955         int ret, i, status = 0;
4956         struct ctdb_node_map_old *nodemap = NULL;
4957         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
4958         uint32_t recmode;
4959
4960         if (argc < 1) {
4961                 usage();
4962         }
4963
4964         assert_single_node_only();
4965
4966         ret = ctdb_ctrl_getrecmode(ctdb, tmp_ctx, TIMELIMIT(), options.pnn,
4967                                     &recmode);
4968         if (ret != 0) {
4969                 DEBUG(DEBUG_ERR, ("Database cannot be detached "
4970                                   "when recovery is active\n"));
4971                 talloc_free(tmp_ctx);
4972                 return -1;
4973         }
4974
4975         ret = ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), options.pnn, tmp_ctx,
4976                                    &nodemap);
4977         if (ret != 0) {
4978                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from node %u\n",
4979                                   options.pnn));
4980                 talloc_free(tmp_ctx);
4981                 return -1;
4982         }
4983
4984         for (i=0; i<nodemap->num; i++) {
4985                 uint32_t value;
4986
4987                 if (nodemap->nodes[i].flags & NODE_FLAGS_DISCONNECTED) {
4988                         continue;
4989                 }
4990
4991                 if (nodemap->nodes[i].flags & NODE_FLAGS_DELETED) {
4992                         continue;
4993                 }
4994
4995                 if (nodemap->nodes[i].flags & NODE_FLAGS_INACTIVE) {
4996                         DEBUG(DEBUG_ERR, ("Database cannot be detached on "
4997                                           "inactive (stopped or banned) node "
4998                                           "%u\n", nodemap->nodes[i].pnn));
4999                         talloc_free(tmp_ctx);
5000                         return -1;
5001                 }
5002
5003                 ret = ctdb_ctrl_get_tunable(ctdb, TIMELIMIT(),
5004                                             nodemap->nodes[i].pnn,
5005                                             "AllowClientDBAttach",
5006                                             &value);
5007                 if (ret != 0) {
5008                         DEBUG(DEBUG_ERR, ("Unable to get tunable "
5009                                           "AllowClientDBAttach from node %u\n",
5010                                            nodemap->nodes[i].pnn));
5011                         talloc_free(tmp_ctx);
5012                         return -1;
5013                 }
5014
5015                 if (value == 1) {
5016                         DEBUG(DEBUG_ERR, ("Database access is still active on "
5017                                           "node %u. Set AllowClientDBAttach=0 "
5018                                           "on all nodes.\n",
5019                                           nodemap->nodes[i].pnn));
5020                         talloc_free(tmp_ctx);
5021                         return -1;
5022                 }
5023         }
5024
5025         talloc_free(tmp_ctx);
5026
5027         for (i=0; i<argc; i++) {
5028                 if (!db_exists(ctdb, argv[i], &db_id, NULL, &flags)) {
5029                         continue;
5030                 }
5031
5032                 if (flags & CTDB_DB_FLAGS_PERSISTENT) {
5033                         DEBUG(DEBUG_ERR, ("Persistent database '%s' "
5034                                           "cannot be detached\n", argv[i]));
5035                         status = -1;
5036                         continue;
5037                 }
5038
5039                 ret = ctdb_detach(ctdb, db_id);
5040                 if (ret != 0) {
5041                         DEBUG(DEBUG_ERR, ("Database '%s' detach failed\n",
5042                                           argv[i]));
5043                         status = ret;
5044                 }
5045         }
5046
5047         return status;
5048 }
5049
5050 /*
5051   set db priority
5052  */
5053 static int control_setdbprio(struct ctdb_context *ctdb, int argc, const char **argv)
5054 {
5055         struct ctdb_db_priority db_prio;
5056         int ret;
5057
5058         if (argc < 2) {
5059                 usage();
5060         }
5061
5062         db_prio.db_id    = strtoul(argv[0], NULL, 0);
5063         db_prio.priority = strtoul(argv[1], NULL, 0);
5064
5065         ret = ctdb_ctrl_set_db_priority(ctdb, TIMELIMIT(), options.pnn, &db_prio);
5066         if (ret != 0) {
5067                 DEBUG(DEBUG_ERR,("Unable to set db prio\n"));
5068                 return -1;
5069         }
5070
5071         return 0;
5072 }
5073
5074 /*
5075   get db priority
5076  */
5077 static int control_getdbprio(struct ctdb_context *ctdb, int argc, const char **argv)
5078 {
5079         uint32_t db_id, priority;
5080         int ret;
5081
5082         if (argc < 1) {
5083                 usage();
5084         }
5085
5086         if (!db_exists(ctdb, argv[0], &db_id, NULL, NULL)) {
5087                 return -1;
5088         }
5089
5090         ret = ctdb_ctrl_get_db_priority(ctdb, TIMELIMIT(), options.pnn, db_id, &priority);
5091         if (ret != 0) {
5092                 DEBUG(DEBUG_ERR,("Unable to get db prio\n"));
5093                 return -1;
5094         }
5095
5096         DEBUG(DEBUG_ERR,("Priority:%u\n", priority));
5097
5098         return 0;
5099 }
5100
5101 /*
5102   set the sticky records capability for a database
5103  */
5104 static int control_setdbsticky(struct ctdb_context *ctdb, int argc, const char **argv)
5105 {
5106         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
5107         uint32_t db_id;
5108         int ret;
5109
5110         if (argc < 1) {
5111                 usage();
5112         }
5113
5114         if (!db_exists(ctdb, argv[0], &db_id, NULL, NULL)) {
5115                 return -1;
5116         }
5117
5118         ret = ctdb_ctrl_set_db_sticky(ctdb, options.pnn, db_id);
5119         if (ret != 0) {
5120                 DEBUG(DEBUG_ERR,("Unable to set db to support sticky records\n"));
5121                 talloc_free(tmp_ctx);
5122                 return -1;
5123         }
5124
5125         talloc_free(tmp_ctx);
5126         return 0;
5127 }
5128
5129 /*
5130   set the readonly capability for a database
5131  */
5132 static int control_setdbreadonly(struct ctdb_context *ctdb, int argc, const char **argv)
5133 {
5134         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
5135         uint32_t db_id;
5136         int ret;
5137
5138         if (argc < 1) {
5139                 usage();
5140         }
5141
5142         if (!db_exists(ctdb, argv[0], &db_id, NULL, NULL)) {
5143                 return -1;
5144         }
5145
5146         ret = ctdb_ctrl_set_db_readonly(ctdb, options.pnn, db_id);
5147         if (ret != 0) {
5148                 DEBUG(DEBUG_ERR,("Unable to set db to support readonly\n"));
5149                 talloc_free(tmp_ctx);
5150                 return -1;
5151         }
5152
5153         talloc_free(tmp_ctx);
5154         return 0;
5155 }
5156
5157 /*
5158   get db seqnum
5159  */
5160 static int control_getdbseqnum(struct ctdb_context *ctdb, int argc, const char **argv)
5161 {
5162         uint32_t db_id;
5163         uint64_t seqnum;
5164         int ret;
5165
5166         if (argc < 1) {
5167                 usage();
5168         }
5169
5170         if (!db_exists(ctdb, argv[0], &db_id, NULL, NULL)) {
5171                 return -1;
5172         }
5173
5174         ret = ctdb_ctrl_getdbseqnum(ctdb, TIMELIMIT(), options.pnn, db_id, &seqnum);
5175         if (ret != 0) {
5176                 DEBUG(DEBUG_ERR, ("Unable to get seqnum from node."));
5177                 return -1;
5178         }
5179
5180         printf("Sequence number:%lld\n", (long long)seqnum);
5181
5182         return 0;
5183 }
5184
5185 /*
5186   run an eventscript on a node
5187  */
5188 static int control_eventscript(struct ctdb_context *ctdb, int argc, const char **argv)
5189 {
5190         TDB_DATA data;
5191         int ret;
5192         int32_t res;
5193         char *errmsg;
5194         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
5195
5196         if (argc != 1) {
5197                 DEBUG(DEBUG_ERR,("Invalid arguments\n"));
5198                 return -1;
5199         }
5200
5201         data.dptr = (unsigned char *)discard_const(argv[0]);
5202         data.dsize = strlen((char *)data.dptr) + 1;
5203
5204         DEBUG(DEBUG_ERR, ("Running eventscripts with arguments \"%s\" on node %u\n", data.dptr, options.pnn));
5205
5206         ret = ctdb_control(ctdb, options.pnn, 0, CTDB_CONTROL_RUN_EVENTSCRIPTS,
5207                            0, data, tmp_ctx, NULL, &res, NULL, &errmsg);
5208         if (ret != 0 || res != 0) {
5209                 if (errmsg != NULL) {
5210                         DEBUG(DEBUG_ERR,
5211                               ("Failed to run eventscripts - %s\n", errmsg));
5212                 } else {
5213                         DEBUG(DEBUG_ERR, ("Failed to run eventscripts\n"));
5214                 }
5215                 talloc_free(tmp_ctx);
5216                 return -1;
5217         }
5218         talloc_free(tmp_ctx);
5219         return 0;
5220 }
5221
5222 #define DB_VERSION 1
5223 #define MAX_DB_NAME 64
5224 struct db_file_header {
5225         unsigned long version;
5226         time_t timestamp;
5227         unsigned long persistent;
5228         unsigned long size;
5229         const char name[MAX_DB_NAME];
5230 };
5231
5232 struct backup_data {
5233         struct ctdb_marshall_buffer *records;
5234         uint32_t len;
5235         uint32_t total;
5236         bool traverse_error;
5237 };
5238
5239 static int backup_traverse(struct tdb_context *tdb, TDB_DATA key, TDB_DATA data, void *private)
5240 {
5241         struct backup_data *bd = talloc_get_type(private, struct backup_data);
5242         struct ctdb_rec_data_old *rec;
5243
5244         /* add the record */
5245         rec = ctdb_marshall_record(bd->records, 0, key, NULL, data);
5246         if (rec == NULL) {
5247                 bd->traverse_error = true;
5248                 DEBUG(DEBUG_ERR,("Failed to marshall record\n"));
5249                 return -1;
5250         }
5251         bd->records = talloc_realloc_size(NULL, bd->records, rec->length + bd->len);
5252         if (bd->records == NULL) {
5253                 DEBUG(DEBUG_ERR,("Failed to expand marshalling buffer\n"));
5254                 bd->traverse_error = true;
5255                 return -1;
5256         }
5257         bd->records->count++;
5258         memcpy(bd->len+(uint8_t *)bd->records, rec, rec->length);
5259         bd->len += rec->length;
5260         talloc_free(rec);
5261
5262         bd->total++;
5263         return 0;
5264 }
5265
5266 /*
5267  * backup a database to a file 
5268  */
5269 static int control_backupdb(struct ctdb_context *ctdb, int argc, const char **argv)
5270 {
5271         const char *db_name;
5272         int ret;
5273         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
5274         struct db_file_header dbhdr;
5275         struct ctdb_db_context *ctdb_db;
5276         struct backup_data *bd;
5277         int fh = -1;
5278         int status = -1;
5279         const char *reason = NULL;
5280         uint32_t db_id;
5281         uint8_t flags;
5282
5283         assert_single_node_only();
5284
5285         if (argc != 2) {
5286                 DEBUG(DEBUG_ERR,("Invalid arguments\n"));
5287                 return -1;
5288         }
5289
5290         if (!db_exists(ctdb, argv[0], &db_id, &db_name, &flags)) {
5291                 return -1;
5292         }
5293
5294         ret = ctdb_ctrl_getdbhealth(ctdb, TIMELIMIT(), options.pnn,
5295                                     db_id, tmp_ctx, &reason);
5296         if (ret != 0) {
5297                 DEBUG(DEBUG_ERR,("Unable to get dbhealth for database '%s'\n",
5298                                  argv[0]));
5299                 talloc_free(tmp_ctx);
5300                 return -1;
5301         }
5302         if (reason) {
5303                 uint32_t allow_unhealthy = 0;
5304
5305                 ctdb_ctrl_get_tunable(ctdb, TIMELIMIT(), options.pnn,
5306                                       "AllowUnhealthyDBRead",
5307                                       &allow_unhealthy);
5308
5309                 if (allow_unhealthy != 1) {
5310                         DEBUG(DEBUG_ERR,("database '%s' is unhealthy: %s\n",
5311                                          argv[0], reason));
5312
5313                         DEBUG(DEBUG_ERR,("disallow backup : tunable AllowUnhealthyDBRead = %u\n",
5314                                          allow_unhealthy));
5315                         talloc_free(tmp_ctx);
5316                         return -1;
5317                 }
5318
5319                 DEBUG(DEBUG_WARNING,("WARNING database '%s' is unhealthy - see 'ctdb getdbstatus %s'\n",
5320                                      argv[0], argv[0]));
5321                 DEBUG(DEBUG_WARNING,("WARNING! allow backup of unhealthy database: "
5322                                      "tunnable AllowUnhealthyDBRead = %u\n",
5323                                      allow_unhealthy));
5324         }
5325
5326         ctdb_db = ctdb_attach(ctdb, TIMELIMIT(), db_name, flags & CTDB_DB_FLAGS_PERSISTENT, 0);
5327         if (ctdb_db == NULL) {
5328                 DEBUG(DEBUG_ERR,("Unable to attach to database '%s'\n", argv[0]));
5329                 talloc_free(tmp_ctx);
5330                 return -1;
5331         }
5332
5333
5334         ret = tdb_transaction_start(ctdb_db->ltdb->tdb);
5335         if (ret == -1) {
5336                 DEBUG(DEBUG_ERR,("Failed to start transaction\n"));
5337                 talloc_free(tmp_ctx);
5338                 return -1;
5339         }
5340
5341
5342         bd = talloc_zero(tmp_ctx, struct backup_data);
5343         if (bd == NULL) {
5344                 DEBUG(DEBUG_ERR,("Failed to allocate backup_data\n"));
5345                 talloc_free(tmp_ctx);
5346                 return -1;
5347         }
5348
5349         bd->records = talloc_zero(bd, struct ctdb_marshall_buffer);
5350         if (bd->records == NULL) {
5351                 DEBUG(DEBUG_ERR,("Failed to allocate ctdb_marshall_buffer\n"));
5352                 talloc_free(tmp_ctx);
5353                 return -1;
5354         }
5355
5356         bd->len = offsetof(struct ctdb_marshall_buffer, data);
5357         bd->records->db_id = ctdb_db->db_id;
5358         /* traverse the database collecting all records */
5359         if (tdb_traverse_read(ctdb_db->ltdb->tdb, backup_traverse, bd) == -1 ||
5360             bd->traverse_error) {
5361                 DEBUG(DEBUG_ERR,("Traverse error\n"));
5362                 talloc_free(tmp_ctx);
5363                 return -1;              
5364         }
5365
5366         tdb_transaction_cancel(ctdb_db->ltdb->tdb);
5367
5368
5369         fh = open(argv[1], O_RDWR|O_CREAT, 0600);
5370         if (fh == -1) {
5371                 DEBUG(DEBUG_ERR,("Failed to open file '%s'\n", argv[1]));
5372                 talloc_free(tmp_ctx);
5373                 return -1;
5374         }
5375
5376         ZERO_STRUCT(dbhdr);
5377         dbhdr.version = DB_VERSION;
5378         dbhdr.timestamp = time(NULL);
5379         dbhdr.persistent = flags & CTDB_DB_FLAGS_PERSISTENT;
5380         dbhdr.size = bd->len;
5381         if (strlen(argv[0]) >= MAX_DB_NAME) {
5382                 DEBUG(DEBUG_ERR,("Too long dbname\n"));
5383                 goto done;
5384         }
5385         strncpy(discard_const(dbhdr.name), argv[0], MAX_DB_NAME-1);
5386         ret = sys_write(fh, &dbhdr, sizeof(dbhdr));
5387         if (ret == -1) {
5388                 DEBUG(DEBUG_ERR,("write failed: %s\n", strerror(errno)));
5389                 goto done;
5390         }
5391         ret = sys_write(fh, bd->records, bd->len);
5392         if (ret == -1) {
5393                 DEBUG(DEBUG_ERR,("write failed: %s\n", strerror(errno)));
5394                 goto done;
5395         }
5396
5397         status = 0;
5398 done:
5399         if (fh != -1) {
5400                 ret = close(fh);
5401                 if (ret == -1) {
5402                         DEBUG(DEBUG_ERR,("close failed: %s\n", strerror(errno)));
5403                 }
5404         }
5405
5406         DEBUG(DEBUG_ERR,("Database backed up to %s\n", argv[1]));
5407
5408         talloc_free(tmp_ctx);
5409         return status;
5410 }
5411
5412 /*
5413  * restore a database from a file 
5414  */
5415 static int control_restoredb(struct ctdb_context *ctdb, int argc, const char **argv)
5416 {
5417         int ret;
5418         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
5419         TDB_DATA outdata;
5420         TDB_DATA data;
5421         struct db_file_header dbhdr;
5422         struct ctdb_db_context *ctdb_db;
5423         struct ctdb_node_map_old *nodemap=NULL;
5424         struct ctdb_vnn_map *vnnmap=NULL;
5425         int i, fh;
5426         struct ctdb_transdb w;
5427         uint32_t *nodes;
5428         uint32_t generation;
5429         struct tm *tm;
5430         char tbuf[100];
5431         char *dbname;
5432
5433         assert_single_node_only();
5434
5435         if (argc < 1 || argc > 2) {
5436                 DEBUG(DEBUG_ERR,("Invalid arguments\n"));
5437                 return -1;
5438         }
5439
5440         fh = open(argv[0], O_RDONLY);
5441         if (fh == -1) {
5442                 DEBUG(DEBUG_ERR,("Failed to open file '%s'\n", argv[0]));
5443                 talloc_free(tmp_ctx);
5444                 return -1;
5445         }
5446
5447         sys_read(fh, &dbhdr, sizeof(dbhdr));
5448         if (dbhdr.version != DB_VERSION) {
5449                 DEBUG(DEBUG_ERR,("Invalid version of database dump. File is version %lu but expected version was %u\n", dbhdr.version, DB_VERSION));
5450                 close(fh);
5451                 talloc_free(tmp_ctx);
5452                 return -1;
5453         }
5454
5455         dbname = discard_const(dbhdr.name);
5456         if (argc == 2) {
5457                 dbname = discard_const(argv[1]);
5458         }
5459
5460         outdata.dsize = dbhdr.size;
5461         outdata.dptr = talloc_size(tmp_ctx, outdata.dsize);
5462         if (outdata.dptr == NULL) {
5463                 DEBUG(DEBUG_ERR,("Failed to allocate data of size '%lu'\n", dbhdr.size));
5464                 close(fh);
5465                 talloc_free(tmp_ctx);
5466                 return -1;
5467         }               
5468         sys_read(fh, outdata.dptr, outdata.dsize);
5469         close(fh);
5470
5471         tm = localtime(&dbhdr.timestamp);
5472         strftime(tbuf,sizeof(tbuf)-1,"%Y/%m/%d %H:%M:%S", tm);
5473         printf("Restoring database '%s' from backup @ %s\n",
5474                 dbname, tbuf);
5475
5476
5477         ctdb_db = ctdb_attach(ctdb, TIMELIMIT(), dbname, dbhdr.persistent, 0);
5478         if (ctdb_db == NULL) {
5479                 DEBUG(DEBUG_ERR,("Unable to attach to database '%s'\n", dbname));
5480                 talloc_free(tmp_ctx);
5481                 return -1;
5482         }
5483
5484         ret = ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), options.pnn, ctdb, &nodemap);
5485         if (ret != 0) {
5486                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from node %u\n", options.pnn));
5487                 talloc_free(tmp_ctx);
5488                 return ret;
5489         }
5490
5491
5492         ret = ctdb_ctrl_getvnnmap(ctdb, TIMELIMIT(), options.pnn, tmp_ctx, &vnnmap);
5493         if (ret != 0) {
5494                 DEBUG(DEBUG_ERR, ("Unable to get vnnmap from node %u\n", options.pnn));
5495                 talloc_free(tmp_ctx);
5496                 return ret;
5497         }
5498
5499         /* freeze all nodes */
5500         nodes = list_of_active_nodes(ctdb, nodemap, tmp_ctx, true);
5501         for (i=1; i<=NUM_DB_PRIORITIES; i++) {
5502                 if (ctdb_client_async_control(ctdb, CTDB_CONTROL_FREEZE,
5503                                         nodes, i,
5504                                         TIMELIMIT(),
5505                                         false, tdb_null,
5506                                         NULL, NULL,
5507                                         NULL) != 0) {
5508                         DEBUG(DEBUG_ERR, ("Unable to freeze nodes.\n"));
5509                         ctdb_ctrl_setrecmode(ctdb, TIMELIMIT(), options.pnn, CTDB_RECOVERY_ACTIVE);
5510                         talloc_free(tmp_ctx);
5511                         return -1;
5512                 }
5513         }
5514
5515         generation = vnnmap->generation;
5516         data.dptr = (void *)&generation;
5517         data.dsize = sizeof(generation);
5518
5519         /* start a cluster wide transaction */
5520         nodes = list_of_active_nodes(ctdb, nodemap, tmp_ctx, true);
5521         if (ctdb_client_async_control(ctdb, CTDB_CONTROL_TRANSACTION_START,
5522                                         nodes, 0,
5523                                         TIMELIMIT(), false, data,
5524                                         NULL, NULL,
5525                                         NULL) != 0) {
5526                 DEBUG(DEBUG_ERR, ("Unable to start cluster wide transactions.\n"));
5527                 return -1;
5528         }
5529
5530
5531         w.db_id = ctdb_db->db_id;
5532         w.tid = generation;
5533
5534         data.dptr = (void *)&w;
5535         data.dsize = sizeof(w);
5536
5537         /* wipe all the remote databases. */
5538         nodes = list_of_active_nodes(ctdb, nodemap, tmp_ctx, true);
5539         if (ctdb_client_async_control(ctdb, CTDB_CONTROL_WIPE_DATABASE,
5540                                         nodes, 0,
5541                                         TIMELIMIT(), false, data,
5542                                         NULL, NULL,
5543                                         NULL) != 0) {
5544                 DEBUG(DEBUG_ERR, ("Unable to wipe database.\n"));
5545                 ctdb_ctrl_setrecmode(ctdb, TIMELIMIT(), options.pnn, CTDB_RECOVERY_ACTIVE);
5546                 talloc_free(tmp_ctx);
5547                 return -1;
5548         }
5549         
5550         /* push the database */
5551         nodes = list_of_active_nodes(ctdb, nodemap, tmp_ctx, true);
5552         if (ctdb_client_async_control(ctdb, CTDB_CONTROL_PUSH_DB,
5553                                         nodes, 0,
5554                                         TIMELIMIT(), false, outdata,
5555                                         NULL, NULL,
5556                                         NULL) != 0) {
5557                 DEBUG(DEBUG_ERR, ("Failed to push database.\n"));
5558                 ctdb_ctrl_setrecmode(ctdb, TIMELIMIT(), options.pnn, CTDB_RECOVERY_ACTIVE);
5559                 talloc_free(tmp_ctx);
5560                 return -1;
5561         }
5562
5563         data.dptr = (void *)&ctdb_db->db_id;
5564         data.dsize = sizeof(ctdb_db->db_id);
5565
5566         /* mark the database as healthy */
5567         nodes = list_of_active_nodes(ctdb, nodemap, tmp_ctx, true);
5568         if (ctdb_client_async_control(ctdb, CTDB_CONTROL_DB_SET_HEALTHY,
5569                                         nodes, 0,
5570                                         TIMELIMIT(), false, data,
5571                                         NULL, NULL,
5572                                         NULL) != 0) {
5573                 DEBUG(DEBUG_ERR, ("Failed to mark database as healthy.\n"));
5574                 ctdb_ctrl_setrecmode(ctdb, TIMELIMIT(), options.pnn, CTDB_RECOVERY_ACTIVE);
5575                 talloc_free(tmp_ctx);
5576                 return -1;
5577         }
5578
5579         data.dptr = (void *)&generation;
5580         data.dsize = sizeof(generation);
5581
5582         /* commit all the changes */
5583         if (ctdb_client_async_control(ctdb, CTDB_CONTROL_TRANSACTION_COMMIT,
5584                                         nodes, 0,
5585                                         TIMELIMIT(), false, data,
5586                                         NULL, NULL,
5587                                         NULL) != 0) {
5588                 DEBUG(DEBUG_ERR, ("Unable to commit databases.\n"));
5589                 ctdb_ctrl_setrecmode(ctdb, TIMELIMIT(), options.pnn, CTDB_RECOVERY_ACTIVE);
5590                 talloc_free(tmp_ctx);
5591                 return -1;
5592         }
5593
5594
5595         /* thaw all nodes */
5596         nodes = list_of_active_nodes(ctdb, nodemap, tmp_ctx, true);
5597         if (ctdb_client_async_control(ctdb, CTDB_CONTROL_THAW,
5598                                         nodes, 0,
5599                                         TIMELIMIT(),
5600                                         false, tdb_null,
5601                                         NULL, NULL,
5602                                         NULL) != 0) {
5603                 DEBUG(DEBUG_ERR, ("Unable to thaw nodes.\n"));
5604                 ctdb_ctrl_setrecmode(ctdb, TIMELIMIT(), options.pnn, CTDB_RECOVERY_ACTIVE);
5605                 talloc_free(tmp_ctx);
5606                 return -1;
5607         }
5608
5609
5610         talloc_free(tmp_ctx);
5611         return 0;
5612 }
5613
5614 /*
5615  * dump a database backup from a file
5616  */
5617 static int control_dumpdbbackup(struct ctdb_context *ctdb, int argc, const char **argv)
5618 {
5619         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
5620         TDB_DATA outdata;
5621         struct db_file_header dbhdr;
5622         int i, fh;
5623         struct tm *tm;
5624         char tbuf[100];
5625         struct ctdb_rec_data_old *rec = NULL;
5626         struct ctdb_marshall_buffer *m;
5627         struct ctdb_dump_db_context c;
5628
5629         assert_single_node_only();
5630
5631         if (argc != 1) {
5632                 DEBUG(DEBUG_ERR,("Invalid arguments\n"));
5633                 return -1;
5634         }
5635
5636         fh = open(argv[0], O_RDONLY);
5637         if (fh == -1) {
5638                 DEBUG(DEBUG_ERR,("Failed to open file '%s'\n", argv[0]));
5639                 talloc_free(tmp_ctx);
5640                 return -1;
5641         }
5642
5643         sys_read(fh, &dbhdr, sizeof(dbhdr));
5644         if (dbhdr.version != DB_VERSION) {
5645                 DEBUG(DEBUG_ERR,("Invalid version of database dump. File is version %lu but expected version was %u\n", dbhdr.version, DB_VERSION));
5646                 close(fh);
5647                 talloc_free(tmp_ctx);
5648                 return -1;
5649         }
5650
5651         outdata.dsize = dbhdr.size;
5652         outdata.dptr = talloc_size(tmp_ctx, outdata.dsize);
5653         if (outdata.dptr == NULL) {
5654                 DEBUG(DEBUG_ERR,("Failed to allocate data of size '%lu'\n", dbhdr.size));
5655                 close(fh);
5656                 talloc_free(tmp_ctx);
5657                 return -1;
5658         }
5659         sys_read(fh, outdata.dptr, outdata.dsize);
5660         close(fh);
5661         m = (struct ctdb_marshall_buffer *)outdata.dptr;
5662
5663         tm = localtime(&dbhdr.timestamp);
5664         strftime(tbuf,sizeof(tbuf)-1,"%Y/%m/%d %H:%M:%S", tm);
5665         printf("Backup of database name:'%s' dbid:0x%x08x from @ %s\n",
5666                 dbhdr.name, m->db_id, tbuf);
5667
5668         ZERO_STRUCT(c);
5669         c.ctdb = ctdb;
5670         c.f = stdout;
5671         c.printemptyrecords = (bool)options.printemptyrecords;
5672         c.printdatasize = (bool)options.printdatasize;
5673         c.printlmaster = false;
5674         c.printhash = (bool)options.printhash;
5675         c.printrecordflags = (bool)options.printrecordflags;
5676
5677         for (i=0; i < m->count; i++) {
5678                 uint32_t reqid = 0;
5679                 TDB_DATA key, data;
5680
5681                 /* we do not want the header splitted, so we pass NULL*/
5682                 rec = ctdb_marshall_loop_next(m, rec, &reqid,
5683                                               NULL, &key, &data);
5684
5685                 ctdb_dumpdb_record(key, data, &c);
5686         }
5687
5688         printf("Dumped %d records\n", i);
5689         talloc_free(tmp_ctx);
5690         return 0;
5691 }
5692
5693 /*
5694  * wipe a database from a file
5695  */
5696 static int control_wipedb(struct ctdb_context *ctdb, int argc,
5697                           const char **argv)
5698 {
5699         const char *db_name;
5700         int ret;
5701         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
5702         TDB_DATA data;
5703         struct ctdb_db_context *ctdb_db;
5704         struct ctdb_node_map_old *nodemap = NULL;
5705         struct ctdb_vnn_map *vnnmap = NULL;
5706         int i;
5707         struct ctdb_transdb w;
5708         uint32_t *nodes;
5709         uint32_t generation;
5710         uint8_t flags;
5711
5712         assert_single_node_only();
5713
5714         if (argc != 1) {
5715                 DEBUG(DEBUG_ERR,("Invalid arguments\n"));
5716                 return -1;
5717         }
5718
5719         if (!db_exists(ctdb, argv[0], NULL, &db_name, &flags)) {
5720                 return -1;
5721         }
5722
5723         ctdb_db = ctdb_attach(ctdb, TIMELIMIT(), db_name, flags & CTDB_DB_FLAGS_PERSISTENT, 0);
5724         if (ctdb_db == NULL) {
5725                 DEBUG(DEBUG_ERR, ("Unable to attach to database '%s'\n",
5726                                   argv[0]));
5727                 talloc_free(tmp_ctx);
5728                 return -1;
5729         }
5730
5731         ret = ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), options.pnn, ctdb,
5732                                    &nodemap);
5733         if (ret != 0) {
5734                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from node %u\n",
5735                                   options.pnn));
5736                 talloc_free(tmp_ctx);
5737                 return ret;
5738         }
5739
5740         ret = ctdb_ctrl_getvnnmap(ctdb, TIMELIMIT(), options.pnn, tmp_ctx,
5741                                   &vnnmap);
5742         if (ret != 0) {
5743                 DEBUG(DEBUG_ERR, ("Unable to get vnnmap from node %u\n",
5744                                   options.pnn));
5745                 talloc_free(tmp_ctx);
5746                 return ret;
5747         }
5748
5749         /* freeze all nodes */
5750         nodes = list_of_active_nodes(ctdb, nodemap, tmp_ctx, true);
5751         for (i=1; i<=NUM_DB_PRIORITIES; i++) {
5752                 ret = ctdb_client_async_control(ctdb, CTDB_CONTROL_FREEZE,
5753                                                 nodes, i,
5754                                                 TIMELIMIT(),
5755                                                 false, tdb_null,
5756                                                 NULL, NULL,
5757                                                 NULL);
5758                 if (ret != 0) {
5759                         DEBUG(DEBUG_ERR, ("Unable to freeze nodes.\n"));
5760                         ctdb_ctrl_setrecmode(ctdb, TIMELIMIT(), options.pnn,
5761                                              CTDB_RECOVERY_ACTIVE);
5762                         talloc_free(tmp_ctx);
5763                         return -1;
5764                 }
5765         }
5766
5767         generation = vnnmap->generation;
5768         data.dptr = (void *)&generation;
5769         data.dsize = sizeof(generation);
5770
5771         /* start a cluster wide transaction */
5772         nodes = list_of_active_nodes(ctdb, nodemap, tmp_ctx, true);
5773         ret = ctdb_client_async_control(ctdb, CTDB_CONTROL_TRANSACTION_START,
5774                                         nodes, 0,
5775                                         TIMELIMIT(), false, data,
5776                                         NULL, NULL,
5777                                         NULL);
5778         if (ret!= 0) {
5779                 DEBUG(DEBUG_ERR, ("Unable to start cluster wide "
5780                                   "transactions.\n"));
5781                 return -1;
5782         }
5783
5784         w.db_id = ctdb_db->db_id;
5785         w.tid = generation;
5786
5787         data.dptr = (void *)&w;
5788         data.dsize = sizeof(w);
5789
5790         /* wipe all the remote databases. */
5791         nodes = list_of_active_nodes(ctdb, nodemap, tmp_ctx, true);
5792         if (ctdb_client_async_control(ctdb, CTDB_CONTROL_WIPE_DATABASE,
5793                                         nodes, 0,
5794                                         TIMELIMIT(), false, data,
5795                                         NULL, NULL,
5796                                         NULL) != 0) {
5797                 DEBUG(DEBUG_ERR, ("Unable to wipe database.\n"));
5798                 ctdb_ctrl_setrecmode(ctdb, TIMELIMIT(), options.pnn, CTDB_RECOVERY_ACTIVE);
5799                 talloc_free(tmp_ctx);
5800                 return -1;
5801         }
5802
5803         data.dptr = (void *)&ctdb_db->db_id;
5804         data.dsize = sizeof(ctdb_db->db_id);
5805
5806         /* mark the database as healthy */
5807         nodes = list_of_active_nodes(ctdb, nodemap, tmp_ctx, true);
5808         if (ctdb_client_async_control(ctdb, CTDB_CONTROL_DB_SET_HEALTHY,
5809                                         nodes, 0,
5810                                         TIMELIMIT(), false, data,
5811                                         NULL, NULL,
5812                                         NULL) != 0) {
5813                 DEBUG(DEBUG_ERR, ("Failed to mark database as healthy.\n"));
5814                 ctdb_ctrl_setrecmode(ctdb, TIMELIMIT(), options.pnn, CTDB_RECOVERY_ACTIVE);
5815                 talloc_free(tmp_ctx);
5816                 return -1;
5817         }
5818
5819         data.dptr = (void *)&generation;
5820         data.dsize = sizeof(generation);
5821
5822         /* commit all the changes */
5823         if (ctdb_client_async_control(ctdb, CTDB_CONTROL_TRANSACTION_COMMIT,
5824                                         nodes, 0,
5825                                         TIMELIMIT(), false, data,
5826                                         NULL, NULL,
5827                                         NULL) != 0) {
5828                 DEBUG(DEBUG_ERR, ("Unable to commit databases.\n"));
5829                 ctdb_ctrl_setrecmode(ctdb, TIMELIMIT(), options.pnn, CTDB_RECOVERY_ACTIVE);
5830                 talloc_free(tmp_ctx);
5831                 return -1;
5832         }
5833
5834         /* thaw all nodes */
5835         nodes = list_of_active_nodes(ctdb, nodemap, tmp_ctx, true);
5836         if (ctdb_client_async_control(ctdb, CTDB_CONTROL_THAW,
5837                                         nodes, 0,
5838                                         TIMELIMIT(),
5839                                         false, tdb_null,
5840                                         NULL, NULL,
5841                                         NULL) != 0) {
5842                 DEBUG(DEBUG_ERR, ("Unable to thaw nodes.\n"));
5843                 ctdb_ctrl_setrecmode(ctdb, TIMELIMIT(), options.pnn, CTDB_RECOVERY_ACTIVE);
5844                 talloc_free(tmp_ctx);
5845                 return -1;
5846         }
5847
5848         DEBUG(DEBUG_ERR, ("Database wiped.\n"));
5849
5850         talloc_free(tmp_ctx);
5851         return 0;
5852 }
5853
5854 /*
5855   dump memory usage
5856  */
5857 static int control_dumpmemory(struct ctdb_context *ctdb, int argc, const char **argv)
5858 {
5859         TDB_DATA data;
5860         int ret;
5861         int32_t res;
5862         char *errmsg;
5863         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
5864         ret = ctdb_control(ctdb, options.pnn, 0, CTDB_CONTROL_DUMP_MEMORY,
5865                            0, tdb_null, tmp_ctx, &data, &res, NULL, &errmsg);
5866         if (ret != 0 || res != 0) {
5867                 DEBUG(DEBUG_ERR,("Failed to dump memory - %s\n", errmsg));
5868                 talloc_free(tmp_ctx);
5869                 return -1;
5870         }
5871         sys_write(1, data.dptr, data.dsize);
5872         talloc_free(tmp_ctx);
5873         return 0;
5874 }
5875
5876 /*
5877   handler for memory dumps
5878 */
5879 static void mem_dump_handler(uint64_t srvid, TDB_DATA data, void *private_data)
5880 {
5881         sys_write(1, data.dptr, data.dsize);
5882         exit(0);
5883 }
5884
5885 /*
5886   dump memory usage on the recovery daemon
5887  */
5888 static int control_rddumpmemory(struct ctdb_context *ctdb, int argc, const char **argv)
5889 {
5890         int ret;
5891         TDB_DATA data;
5892         struct ctdb_srvid_message rd;
5893
5894         rd.pnn = ctdb_get_pnn(ctdb);
5895         rd.srvid = getpid();
5896
5897         /* register a message port for receiveing the reply so that we
5898            can receive the reply
5899         */
5900         ctdb_client_set_message_handler(ctdb, rd.srvid, mem_dump_handler, NULL);
5901
5902
5903         data.dptr = (uint8_t *)&rd;
5904         data.dsize = sizeof(rd);
5905
5906         ret = ctdb_client_send_message(ctdb, options.pnn, CTDB_SRVID_MEM_DUMP, data);
5907         if (ret != 0) {
5908                 DEBUG(DEBUG_ERR,("Failed to send memdump request message to %u\n", options.pnn));
5909                 return -1;
5910         }
5911
5912         /* this loop will terminate when we have received the reply */
5913         while (1) {
5914                 tevent_loop_once(ctdb->ev);
5915         }
5916
5917         return 0;
5918 }
5919
5920 /*
5921   send a message to a srvid
5922  */
5923 static int control_msgsend(struct ctdb_context *ctdb, int argc, const char **argv)
5924 {
5925         unsigned long srvid;
5926         int ret;
5927         TDB_DATA data;
5928
5929         if (argc < 2) {
5930                 usage();
5931         }
5932
5933         srvid      = strtoul(argv[0], NULL, 0);
5934
5935         data.dptr = (uint8_t *)discard_const(argv[1]);
5936         data.dsize= strlen(argv[1]);
5937
5938         ret = ctdb_client_send_message(ctdb, CTDB_BROADCAST_CONNECTED, srvid, data);
5939         if (ret != 0) {
5940                 DEBUG(DEBUG_ERR,("Failed to send memdump request message to %u\n", options.pnn));
5941                 return -1;
5942         }
5943
5944         return 0;
5945 }
5946
5947 /*
5948   handler for msglisten
5949 */
5950 static void msglisten_handler(uint64_t srvid, TDB_DATA data,
5951                               void *private_data)
5952 {
5953         int i;
5954
5955         printf("Message received: ");
5956         for (i=0;i<data.dsize;i++) {
5957                 printf("%c", data.dptr[i]);
5958         }
5959         printf("\n");
5960 }
5961
5962 /*
5963   listen for messages on a messageport
5964  */
5965 static int control_msglisten(struct ctdb_context *ctdb, int argc, const char **argv)
5966 {
5967         uint64_t srvid;
5968
5969         srvid = getpid();
5970
5971         /* register a message port and listen for messages
5972         */
5973         ctdb_client_set_message_handler(ctdb, srvid, msglisten_handler, NULL);
5974         printf("Listening for messages on srvid:%d\n", (int)srvid);
5975
5976         while (1) {
5977                 tevent_loop_once(ctdb->ev);
5978         }
5979
5980         return 0;
5981 }
5982
5983 /*
5984   list all nodes in the cluster
5985   we parse the nodes file directly
5986  */
5987 static int control_listnodes(struct ctdb_context *ctdb, int argc, const char **argv)
5988 {
5989         TALLOC_CTX *mem_ctx = talloc_new(NULL);
5990         struct ctdb_node_map_old *node_map;
5991         int i;
5992
5993         assert_single_node_only();
5994
5995         node_map = read_nodes_file(mem_ctx);
5996         if (node_map == NULL) {
5997                 talloc_free(mem_ctx);
5998                 return -1;
5999         }
6000
6001         for (i = 0; i < node_map->num; i++) {
6002                 const char *addr;
6003
6004                 if (node_map->nodes[i].flags & NODE_FLAGS_DELETED) {
6005                         continue;
6006                 }
6007                 addr = ctdb_addr_to_str(&node_map->nodes[i].addr);
6008                 if (options.machinereadable){
6009                         printm(":%d:%s:\n", node_map->nodes[i].pnn, addr);
6010                 } else {
6011                         printf("%s\n", addr);
6012                 }
6013         }
6014         talloc_free(mem_ctx);
6015
6016         return 0;
6017 }
6018
6019 /**********************************************************************/
6020 /* reload the nodes file on all nodes */
6021
6022 static void get_nodes_files_callback(struct ctdb_context *ctdb,
6023                                      uint32_t node_pnn, int32_t res,
6024                                      TDB_DATA outdata, void *callback_data)
6025 {
6026         struct ctdb_node_map_old **maps =
6027                 talloc_get_type(callback_data, struct ctdb_node_map_old *);
6028
6029         if (outdata.dsize < offsetof(struct ctdb_node_map_old, nodes) ||
6030             outdata.dptr == NULL) {
6031                 DEBUG(DEBUG_ERR,
6032                       (__location__ " Invalid return data: %u %p\n",
6033                        (unsigned)outdata.dsize, outdata.dptr));
6034                 return;
6035         }
6036
6037         if (node_pnn >= talloc_array_length(maps)) {
6038                 DEBUG(DEBUG_ERR,
6039                       (__location__ " unexpected PNN %u\n", node_pnn));
6040                 return;
6041         }
6042
6043         maps[node_pnn] = talloc_memdup(maps, outdata.dptr, outdata.dsize);
6044 }
6045
6046 static void get_nodes_files_fail_callback(struct ctdb_context *ctdb,
6047                                           uint32_t node_pnn, int32_t res,
6048                                           TDB_DATA outdata, void *callback_data)
6049 {
6050         DEBUG(DEBUG_ERR,
6051               ("ERROR: Failed to get nodes file from node %u\n", node_pnn));
6052 }
6053
6054 static struct ctdb_node_map_old **
6055 ctdb_get_nodes_files(struct ctdb_context *ctdb,
6056                      TALLOC_CTX *mem_ctx,
6057                      struct timeval timeout,
6058                      struct ctdb_node_map_old *nodemap)
6059 {
6060         uint32_t *nodes;
6061         int ret;
6062         struct ctdb_node_map_old **maps;
6063
6064         maps = talloc_zero_array(mem_ctx, struct ctdb_node_map_old *, nodemap->num);
6065         CTDB_NO_MEMORY_NULL(ctdb, maps);
6066
6067         nodes = list_of_connected_nodes(ctdb, nodemap, mem_ctx, true);
6068
6069         ret = ctdb_client_async_control(ctdb, CTDB_CONTROL_GET_NODES_FILE,
6070                                         nodes, 0, TIMELIMIT(),
6071                                         true, tdb_null,
6072                                         get_nodes_files_callback,
6073                                         get_nodes_files_fail_callback,
6074                                         maps);
6075         if (ret != 0) {
6076                 talloc_free(maps);
6077                 return NULL;
6078         }
6079
6080         return maps;
6081 }
6082
6083 static bool node_files_are_identical(struct ctdb_node_map_old *nm1,
6084                                      struct ctdb_node_map_old *nm2)
6085 {
6086         int i;
6087
6088         if (nm1->num != nm2->num) {
6089                 return false;
6090         }
6091         for (i = 0; i < nm1->num; i++) {
6092                 if (memcmp(&nm1->nodes[i], &nm2->nodes[i],
6093                            sizeof(struct ctdb_node_and_flags)) != 0) {
6094                         return false;
6095                 }
6096         }
6097
6098         return true;
6099 }
6100
6101 static bool check_all_node_files_are_identical(struct ctdb_context *ctdb,
6102                                                TALLOC_CTX *mem_ctx,
6103                                                struct timeval timeout,
6104                                                struct ctdb_node_map_old *nodemap,
6105                                                struct ctdb_node_map_old *file_nodemap)
6106 {
6107         static struct ctdb_node_map_old **maps;
6108         int i;
6109         bool ret = true;
6110
6111         maps = ctdb_get_nodes_files(ctdb, mem_ctx, timeout, nodemap);
6112         if (maps == NULL) {
6113                 return false;
6114         }
6115
6116         for (i = 0; i < talloc_array_length(maps); i++) {
6117                 if (maps[i] == NULL) {
6118                         continue;
6119                 }
6120                 if (!node_files_are_identical(file_nodemap, maps[i])) {
6121                         DEBUG(DEBUG_ERR,
6122                               ("ERROR: Node file on node %u differs from current node (%u)\n",
6123                                i, ctdb_get_pnn(ctdb)));
6124                         ret = false;
6125                 }
6126         }
6127
6128         return ret;
6129 }
6130
6131 /*
6132   reload the nodes file on the local node
6133  */
6134 static bool sanity_check_nodes_file_changes(TALLOC_CTX *mem_ctx,
6135                                             struct ctdb_node_map_old *nodemap,
6136                                             struct ctdb_node_map_old *file_nodemap)
6137 {
6138         int i;
6139         bool should_abort = false;
6140         bool have_changes = false;
6141
6142         for (i=0; i<nodemap->num; i++) {
6143                 if (i >= file_nodemap->num) {
6144                         DEBUG(DEBUG_ERR,
6145                               ("ERROR: Node %u (%s) missing from nodes file\n",
6146                                nodemap->nodes[i].pnn,
6147                                ctdb_addr_to_str(&nodemap->nodes[i].addr)));
6148                         should_abort = true;
6149                         continue;
6150                 }
6151                 if (nodemap->nodes[i].flags & NODE_FLAGS_DELETED &&
6152                     file_nodemap->nodes[i].flags & NODE_FLAGS_DELETED) {
6153                         /* Node remains deleted */
6154                         DEBUG(DEBUG_INFO,
6155                               ("Node %u is unchanged (DELETED)\n",
6156                                nodemap->nodes[i].pnn));
6157                 } else if (!(nodemap->nodes[i].flags & NODE_FLAGS_DELETED) &&
6158                            !(file_nodemap->nodes[i].flags & NODE_FLAGS_DELETED)) {
6159                         /* Node not newly nor previously deleted */
6160                         if (!ctdb_same_ip(&nodemap->nodes[i].addr,
6161                                           &file_nodemap->nodes[i].addr)) {
6162                                 DEBUG(DEBUG_ERR,
6163                                       ("ERROR: Node %u has changed IP address (was %s, now %s)\n",
6164                                        nodemap->nodes[i].pnn,
6165                                        /* ctdb_addr_to_str() returns a static */
6166                                        talloc_strdup(mem_ctx,
6167                                                      ctdb_addr_to_str(&nodemap->nodes[i].addr)),
6168                                        ctdb_addr_to_str(&file_nodemap->nodes[i].addr)));
6169                                 should_abort = true;
6170                         } else {
6171                                 DEBUG(DEBUG_INFO,
6172                                       ("Node %u is unchanged\n",
6173                                        nodemap->nodes[i].pnn));
6174                                 if (nodemap->nodes[i].flags & NODE_FLAGS_DISCONNECTED) {
6175                                         DEBUG(DEBUG_WARNING,
6176                                               ("WARNING: Node %u is disconnected. You MUST fix this node manually!\n",
6177                                                nodemap->nodes[i].pnn));
6178                                 }
6179                         }
6180                 } else if (file_nodemap->nodes[i].flags & NODE_FLAGS_DELETED) {
6181                         /* Node is being deleted */
6182                         DEBUG(DEBUG_NOTICE,
6183                               ("Node %u is DELETED\n",
6184                                nodemap->nodes[i].pnn));
6185                         have_changes = true;
6186                         if (!(nodemap->nodes[i].flags & NODE_FLAGS_DISCONNECTED)) {
6187                                 DEBUG(DEBUG_ERR,
6188                                       ("ERROR: Node %u is still connected\n",
6189                                        nodemap->nodes[i].pnn));
6190                                 should_abort = true;
6191                         }
6192                 } else if (nodemap->nodes[i].flags & NODE_FLAGS_DELETED) {
6193                         /* Node was previously deleted */
6194                         DEBUG(DEBUG_NOTICE,
6195                               ("Node %u is UNDELETED\n", nodemap->nodes[i].pnn));
6196                         have_changes = true;
6197                 }
6198         }
6199
6200         if (should_abort) {
6201                 DEBUG(DEBUG_ERR,
6202                       ("ERROR: Nodes will not be reloaded due to previous error\n"));
6203                 talloc_free(mem_ctx);
6204                 exit(1);
6205         }
6206
6207         /* Leftover nodes in file are NEW */
6208         for (; i < file_nodemap->num; i++) {
6209                 DEBUG(DEBUG_NOTICE, ("Node %u is NEW\n",
6210                                      file_nodemap->nodes[i].pnn));
6211                 have_changes = true;
6212         }
6213
6214         return have_changes;
6215 }
6216
6217 static void reload_nodes_fail_callback(struct ctdb_context *ctdb,
6218                                        uint32_t node_pnn, int32_t res,
6219                                        TDB_DATA outdata, void *callback_data)
6220 {
6221         DEBUG(DEBUG_WARNING,
6222               ("WARNING: Node %u failed to reload nodes. You MUST fix this node manually!\n",
6223                node_pnn));
6224 }
6225
6226 static int control_reload_nodes_file(struct ctdb_context *ctdb, int argc, const char **argv)
6227 {
6228         int i, ret;
6229         struct ctdb_node_map_old *nodemap=NULL;
6230         TALLOC_CTX *tmp_ctx = talloc_new(NULL);
6231         struct ctdb_node_map_old *file_nodemap;
6232         uint32_t *conn;
6233         uint32_t timeout;
6234
6235         assert_current_node_only(ctdb);
6236
6237         /* Load both the current nodemap and the contents of the local
6238          * nodes file.  Compare and sanity check them before doing
6239          * anything. */
6240
6241         ret = ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE, ctdb, &nodemap);
6242         if (ret != 0) {
6243                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from local node\n"));
6244                 return ret;
6245         }
6246
6247         file_nodemap = read_nodes_file(tmp_ctx);
6248         if (file_nodemap == NULL) {
6249                 DEBUG(DEBUG_ERR,("Failed to read nodes file\n"));
6250                 talloc_free(tmp_ctx);
6251                 return -1;
6252         }
6253
6254         if (!check_all_node_files_are_identical(ctdb, tmp_ctx, TIMELIMIT(),
6255                                                 nodemap, file_nodemap)) {
6256                 return -1;
6257         }
6258
6259         if (!sanity_check_nodes_file_changes(tmp_ctx, nodemap, file_nodemap)) {
6260                 DEBUG(DEBUG_NOTICE,
6261                       ("No change in nodes file, skipping unnecessary reload\n"));
6262                 talloc_free(tmp_ctx);
6263                 return 0;
6264         }
6265
6266         /* Now make the changes */
6267         conn = list_of_connected_nodes(ctdb, nodemap, tmp_ctx, true);
6268         for (i = 0; i < talloc_array_length(conn); i++) {
6269                 DEBUG(DEBUG_NOTICE, ("Reloading nodes file on node %u\n",
6270                                      conn[i]));
6271         }
6272
6273         /* Another timeout could be used, such as ReRecoveryTimeout or
6274          * a new one for this purpose.  However, this is the simplest
6275          * option. */
6276         timeout = options.timelimit;
6277         srvid_broadcast(ctdb, CTDB_SRVID_DISABLE_RECOVERIES, &timeout,
6278                         "Disable recoveries", true);
6279
6280
6281         ret = ctdb_client_async_control(ctdb, CTDB_CONTROL_RELOAD_NODES_FILE,
6282                                         conn, 0, TIMELIMIT(),
6283                                         true, tdb_null,
6284                                         NULL, reload_nodes_fail_callback,
6285                                         NULL);
6286
6287         timeout = 0;
6288         srvid_broadcast(ctdb, CTDB_SRVID_DISABLE_RECOVERIES, &timeout,
6289                         "Enable recoveries", true);
6290
6291         talloc_free(tmp_ctx);
6292
6293         return 0;
6294 }
6295
6296
6297 static const struct {
6298         const char *name;
6299         int (*fn)(struct ctdb_context *, int, const char **);
6300         bool auto_all;
6301         bool without_daemon; /* can be run without daemon running ? */
6302         const char *msg;
6303         const char *args;
6304 } ctdb_commands[] = {
6305         { "version",         control_version,           true,   true,   "show version of ctdb" },
6306         { "status",          control_status,            true,   false,  "show node status" },
6307         { "uptime",          control_uptime,            true,   false,  "show node uptime" },
6308         { "ping",            control_ping,              true,   false,  "ping all nodes" },
6309         { "runstate",        control_runstate,          true,   false,  "get/check runstate of a node", "[setup|first_recovery|startup|running]" },
6310         { "getvar",          control_getvar,            true,   false,  "get a tunable variable",               "<name>"},
6311         { "setvar",          control_setvar,            true,   false,  "set a tunable variable",               "<name> <value>"},
6312         { "listvars",        control_listvars,          true,   false,  "list tunable variables"},
6313         { "statistics",      control_statistics,        false,  false, "show statistics" },
6314         { "statisticsreset", control_statistics_reset,  true,   false,  "reset statistics"},
6315         { "stats",           control_stats,             false,  false,  "show rolling statistics", "[number of history records]" },
6316         { "ip",              control_ip,                false,  false,  "show which public ip's that ctdb manages" },
6317         { "ipinfo",          control_ipinfo,            true,   false,  "show details about a public ip that ctdb manages", "<ip>" },
6318         { "ifaces",          control_ifaces,            true,   false,  "show which interfaces that ctdb manages" },
6319         { "setifacelink",    control_setifacelink,      true,   false,  "set interface link status", "<iface> <status>" },
6320         { "process-exists",  control_process_exists,    true,   false,  "check if a process exists on a node",  "<pid>"},
6321         { "getdbmap",        control_getdbmap,          true,   false,  "show the database map" },
6322         { "getdbstatus",     control_getdbstatus,       true,   false,  "show the status of a database", "<dbname|dbid>" },
6323         { "catdb",           control_catdb,             true,   false,  "dump a ctdb database" ,                     "<dbname|dbid>"},
6324         { "cattdb",          control_cattdb,            true,   false,  "dump a local tdb database" ,                     "<dbname|dbid>"},
6325         { "getmonmode",      control_getmonmode,        true,   false,  "show monitoring mode" },
6326         { "getcapabilities", control_getcapabilities,   true,   false,  "show node capabilities" },
6327         { "pnn",             control_pnn,               true,   false,  "show the pnn of the currnet node" },
6328         { "lvs",             control_lvs,               true,   false,  "show lvs configuration" },
6329         { "lvsmaster",       control_lvsmaster,         true,   false,  "show which node is the lvs master" },
6330         { "disablemonitor",      control_disable_monmode,true,  false,  "set monitoring mode to DISABLE" },
6331         { "enablemonitor",      control_enable_monmode, true,   false,  "set monitoring mode to ACTIVE" },
6332         { "setdebug",        control_setdebug,          true,   false,  "set debug level",                      "<EMERG|ALERT|CRIT|ERR|WARNING|NOTICE|INFO|DEBUG>" },
6333         { "getdebug",        control_getdebug,          true,   false,  "get debug level" },
6334         { "attach",          control_attach,            true,   false,  "attach to a database",                 "<dbname> [persistent]" },
6335         { "detach",          control_detach,            false,  false,  "detach from a database",                 "<dbname|dbid> [<dbname|dbid> ...]" },
6336         { "dumpmemory",      control_dumpmemory,        true,   false,  "dump memory map to stdout" },
6337         { "rddumpmemory",    control_rddumpmemory,      true,   false,  "dump memory map from the recovery daemon to stdout" },
6338         { "getpid",          control_getpid,            true,   false,  "get ctdbd process ID" },
6339         { "disable",         control_disable,           true,   false,  "disable a nodes public IP" },
6340         { "enable",          control_enable,            true,   false,  "enable a nodes public IP" },
6341         { "stop",            control_stop,              true,   false,  "stop a node" },
6342         { "continue",        control_continue,          true,   false,  "re-start a stopped node" },
6343         { "ban",             control_ban,               true,   false,  "ban a node from the cluster",          "<bantime>"},
6344         { "unban",           control_unban,             true,   false,  "unban a node" },
6345         { "showban",         control_showban,           true,   false,  "show ban information"},
6346         { "shutdown",        control_shutdown,          true,   false,  "shutdown ctdbd" },
6347         { "recover",         control_recover,           true,   false,  "force recovery" },
6348         { "sync",            control_ipreallocate,      false,  false,  "wait until ctdbd has synced all state changes" },
6349         { "ipreallocate",    control_ipreallocate,      false,  false,  "force the recovery daemon to perform a ip reallocation procedure" },
6350         { "thaw",            control_thaw,              true,   false,  "thaw databases", "[priority:1-3]" },
6351         { "isnotrecmaster",  control_isnotrecmaster,    false,  false,  "check if the local node is recmaster or not" },
6352         { "killtcp",         kill_tcp,                  false,  false, "kill a tcp connection.", "[<srcip:port> <dstip:port>]" },
6353         { "gratiousarp",     control_gratious_arp,      false,  false, "send a gratious arp", "<ip> <interface>" },
6354         { "tickle",          tickle_tcp,                false,  false, "send a tcp tickle ack", "<srcip:port> <dstip:port>" },
6355         { "gettickles",      control_get_tickles,       false,  false, "get the list of tickles registered for this ip", "<ip> [<port>]" },
6356         { "addtickle",       control_add_tickle,        false,  false, "add a tickle for this ip", "<ip>:<port> <ip>:<port>" },
6357
6358         { "deltickle",       control_del_tickle,        false,  false, "delete a tickle from this ip", "<ip>:<port> <ip>:<port>" },
6359
6360         { "regsrvid",        regsrvid,                  false,  false, "register a server id", "<pnn> <type> <id>" },
6361         { "unregsrvid",      unregsrvid,                false,  false, "unregister a server id", "<pnn> <type> <id>" },
6362         { "chksrvid",        chksrvid,                  false,  false, "check if a server id exists", "<pnn> <type> <id>" },
6363         { "getsrvids",       getsrvids,                 false,  false, "get a list of all server ids"},
6364         { "check_srvids",    check_srvids,              false,  false, "check if a srvid exists", "<id>+" },
6365         { "listnodes",       control_listnodes,         false,  true, "list all nodes in the cluster"},
6366         { "reloadnodes",     control_reload_nodes_file, false,  false, "reload the nodes file and restart the transport on all nodes"},
6367         { "moveip",          control_moveip,            false,  false, "move/failover an ip address to another node", "<ip> <node>"},
6368         { "rebalanceip",     control_rebalanceip,       false,  false, "release an ip from the node and let recd rebalance it", "<ip>"},
6369         { "addip",           control_addip,             true,   false, "add a ip address to a node", "<ip/mask> <iface>"},
6370         { "delip",           control_delip,             false,  false, "delete an ip address from a node", "<ip>"},
6371         { "eventscript",     control_eventscript,       true,   false, "run the eventscript with the given parameters on a node", "<arguments>"},
6372         { "backupdb",        control_backupdb,          false,  false, "backup the database into a file.", "<dbname|dbid> <file>"},
6373         { "restoredb",        control_restoredb,        false,  false, "restore the database from a file.", "<file> [dbname]"},
6374         { "dumpdbbackup",    control_dumpdbbackup,      false,  true,  "dump database backup from a file.", "<file>"},
6375         { "wipedb",           control_wipedb,        false,     false, "wipe the contents of a database.", "<dbname|dbid>"},
6376         { "recmaster",        control_recmaster,        true,   false, "show the pnn for the recovery master."},
6377         { "scriptstatus",     control_scriptstatus,     true,   false, "show the status of the monitoring scripts (or all scripts)", "[all]"},
6378         { "enablescript",     control_enablescript,  true,      false, "enable an eventscript", "<script>"},
6379         { "disablescript",    control_disablescript,  true,     false, "disable an eventscript", "<script>"},
6380         { "natgwlist",        control_natgwlist,        false,  true, "show the nodes belonging to this natgw configuration"},
6381         { "xpnn",             control_xpnn,             false,  true,  "find the pnn of the local node without talking to the daemon (unreliable)" },
6382         { "getreclock",       control_getreclock,       true,   false, "Show the reclock file of a node"},
6383         { "setreclock",       control_setreclock,       true,   false, "Set/clear the reclock file of a node", "[filename]"},
6384         { "setlmasterrole",   control_setlmasterrole,   false,  false, "Set LMASTER role to on/off", "{on|off}"},
6385         { "setrecmasterrole", control_setrecmasterrole, false,  false, "Set RECMASTER role to on/off", "{on|off}"},
6386         { "setdbprio",        control_setdbprio,        false,  false, "Set DB priority", "<dbname|dbid> <prio:1-3>"},
6387         { "getdbprio",        control_getdbprio,        false,  false, "Get DB priority", "<dbname|dbid>"},
6388         { "setdbreadonly",    control_setdbreadonly,    false,  false, "Set DB readonly capable", "<dbname|dbid>"},
6389         { "setdbsticky",      control_setdbsticky,      false,  false, "Set DB sticky-records capable", "<dbname|dbid>"},
6390         { "msglisten",        control_msglisten,        false,  false, "Listen on a srvid port for messages", "<msg srvid>"},
6391         { "msgsend",          control_msgsend,  false,  false, "Send a message to srvid", "<srvid> <message>"},
6392         { "pfetch",          control_pfetch,            false,  false,  "fetch a record from a persistent database", "<dbname|dbid> <key> [<file>]" },
6393         { "pstore",          control_pstore,            false,  false,  "write a record to a persistent database", "<dbname|dbid> <key> <file containing record>" },
6394         { "pdelete",         control_pdelete,           false,  false,  "delete a record from a persistent database", "<dbname|dbid> <key>" },
6395         { "ptrans",          control_ptrans,            false,  false,  "update a persistent database (from stdin)", "<dbname|dbid>" },
6396         { "tfetch",          control_tfetch,            false,  true,  "fetch a record from a [c]tdb-file [-v]", "<tdb-file> <key> [<file>]" },
6397         { "tstore",          control_tstore,            false,  true,  "store a record (including ltdb header)", "<tdb-file> <key> <data> [<rsn> <dmaster> <flags>]" },
6398         { "readkey",         control_readkey,           true,   false,  "read the content off a database key", "<dbname|dbid> <key>" },
6399         { "writekey",        control_writekey,          true,   false,  "write to a database key", "<dbname|dbid> <key> <value>" },
6400         { "checktcpport",    control_chktcpport,        false,  true,  "check if a service is bound to a specific tcp port or not", "<port>" },
6401         { "rebalancenode",     control_rebalancenode,   false,  false, "mark nodes as forced IP rebalancing targets", "[<pnn-list>]"},
6402         { "getdbseqnum",     control_getdbseqnum,       false,  false, "get the sequence number off a database", "<dbname|dbid>" },
6403         { "nodestatus",      control_nodestatus,        true,   false,  "show and return node status", "[<pnn-list>]" },
6404         { "dbstatistics",    control_dbstatistics,      false,  false, "show db statistics", "<dbname|dbid>" },
6405         { "reloadips",       control_reloadips,         false,  false, "reload the public addresses file on specified nodes" , "[<pnn-list>]" },
6406         { "ipiface",         control_ipiface,           false,  true,  "Find which interface an ip address is hosted on", "<ip>" },
6407 };
6408
6409 /*
6410   show usage message
6411  */
6412 static void usage(void)
6413 {
6414         int i;
6415         printf(
6416 "Usage: ctdb [options] <control>\n" \
6417 "Options:\n" \
6418 "   -n <node>          choose node number, or 'all' (defaults to local node)\n"
6419 "   -Y                 generate machine readable output\n"
6420 "   -x <char>          specify delimiter for machine readable output\n"
6421 "   -v                 generate verbose output\n"
6422 "   -t <timelimit>     set timelimit for control in seconds (default %u)\n", options.timelimit);
6423         printf("Controls:\n");
6424         for (i=0;i<ARRAY_SIZE(ctdb_commands);i++) {
6425                 printf("  %-15s %-27s  %s\n", 
6426                        ctdb_commands[i].name, 
6427                        ctdb_commands[i].args?ctdb_commands[i].args:"",
6428                        ctdb_commands[i].msg);
6429         }
6430         exit(1);
6431 }
6432
6433
6434 static void ctdb_alarm(int sig)
6435 {
6436         printf("Maximum runtime exceeded - exiting\n");
6437         _exit(ERR_TIMEOUT);
6438 }
6439
6440 /*
6441   main program
6442 */
6443 int main(int argc, const char *argv[])
6444 {
6445         struct ctdb_context *ctdb;
6446         char *nodestring = NULL;
6447         int machineparsable = 0;
6448         struct poptOption popt_options[] = {
6449                 POPT_AUTOHELP
6450                 POPT_CTDB_CMDLINE
6451                 { "timelimit", 't', POPT_ARG_INT, &options.timelimit, 0, "timelimit", "integer" },
6452                 { "node",      'n', POPT_ARG_STRING, &nodestring, 0, "node", "integer|all" },
6453                 { "machinereadable", 'Y', POPT_ARG_NONE, &options.machinereadable, 0, "enable machine readable output", NULL },
6454                 { NULL, 'x', POPT_ARG_STRING, &options.machineseparator, 0, "specify separator for machine readable output", "char" },
6455                 { NULL, 'X', POPT_ARG_NONE, &machineparsable, 0, "enable machine parsable output with separator |", NULL },
6456                 { "verbose",    'v', POPT_ARG_NONE, &options.verbose, 0, "enable verbose output", NULL },
6457                 { "maxruntime", 'T', POPT_ARG_INT, &options.maxruntime, 0, "die if runtime exceeds this limit (in seconds)", "integer" },
6458                 { "print-emptyrecords", 0, POPT_ARG_NONE, &options.printemptyrecords, 0, "print the empty records when dumping databases (catdb, cattdb, dumpdbbackup)", NULL },
6459                 { "print-datasize", 0, POPT_ARG_NONE, &options.printdatasize, 0, "do not print record data when dumping databases, only the data size", NULL },
6460                 { "print-lmaster", 0, POPT_ARG_NONE, &options.printlmaster, 0, "print the record's lmaster in catdb", NULL },
6461                 { "print-hash", 0, POPT_ARG_NONE, &options.printhash, 0, "print the record's hash when dumping databases", NULL },
6462                 { "print-recordflags", 0, POPT_ARG_NONE, &options.printrecordflags, 0, "print the record flags in catdb and dumpdbbackup", NULL },
6463                 POPT_TABLEEND
6464         };
6465         int opt;
6466         const char **extra_argv;
6467         int extra_argc = 0;
6468         int ret=-1, i;
6469         poptContext pc;
6470         struct tevent_context *ev;
6471         const char *control;
6472
6473         setlinebuf(stdout);
6474         
6475         /* set some defaults */
6476         options.maxruntime = 0;
6477         options.timelimit = 10;
6478         options.pnn = CTDB_CURRENT_NODE;
6479
6480         pc = poptGetContext(argv[0], argc, argv, popt_options, POPT_CONTEXT_KEEP_FIRST);
6481
6482         while ((opt = poptGetNextOpt(pc)) != -1) {
6483                 switch (opt) {
6484                 default:
6485                         DEBUG(DEBUG_ERR, ("Invalid option %s: %s\n", 
6486                                 poptBadOption(pc, 0), poptStrerror(opt)));
6487                         exit(1);
6488                 }
6489         }
6490
6491         /* setup the remaining options for the main program to use */
6492         extra_argv = poptGetArgs(pc);
6493         if (extra_argv) {
6494                 extra_argv++;
6495                 while (extra_argv[extra_argc]) extra_argc++;
6496         }
6497
6498         if (extra_argc < 1) {
6499                 usage();
6500         }
6501
6502         if (options.maxruntime == 0) {
6503                 const char *ctdb_timeout;
6504                 ctdb_timeout = getenv("CTDB_TIMEOUT");
6505                 if (ctdb_timeout != NULL) {
6506                         options.maxruntime = strtoul(ctdb_timeout, NULL, 0);
6507                 } else {
6508                         /* default timeout is 120 seconds */
6509                         options.maxruntime = 120;
6510                 }
6511         }
6512
6513         if (machineparsable) {
6514                 options.machineseparator = "|";
6515         }
6516         if (options.machineseparator != NULL) {
6517                 if (strlen(options.machineseparator) != 1) {
6518                         printf("Invalid separator \"%s\" - "
6519                                "must be single character\n",
6520                                options.machineseparator);
6521                         exit(1);
6522                 }
6523
6524                 /* -x implies -Y */
6525                 options.machinereadable = true;
6526         } else if (options.machinereadable) {
6527                 options.machineseparator = ":";
6528         }
6529
6530         signal(SIGALRM, ctdb_alarm);
6531         alarm(options.maxruntime);
6532
6533         control = extra_argv[0];
6534
6535         /* Default value for CTDB_BASE - don't override */
6536         setenv("CTDB_BASE", CTDB_ETCDIR, 0);
6537
6538         ev = tevent_context_init(NULL);
6539         if (!ev) {
6540                 DEBUG(DEBUG_ERR, ("Failed to initialize event system\n"));
6541                 exit(1);
6542         }
6543
6544         for (i=0;i<ARRAY_SIZE(ctdb_commands);i++) {
6545                 if (strcmp(control, ctdb_commands[i].name) == 0) {
6546                         break;
6547                 }
6548         }
6549
6550         if (i == ARRAY_SIZE(ctdb_commands)) {
6551                 DEBUG(DEBUG_ERR, ("Unknown control '%s'\n", control));
6552                 exit(1);
6553         }
6554
6555         if (ctdb_commands[i].without_daemon == true) {
6556                 if (nodestring != NULL) {
6557                         DEBUG(DEBUG_ERR, ("Can't specify node(s) with \"ctdb %s\"\n", control));
6558                         exit(1);
6559                 }
6560                 return ctdb_commands[i].fn(NULL, extra_argc-1, extra_argv+1);
6561         }
6562
6563         /* initialise ctdb */
6564         ctdb = ctdb_cmdline_client(ev, TIMELIMIT());
6565
6566         if (ctdb == NULL) {
6567                 uint32_t pnn;
6568                 DEBUG(DEBUG_ERR, ("Failed to init ctdb\n"));
6569
6570                 pnn = find_node_xpnn();
6571                 if (pnn == -1) {
6572                         DEBUG(DEBUG_ERR,
6573                               ("Is this node part of a CTDB cluster?\n"));
6574                 }
6575                 exit(1);
6576         }
6577
6578         /* setup the node number(s) to contact */
6579         if (!parse_nodestring(ctdb, ctdb, nodestring, CTDB_CURRENT_NODE, false,
6580                               &options.nodes, &options.pnn)) {
6581                 usage();
6582         }
6583
6584         if (options.pnn == CTDB_CURRENT_NODE) {
6585                 options.pnn = options.nodes[0];
6586         }
6587
6588         if (ctdb_commands[i].auto_all && 
6589             ((options.pnn == CTDB_BROADCAST_ALL) ||
6590              (options.pnn == CTDB_MULTICAST))) {
6591                 int j;
6592
6593                 ret = 0;
6594                 for (j = 0; j < talloc_array_length(options.nodes); j++) {
6595                         options.pnn = options.nodes[j];
6596                         ret |= ctdb_commands[i].fn(ctdb, extra_argc-1, extra_argv+1);
6597                 }
6598         } else {
6599                 ret = ctdb_commands[i].fn(ctdb, extra_argc-1, extra_argv+1);
6600         }
6601
6602         talloc_free(ctdb);
6603         talloc_free(ev);
6604         (void)poptFreeContext(pc);
6605
6606         return ret;
6607
6608 }