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