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