tools/ctdb: Fix a compiler warning
[obnox/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   move/failover an ip address to a specific node
1599  */
1600 static int control_moveip(struct ctdb_context *ctdb, int argc, const char **argv)
1601 {
1602         uint32_t pnn;
1603         int ret, retries = 0;
1604         ctdb_sock_addr addr;
1605
1606         if (argc < 2) {
1607                 usage();
1608                 return -1;
1609         }
1610
1611         if (parse_ip(argv[0], NULL, 0, &addr) == 0) {
1612                 DEBUG(DEBUG_ERR,("Wrongly formed ip address '%s'\n", argv[0]));
1613                 return -1;
1614         }
1615
1616
1617         if (sscanf(argv[1], "%u", &pnn) != 1) {
1618                 DEBUG(DEBUG_ERR, ("Badly formed pnn\n"));
1619                 return -1;
1620         }
1621
1622         do {
1623                 ret = move_ip(ctdb, &addr, pnn);
1624                 if (ret != 0) {
1625                         DEBUG(DEBUG_ERR,("Failed to move ip to node %d. Wait 3 second and try again.\n", pnn));
1626                         sleep(3);
1627                         retries++;
1628                 }
1629         } while (retries < 5 && ret != 0);
1630         if (ret != 0) {
1631                 DEBUG(DEBUG_ERR,("Failed to move ip to node %d. Giving up.\n", pnn));
1632                 return -1;
1633         }
1634
1635         return 0;
1636 }
1637
1638 static int rebalance_node(struct ctdb_context *ctdb, uint32_t pnn)
1639 {
1640         uint32_t recmaster;
1641         TDB_DATA data;
1642
1643         if (ctdb_ctrl_getrecmaster(ctdb, ctdb, TIMELIMIT(), pnn, &recmaster) != 0) {
1644                 DEBUG(DEBUG_ERR, ("Unable to get recmaster from node %u\n", pnn));
1645                 return -1;
1646         }
1647
1648         data.dptr  = (uint8_t *)&pnn;
1649         data.dsize = sizeof(uint32_t);
1650         if (ctdb_client_send_message(ctdb, recmaster, CTDB_SRVID_REBALANCE_NODE, data) != 0) {
1651                 DEBUG(DEBUG_ERR,("Failed to send message to force node reallocation\n"));
1652                 return -1;
1653         }
1654
1655         return 0;
1656 }
1657
1658
1659 /*
1660   rebalance a node by setting it to allow failback and triggering a
1661   takeover run
1662  */
1663 static int control_rebalancenode(struct ctdb_context *ctdb, int argc, const char **argv)
1664 {
1665         switch (options.pnn) {
1666         case CTDB_BROADCAST_ALL:
1667         case CTDB_CURRENT_NODE:
1668                 DEBUG(DEBUG_ERR,("You must specify a node number with -n <pnn> for the node to rebalance\n"));
1669                 return -1;
1670         }
1671
1672         return rebalance_node(ctdb, options.pnn);
1673 }
1674
1675
1676 static int rebalance_ip(struct ctdb_context *ctdb, ctdb_sock_addr *addr)
1677 {
1678         struct ctdb_public_ip ip;
1679         int ret;
1680         uint32_t *nodes;
1681         uint32_t disable_time;
1682         TDB_DATA data;
1683         struct ctdb_node_map *nodemap=NULL;
1684         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
1685
1686         disable_time = 30;
1687         data.dptr  = (uint8_t*)&disable_time;
1688         data.dsize = sizeof(disable_time);
1689         ret = ctdb_client_send_message(ctdb, CTDB_BROADCAST_CONNECTED, CTDB_SRVID_DISABLE_IP_CHECK, data);
1690         if (ret != 0) {
1691                 DEBUG(DEBUG_ERR,("Failed to send message to disable ipcheck\n"));
1692                 return -1;
1693         }
1694
1695         ip.pnn  = -1;
1696         ip.addr = *addr;
1697
1698         data.dptr  = (uint8_t *)&ip;
1699         data.dsize = sizeof(ip);
1700
1701         ret = ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), options.pnn, tmp_ctx, &nodemap);
1702         if (ret != 0) {
1703                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from node %u\n", options.pnn));
1704                 talloc_free(tmp_ctx);
1705                 return ret;
1706         }
1707
1708         nodes = list_of_active_nodes(ctdb, nodemap, tmp_ctx, true);
1709         ret = ctdb_client_async_control(ctdb, CTDB_CONTROL_RELEASE_IP,
1710                                         nodes, 0,
1711                                         LONGTIMELIMIT(),
1712                                         false, data,
1713                                         NULL, NULL,
1714                                         NULL);
1715         if (ret != 0) {
1716                 DEBUG(DEBUG_ERR,("Failed to release IP on nodes\n"));
1717                 talloc_free(tmp_ctx);
1718                 return -1;
1719         }
1720
1721         talloc_free(tmp_ctx);
1722         return 0;
1723 }
1724
1725 /*
1726   release an ip form all nodes and have it re-assigned by recd
1727  */
1728 static int control_rebalanceip(struct ctdb_context *ctdb, int argc, const char **argv)
1729 {
1730         ctdb_sock_addr addr;
1731
1732         if (argc < 1) {
1733                 usage();
1734                 return -1;
1735         }
1736
1737         if (parse_ip(argv[0], NULL, 0, &addr) == 0) {
1738                 DEBUG(DEBUG_ERR,("Wrongly formed ip address '%s'\n", argv[0]));
1739                 return -1;
1740         }
1741
1742         if (rebalance_ip(ctdb, &addr) != 0) {
1743                 DEBUG(DEBUG_ERR,("Error when trying to reassign ip\n"));
1744                 return -1;
1745         }
1746
1747         return 0;
1748 }
1749
1750 static int getips_store_callback(void *param, void *data)
1751 {
1752         struct ctdb_public_ip *node_ip = (struct ctdb_public_ip *)data;
1753         struct ctdb_all_public_ips *ips = param;
1754         int i;
1755
1756         i = ips->num++;
1757         ips->ips[i].pnn  = node_ip->pnn;
1758         ips->ips[i].addr = node_ip->addr;
1759         return 0;
1760 }
1761
1762 static int getips_count_callback(void *param, void *data)
1763 {
1764         uint32_t *count = param;
1765
1766         (*count)++;
1767         return 0;
1768 }
1769
1770 #define IP_KEYLEN       4
1771 static uint32_t *ip_key(ctdb_sock_addr *ip)
1772 {
1773         static uint32_t key[IP_KEYLEN];
1774
1775         bzero(key, sizeof(key));
1776
1777         switch (ip->sa.sa_family) {
1778         case AF_INET:
1779                 key[0]  = ip->ip.sin_addr.s_addr;
1780                 break;
1781         case AF_INET6: {
1782                 uint32_t *s6_a32 = (uint32_t *)&(ip->ip6.sin6_addr.s6_addr);
1783                 key[0]  = s6_a32[3];
1784                 key[1]  = s6_a32[2];
1785                 key[2]  = s6_a32[1];
1786                 key[3]  = s6_a32[0];
1787                 break;
1788         }
1789         default:
1790                 DEBUG(DEBUG_ERR, (__location__ " ERROR, unknown family passed :%u\n", ip->sa.sa_family));
1791                 return key;
1792         }
1793
1794         return key;
1795 }
1796
1797 static void *add_ip_callback(void *parm, void *data)
1798 {
1799         return parm;
1800 }
1801
1802 static int
1803 control_get_all_public_ips(struct ctdb_context *ctdb, TALLOC_CTX *tmp_ctx, struct ctdb_all_public_ips **ips)
1804 {
1805         struct ctdb_all_public_ips *tmp_ips;
1806         struct ctdb_node_map *nodemap=NULL;
1807         trbt_tree_t *ip_tree;
1808         int i, j, len, ret;
1809         uint32_t count;
1810
1811         ret = ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE, tmp_ctx, &nodemap);
1812         if (ret != 0) {
1813                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from node %u\n", options.pnn));
1814                 return ret;
1815         }
1816
1817         ip_tree = trbt_create(tmp_ctx, 0);
1818
1819         for(i=0;i<nodemap->num;i++){
1820                 if (nodemap->nodes[i].flags & NODE_FLAGS_DELETED) {
1821                         continue;
1822                 }
1823                 if (nodemap->nodes[i].flags & NODE_FLAGS_DISCONNECTED) {
1824                         continue;
1825                 }
1826
1827                 /* read the public ip list from this node */
1828                 ret = ctdb_ctrl_get_public_ips(ctdb, TIMELIMIT(), nodemap->nodes[i].pnn, tmp_ctx, &tmp_ips);
1829                 if (ret != 0) {
1830                         DEBUG(DEBUG_ERR, ("Unable to get public ip list from node %u\n", nodemap->nodes[i].pnn));
1831                         return -1;
1832                 }
1833         
1834                 for (j=0; j<tmp_ips->num;j++) {
1835                         struct ctdb_public_ip *node_ip;
1836
1837                         node_ip = talloc(tmp_ctx, struct ctdb_public_ip);
1838                         node_ip->pnn  = tmp_ips->ips[j].pnn;
1839                         node_ip->addr = tmp_ips->ips[j].addr;
1840
1841                         trbt_insertarray32_callback(ip_tree,
1842                                 IP_KEYLEN, ip_key(&tmp_ips->ips[j].addr),
1843                                 add_ip_callback,
1844                                 node_ip);
1845                 }
1846                 talloc_free(tmp_ips);
1847         }
1848
1849         /* traverse */
1850         count = 0;
1851         trbt_traversearray32(ip_tree, IP_KEYLEN, getips_count_callback, &count);
1852
1853         len = offsetof(struct ctdb_all_public_ips, ips) + 
1854                 count*sizeof(struct ctdb_public_ip);
1855         tmp_ips = talloc_zero_size(tmp_ctx, len);
1856         trbt_traversearray32(ip_tree, IP_KEYLEN, getips_store_callback, tmp_ips);
1857
1858         *ips = tmp_ips;
1859
1860         return 0;
1861 }
1862
1863
1864 /* 
1865  * scans all other nodes and returns a pnn for another node that can host this 
1866  * ip address or -1
1867  */
1868 static int
1869 find_other_host_for_public_ip(struct ctdb_context *ctdb, ctdb_sock_addr *addr)
1870 {
1871         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
1872         struct ctdb_all_public_ips *ips;
1873         struct ctdb_node_map *nodemap=NULL;
1874         int i, j, ret;
1875
1876         ret = ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE, tmp_ctx, &nodemap);
1877         if (ret != 0) {
1878                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from node %u\n", options.pnn));
1879                 talloc_free(tmp_ctx);
1880                 return ret;
1881         }
1882
1883         for(i=0;i<nodemap->num;i++){
1884                 if (nodemap->nodes[i].flags & NODE_FLAGS_INACTIVE) {
1885                         continue;
1886                 }
1887                 if (nodemap->nodes[i].pnn == options.pnn) {
1888                         continue;
1889                 }
1890
1891                 /* read the public ip list from this node */
1892                 ret = ctdb_ctrl_get_public_ips(ctdb, TIMELIMIT(), nodemap->nodes[i].pnn, tmp_ctx, &ips);
1893                 if (ret != 0) {
1894                         DEBUG(DEBUG_ERR, ("Unable to get public ip list from node %u\n", nodemap->nodes[i].pnn));
1895                         return -1;
1896                 }
1897
1898                 for (j=0;j<ips->num;j++) {
1899                         if (ctdb_same_ip(addr, &ips->ips[j].addr)) {
1900                                 talloc_free(tmp_ctx);
1901                                 return nodemap->nodes[i].pnn;
1902                         }
1903                 }
1904                 talloc_free(ips);
1905         }
1906
1907         talloc_free(tmp_ctx);
1908         return -1;
1909 }
1910
1911 static uint32_t ipreallocate_finished;
1912
1913 /*
1914   handler for receiving the response to ipreallocate
1915 */
1916 static void ip_reallocate_handler(struct ctdb_context *ctdb, uint64_t srvid, 
1917                              TDB_DATA data, void *private_data)
1918 {
1919         ipreallocate_finished = 1;
1920 }
1921
1922 static void ctdb_every_second(struct event_context *ev, struct timed_event *te, struct timeval t, void *p)
1923 {
1924         struct ctdb_context *ctdb = talloc_get_type(p, struct ctdb_context);
1925
1926         event_add_timed(ctdb->ev, ctdb, 
1927                                 timeval_current_ofs(1, 0),
1928                                 ctdb_every_second, ctdb);
1929 }
1930
1931 /*
1932   ask the recovery daemon on the recovery master to perform a ip reallocation
1933  */
1934 static int control_ipreallocate(struct ctdb_context *ctdb, int argc, const char **argv)
1935 {
1936         int i, ret;
1937         TDB_DATA data;
1938         struct takeover_run_reply rd;
1939         uint32_t recmaster;
1940         struct ctdb_node_map *nodemap=NULL;
1941         int retries=0;
1942         struct timeval tv = timeval_current();
1943
1944         /* we need some events to trigger so we can timeout and restart
1945            the loop
1946         */
1947         event_add_timed(ctdb->ev, ctdb, 
1948                                 timeval_current_ofs(1, 0),
1949                                 ctdb_every_second, ctdb);
1950
1951         rd.pnn = ctdb_ctrl_getpnn(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE);
1952         if (rd.pnn == -1) {
1953                 DEBUG(DEBUG_ERR, ("Failed to get pnn of local node\n"));
1954                 return -1;
1955         }
1956         rd.srvid = getpid();
1957
1958         /* register a message port for receiveing the reply so that we
1959            can receive the reply
1960         */
1961         ctdb_client_set_message_handler(ctdb, rd.srvid, ip_reallocate_handler, NULL);
1962
1963         data.dptr = (uint8_t *)&rd;
1964         data.dsize = sizeof(rd);
1965
1966 again:
1967         /* check that there are valid nodes available */
1968         if (ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), options.pnn, ctdb, &nodemap) != 0) {
1969                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from local node\n"));
1970                 return -1;
1971         }
1972         for (i=0; i<nodemap->num;i++) {
1973                 if ((nodemap->nodes[i].flags & (NODE_FLAGS_DELETED|NODE_FLAGS_BANNED|NODE_FLAGS_STOPPED)) == 0) {
1974                         break;
1975                 }
1976         }
1977         if (i==nodemap->num) {
1978                 DEBUG(DEBUG_ERR,("No recmaster available, no need to wait for cluster convergence\n"));
1979                 return 0;
1980         }
1981
1982
1983         if (!ctdb_getrecmaster(ctdb_connection, options.pnn, &recmaster)) {
1984                 DEBUG(DEBUG_ERR, ("Unable to get recmaster from node %u\n", options.pnn));
1985                 return -1;
1986         }
1987
1988         /* verify the node exists */
1989         if (ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), recmaster, ctdb, &nodemap) != 0) {
1990                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from local node\n"));
1991                 return -1;
1992         }
1993
1994
1995         /* check tha there are nodes available that can act as a recmaster */
1996         for (i=0; i<nodemap->num; i++) {
1997                 if (nodemap->nodes[i].flags & (NODE_FLAGS_DELETED|NODE_FLAGS_BANNED|NODE_FLAGS_STOPPED)) {
1998                         continue;
1999                 }
2000                 break;
2001         }
2002         if (i == nodemap->num) {
2003                 DEBUG(DEBUG_ERR,("No possible nodes to host addresses.\n"));
2004                 return 0;
2005         }
2006
2007         /* verify the recovery master is not STOPPED, nor BANNED */
2008         if (nodemap->nodes[recmaster].flags & (NODE_FLAGS_DELETED|NODE_FLAGS_BANNED|NODE_FLAGS_STOPPED)) {
2009                 DEBUG(DEBUG_ERR,("No suitable recmaster found. Try again\n"));
2010                 retries++;
2011                 sleep(1);
2012                 goto again;
2013         } 
2014         
2015         /* verify the recovery master is not STOPPED, nor BANNED */
2016         if (nodemap->nodes[recmaster].flags & (NODE_FLAGS_DELETED|NODE_FLAGS_BANNED|NODE_FLAGS_STOPPED)) {
2017                 DEBUG(DEBUG_ERR,("No suitable recmaster found. Try again\n"));
2018                 retries++;
2019                 sleep(1);
2020                 goto again;
2021         } 
2022
2023         ipreallocate_finished = 0;
2024         ret = ctdb_client_send_message(ctdb, recmaster, CTDB_SRVID_TAKEOVER_RUN, data);
2025         if (ret != 0) {
2026                 DEBUG(DEBUG_ERR,("Failed to send ip takeover run request message to %u\n", options.pnn));
2027                 return -1;
2028         }
2029
2030         tv = timeval_current();
2031         /* this loop will terminate when we have received the reply */
2032         while (timeval_elapsed(&tv) < 5.0 && ipreallocate_finished == 0) {
2033                 event_loop_once(ctdb->ev);
2034         }
2035         if (ipreallocate_finished == 1) {
2036                 return 0;
2037         }
2038
2039         retries++;
2040         sleep(1);
2041         goto again;
2042
2043         return 0;
2044 }
2045
2046
2047 /*
2048   add a public ip address to a node
2049  */
2050 static int control_addip(struct ctdb_context *ctdb, int argc, const char **argv)
2051 {
2052         int i, ret;
2053         int len, retries = 0;
2054         unsigned mask;
2055         ctdb_sock_addr addr;
2056         struct ctdb_control_ip_iface *pub;
2057         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
2058         struct ctdb_all_public_ips *ips;
2059
2060
2061         if (argc != 2) {
2062                 talloc_free(tmp_ctx);
2063                 usage();
2064         }
2065
2066         if (!parse_ip_mask(argv[0], argv[1], &addr, &mask)) {
2067                 DEBUG(DEBUG_ERR, ("Badly formed ip/mask : %s\n", argv[0]));
2068                 talloc_free(tmp_ctx);
2069                 return -1;
2070         }
2071
2072         /* read the public ip list from the node */
2073         ret = ctdb_ctrl_get_public_ips(ctdb, TIMELIMIT(), options.pnn, tmp_ctx, &ips);
2074         if (ret != 0) {
2075                 DEBUG(DEBUG_ERR, ("Unable to get public ip list from node %u\n", options.pnn));
2076                 talloc_free(tmp_ctx);
2077                 return -1;
2078         }
2079         for (i=0;i<ips->num;i++) {
2080                 if (ctdb_same_ip(&addr, &ips->ips[i].addr)) {
2081                         DEBUG(DEBUG_ERR,("Can not add ip to node. Node already hosts this ip\n"));
2082                         return 0;
2083                 }
2084         }
2085
2086
2087
2088         /* Dont timeout. This command waits for an ip reallocation
2089            which sometimes can take wuite a while if there has
2090            been a recent recovery
2091         */
2092         alarm(0);
2093
2094         len = offsetof(struct ctdb_control_ip_iface, iface) + strlen(argv[1]) + 1;
2095         pub = talloc_size(tmp_ctx, len); 
2096         CTDB_NO_MEMORY(ctdb, pub);
2097
2098         pub->addr  = addr;
2099         pub->mask  = mask;
2100         pub->len   = strlen(argv[1])+1;
2101         memcpy(&pub->iface[0], argv[1], strlen(argv[1])+1);
2102
2103         do {
2104                 ret = ctdb_ctrl_add_public_ip(ctdb, TIMELIMIT(), options.pnn, pub);
2105                 if (ret != 0) {
2106                         DEBUG(DEBUG_ERR, ("Unable to add public ip to node %u. Wait 3 seconds and try again.\n", options.pnn));
2107                         sleep(3);
2108                         retries++;
2109                 }
2110         } while (retries < 5 && ret != 0);
2111         if (ret != 0) {
2112                 DEBUG(DEBUG_ERR, ("Unable to add public ip to node %u. Giving up.\n", options.pnn));
2113                 talloc_free(tmp_ctx);
2114                 return ret;
2115         }
2116
2117         if (rebalance_node(ctdb, options.pnn) != 0) {
2118                 DEBUG(DEBUG_ERR,("Error when trying to rebalance node\n"));
2119                 return ret;
2120         }
2121
2122         talloc_free(tmp_ctx);
2123         return 0;
2124 }
2125
2126 /*
2127   add a public ip address to a node
2128  */
2129 static int control_ipiface(struct ctdb_context *ctdb, int argc, const char **argv)
2130 {
2131         ctdb_sock_addr addr;
2132
2133         if (argc != 1) {
2134                 usage();
2135         }
2136
2137         if (!parse_ip(argv[0], NULL, 0, &addr)) {
2138                 printf("Badly formed ip : %s\n", argv[0]);
2139                 return -1;
2140         }
2141
2142         printf("IP on interface %s\n", ctdb_sys_find_ifname(&addr));
2143
2144         return 0;
2145 }
2146
2147 static int control_delip(struct ctdb_context *ctdb, int argc, const char **argv);
2148
2149 static int control_delip_all(struct ctdb_context *ctdb, int argc, const char **argv, ctdb_sock_addr *addr)
2150 {
2151         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
2152         struct ctdb_node_map *nodemap=NULL;
2153         struct ctdb_all_public_ips *ips;
2154         int ret, i, j;
2155
2156         ret = ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE, tmp_ctx, &nodemap);
2157         if (ret != 0) {
2158                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from current node\n"));
2159                 return ret;
2160         }
2161
2162         /* remove it from the nodes that are not hosting the ip currently */
2163         for(i=0;i<nodemap->num;i++){
2164                 if (nodemap->nodes[i].flags & NODE_FLAGS_INACTIVE) {
2165                         continue;
2166                 }
2167                 if (ctdb_ctrl_get_public_ips(ctdb, TIMELIMIT(), nodemap->nodes[i].pnn, tmp_ctx, &ips) != 0) {
2168                         DEBUG(DEBUG_ERR, ("Unable to get public ip list from node %d\n", nodemap->nodes[i].pnn));
2169                         continue;
2170                 }
2171
2172                 for (j=0;j<ips->num;j++) {
2173                         if (ctdb_same_ip(addr, &ips->ips[j].addr)) {
2174                                 break;
2175                         }
2176                 }
2177                 if (j==ips->num) {
2178                         continue;
2179                 }
2180
2181                 if (ips->ips[j].pnn == nodemap->nodes[i].pnn) {
2182                         continue;
2183                 }
2184
2185                 options.pnn = nodemap->nodes[i].pnn;
2186                 control_delip(ctdb, argc, argv);
2187         }
2188
2189
2190         /* remove it from every node (also the one hosting it) */
2191         for(i=0;i<nodemap->num;i++){
2192                 if (nodemap->nodes[i].flags & NODE_FLAGS_INACTIVE) {
2193                         continue;
2194                 }
2195                 if (ctdb_ctrl_get_public_ips(ctdb, TIMELIMIT(), nodemap->nodes[i].pnn, tmp_ctx, &ips) != 0) {
2196                         DEBUG(DEBUG_ERR, ("Unable to get public ip list from node %d\n", nodemap->nodes[i].pnn));
2197                         continue;
2198                 }
2199
2200                 for (j=0;j<ips->num;j++) {
2201                         if (ctdb_same_ip(addr, &ips->ips[j].addr)) {
2202                                 break;
2203                         }
2204                 }
2205                 if (j==ips->num) {
2206                         continue;
2207                 }
2208
2209                 options.pnn = nodemap->nodes[i].pnn;
2210                 control_delip(ctdb, argc, argv);
2211         }
2212
2213         talloc_free(tmp_ctx);
2214         return 0;
2215 }
2216         
2217 /*
2218   delete a public ip address from a node
2219  */
2220 static int control_delip(struct ctdb_context *ctdb, int argc, const char **argv)
2221 {
2222         int i, ret;
2223         int retries = 0;
2224         ctdb_sock_addr addr;
2225         struct ctdb_control_ip_iface pub;
2226         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
2227         struct ctdb_all_public_ips *ips;
2228
2229         if (argc != 1) {
2230                 talloc_free(tmp_ctx);
2231                 usage();
2232         }
2233
2234         if (parse_ip(argv[0], NULL, 0, &addr) == 0) {
2235                 DEBUG(DEBUG_ERR,("Wrongly formed ip address '%s'\n", argv[0]));
2236                 return -1;
2237         }
2238
2239         if (options.pnn == CTDB_BROADCAST_ALL) {
2240                 return control_delip_all(ctdb, argc, argv, &addr);
2241         }
2242
2243         pub.addr  = addr;
2244         pub.mask  = 0;
2245         pub.len   = 0;
2246
2247         ret = ctdb_ctrl_get_public_ips(ctdb, TIMELIMIT(), options.pnn, tmp_ctx, &ips);
2248         if (ret != 0) {
2249                 DEBUG(DEBUG_ERR, ("Unable to get public ip list from cluster\n"));
2250                 talloc_free(tmp_ctx);
2251                 return ret;
2252         }
2253         
2254         for (i=0;i<ips->num;i++) {
2255                 if (ctdb_same_ip(&addr, &ips->ips[i].addr)) {
2256                         break;
2257                 }
2258         }
2259
2260         if (i==ips->num) {
2261                 DEBUG(DEBUG_ERR, ("This node does not support this public address '%s'\n",
2262                         ctdb_addr_to_str(&addr)));
2263                 talloc_free(tmp_ctx);
2264                 return -1;
2265         }
2266
2267         if (ips->ips[i].pnn == options.pnn) {
2268                 int pnn;
2269
2270                 pnn = find_other_host_for_public_ip(ctdb, &addr);
2271                 if (pnn != -1) {
2272                         do {
2273                                 ret = move_ip(ctdb, &addr, pnn);
2274                                 if (ret != 0) {
2275                                         DEBUG(DEBUG_ERR,("Failed to move ip to node %d. Wait 3 seconds and try again.\n", options.pnn));
2276                                         sleep(3);
2277                                         retries++;
2278                                 }
2279                         } while (retries < 5 && ret != 0);
2280                         if (ret != 0) {
2281                                 DEBUG(DEBUG_ERR,("Failed to move ip to node %d. Giving up.\n", options.pnn));
2282                                 return -1;
2283                         }
2284                 }
2285         }
2286
2287         ret = ctdb_ctrl_del_public_ip(ctdb, TIMELIMIT(), options.pnn, &pub);
2288         if (ret != 0) {
2289                 DEBUG(DEBUG_ERR, ("Unable to del public ip from node %u\n", options.pnn));
2290                 talloc_free(tmp_ctx);
2291                 return ret;
2292         }
2293
2294         talloc_free(tmp_ctx);
2295         return 0;
2296 }
2297
2298 /*
2299   kill a tcp connection
2300  */
2301 static int kill_tcp(struct ctdb_context *ctdb, int argc, const char **argv)
2302 {
2303         int ret;
2304         struct ctdb_control_killtcp killtcp;
2305
2306         if (argc < 2) {
2307                 usage();
2308         }
2309
2310         if (!parse_ip_port(argv[0], &killtcp.src_addr)) {
2311                 DEBUG(DEBUG_ERR, ("Bad IP:port '%s'\n", argv[0]));
2312                 return -1;
2313         }
2314
2315         if (!parse_ip_port(argv[1], &killtcp.dst_addr)) {
2316                 DEBUG(DEBUG_ERR, ("Bad IP:port '%s'\n", argv[1]));
2317                 return -1;
2318         }
2319
2320         ret = ctdb_ctrl_killtcp(ctdb, TIMELIMIT(), options.pnn, &killtcp);
2321         if (ret != 0) {
2322                 DEBUG(DEBUG_ERR, ("Unable to killtcp from node %u\n", options.pnn));
2323                 return ret;
2324         }
2325
2326         return 0;
2327 }
2328
2329
2330 /*
2331   send a gratious arp
2332  */
2333 static int control_gratious_arp(struct ctdb_context *ctdb, int argc, const char **argv)
2334 {
2335         int ret;
2336         ctdb_sock_addr addr;
2337
2338         if (argc < 2) {
2339                 usage();
2340         }
2341
2342         if (!parse_ip(argv[0], NULL, 0, &addr)) {
2343                 DEBUG(DEBUG_ERR, ("Bad IP '%s'\n", argv[0]));
2344                 return -1;
2345         }
2346
2347         ret = ctdb_ctrl_gratious_arp(ctdb, TIMELIMIT(), options.pnn, &addr, argv[1]);
2348         if (ret != 0) {
2349                 DEBUG(DEBUG_ERR, ("Unable to send gratious_arp from node %u\n", options.pnn));
2350                 return ret;
2351         }
2352
2353         return 0;
2354 }
2355
2356 /*
2357   register a server id
2358  */
2359 static int regsrvid(struct ctdb_context *ctdb, int argc, const char **argv)
2360 {
2361         int ret;
2362         struct ctdb_server_id server_id;
2363
2364         if (argc < 3) {
2365                 usage();
2366         }
2367
2368         server_id.pnn       = strtoul(argv[0], NULL, 0);
2369         server_id.type      = strtoul(argv[1], NULL, 0);
2370         server_id.server_id = strtoul(argv[2], NULL, 0);
2371
2372         ret = ctdb_ctrl_register_server_id(ctdb, TIMELIMIT(), &server_id);
2373         if (ret != 0) {
2374                 DEBUG(DEBUG_ERR, ("Unable to register server_id from node %u\n", options.pnn));
2375                 return ret;
2376         }
2377         DEBUG(DEBUG_ERR,("Srvid registered. Sleeping for 999 seconds\n"));
2378         sleep(999);
2379         return -1;
2380 }
2381
2382 /*
2383   unregister a server id
2384  */
2385 static int unregsrvid(struct ctdb_context *ctdb, int argc, const char **argv)
2386 {
2387         int ret;
2388         struct ctdb_server_id server_id;
2389
2390         if (argc < 3) {
2391                 usage();
2392         }
2393
2394         server_id.pnn       = strtoul(argv[0], NULL, 0);
2395         server_id.type      = strtoul(argv[1], NULL, 0);
2396         server_id.server_id = strtoul(argv[2], NULL, 0);
2397
2398         ret = ctdb_ctrl_unregister_server_id(ctdb, TIMELIMIT(), &server_id);
2399         if (ret != 0) {
2400                 DEBUG(DEBUG_ERR, ("Unable to unregister server_id from node %u\n", options.pnn));
2401                 return ret;
2402         }
2403         return -1;
2404 }
2405
2406 /*
2407   check if a server id exists
2408  */
2409 static int chksrvid(struct ctdb_context *ctdb, int argc, const char **argv)
2410 {
2411         uint32_t status;
2412         int ret;
2413         struct ctdb_server_id server_id;
2414
2415         if (argc < 3) {
2416                 usage();
2417         }
2418
2419         server_id.pnn       = strtoul(argv[0], NULL, 0);
2420         server_id.type      = strtoul(argv[1], NULL, 0);
2421         server_id.server_id = strtoul(argv[2], NULL, 0);
2422
2423         ret = ctdb_ctrl_check_server_id(ctdb, TIMELIMIT(), options.pnn, &server_id, &status);
2424         if (ret != 0) {
2425                 DEBUG(DEBUG_ERR, ("Unable to check server_id from node %u\n", options.pnn));
2426                 return ret;
2427         }
2428
2429         if (status) {
2430                 printf("Server id %d:%d:%d EXISTS\n", server_id.pnn, server_id.type, server_id.server_id);
2431         } else {
2432                 printf("Server id %d:%d:%d does NOT exist\n", server_id.pnn, server_id.type, server_id.server_id);
2433         }
2434         return 0;
2435 }
2436
2437 /*
2438   get a list of all server ids that are registered on a node
2439  */
2440 static int getsrvids(struct ctdb_context *ctdb, int argc, const char **argv)
2441 {
2442         int i, ret;
2443         struct ctdb_server_id_list *server_ids;
2444
2445         ret = ctdb_ctrl_get_server_id_list(ctdb, ctdb, TIMELIMIT(), options.pnn, &server_ids);
2446         if (ret != 0) {
2447                 DEBUG(DEBUG_ERR, ("Unable to get server_id list from node %u\n", options.pnn));
2448                 return ret;
2449         }
2450
2451         for (i=0; i<server_ids->num; i++) {
2452                 printf("Server id %d:%d:%d\n", 
2453                         server_ids->server_ids[i].pnn, 
2454                         server_ids->server_ids[i].type, 
2455                         server_ids->server_ids[i].server_id); 
2456         }
2457
2458         return -1;
2459 }
2460
2461 /*
2462   check if a server id exists
2463  */
2464 static int check_srvids(struct ctdb_context *ctdb, int argc, const char **argv)
2465 {
2466         TALLOC_CTX *tmp_ctx = talloc_new(NULL);
2467         uint64_t *ids;
2468         uint8_t *result;
2469         int i;
2470
2471         if (argc < 1) {
2472                 talloc_free(tmp_ctx);
2473                 usage();
2474         }
2475
2476         ids    = talloc_array(tmp_ctx, uint64_t, argc);
2477         result = talloc_array(tmp_ctx, uint8_t, argc);
2478
2479         for (i = 0; i < argc; i++) {
2480                 ids[i] = strtoull(argv[i], NULL, 0);
2481         }
2482
2483         if (!ctdb_check_message_handlers(ctdb_connection,
2484                 options.pnn, argc, ids, result)) {
2485                 DEBUG(DEBUG_ERR, ("Unable to check server_id from node %u\n",
2486                                   options.pnn));
2487                 talloc_free(tmp_ctx);
2488                 return -1;
2489         }
2490
2491         for (i=0; i < argc; i++) {
2492                 printf("Server id %d:%llu %s\n", options.pnn, (long long)ids[i],
2493                        result[i] ? "exists" : "does not exist");
2494         }
2495
2496         talloc_free(tmp_ctx);
2497         return 0;
2498 }
2499
2500 /*
2501   send a tcp tickle ack
2502  */
2503 static int tickle_tcp(struct ctdb_context *ctdb, int argc, const char **argv)
2504 {
2505         int ret;
2506         ctdb_sock_addr  src, dst;
2507
2508         if (argc < 2) {
2509                 usage();
2510         }
2511
2512         if (!parse_ip_port(argv[0], &src)) {
2513                 DEBUG(DEBUG_ERR, ("Bad IP:port '%s'\n", argv[0]));
2514                 return -1;
2515         }
2516
2517         if (!parse_ip_port(argv[1], &dst)) {
2518                 DEBUG(DEBUG_ERR, ("Bad IP:port '%s'\n", argv[1]));
2519                 return -1;
2520         }
2521
2522         ret = ctdb_sys_send_tcp(&src, &dst, 0, 0, 0);
2523         if (ret==0) {
2524                 return 0;
2525         }
2526         DEBUG(DEBUG_ERR, ("Error while sending tickle ack\n"));
2527
2528         return -1;
2529 }
2530
2531
2532 /*
2533   display public ip status
2534  */
2535 static int control_ip(struct ctdb_context *ctdb, int argc, const char **argv)
2536 {
2537         int i, ret;
2538         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
2539         struct ctdb_all_public_ips *ips;
2540
2541         if (options.pnn == CTDB_BROADCAST_ALL) {
2542                 /* read the list of public ips from all nodes */
2543                 ret = control_get_all_public_ips(ctdb, tmp_ctx, &ips);
2544         } else {
2545                 /* read the public ip list from this node */
2546                 ret = ctdb_ctrl_get_public_ips(ctdb, TIMELIMIT(), options.pnn, tmp_ctx, &ips);
2547         }
2548         if (ret != 0) {
2549                 DEBUG(DEBUG_ERR, ("Unable to get public ips from node %u\n", options.pnn));
2550                 talloc_free(tmp_ctx);
2551                 return ret;
2552         }
2553
2554         if (options.machinereadable){
2555                 printf(":Public IP:Node:");
2556                 if (options.verbose){
2557                         printf("ActiveInterface:AvailableInterfaces:ConfiguredInterfaces:");
2558                 }
2559                 printf("\n");
2560         } else {
2561                 if (options.pnn == CTDB_BROADCAST_ALL) {
2562                         printf("Public IPs on ALL nodes\n");
2563                 } else {
2564                         printf("Public IPs on node %u\n", options.pnn);
2565                 }
2566         }
2567
2568         for (i=1;i<=ips->num;i++) {
2569                 struct ctdb_control_public_ip_info *info = NULL;
2570                 int32_t pnn;
2571                 char *aciface = NULL;
2572                 char *avifaces = NULL;
2573                 char *cifaces = NULL;
2574
2575                 if (options.pnn == CTDB_BROADCAST_ALL) {
2576                         pnn = ips->ips[ips->num-i].pnn;
2577                 } else {
2578                         pnn = options.pnn;
2579                 }
2580
2581                 if (pnn != -1) {
2582                         ret = ctdb_ctrl_get_public_ip_info(ctdb, TIMELIMIT(), pnn, ctdb,
2583                                                    &ips->ips[ips->num-i].addr, &info);
2584                 } else {
2585                         ret = -1;
2586                 }
2587
2588                 if (ret == 0) {
2589                         int j;
2590                         for (j=0; j < info->num; j++) {
2591                                 if (cifaces == NULL) {
2592                                         cifaces = talloc_strdup(info,
2593                                                                 info->ifaces[j].name);
2594                                 } else {
2595                                         cifaces = talloc_asprintf_append(cifaces,
2596                                                                          ",%s",
2597                                                                          info->ifaces[j].name);
2598                                 }
2599
2600                                 if (info->active_idx == j) {
2601                                         aciface = info->ifaces[j].name;
2602                                 }
2603
2604                                 if (info->ifaces[j].link_state == 0) {
2605                                         continue;
2606                                 }
2607
2608                                 if (avifaces == NULL) {
2609                                         avifaces = talloc_strdup(info, info->ifaces[j].name);
2610                                 } else {
2611                                         avifaces = talloc_asprintf_append(avifaces,
2612                                                                           ",%s",
2613                                                                           info->ifaces[j].name);
2614                                 }
2615                         }
2616                 }
2617
2618                 if (options.machinereadable){
2619                         printf(":%s:%d:",
2620                                 ctdb_addr_to_str(&ips->ips[ips->num-i].addr),
2621                                 ips->ips[ips->num-i].pnn);
2622                         if (options.verbose){
2623                                 printf("%s:%s:%s:",
2624                                         aciface?aciface:"",
2625                                         avifaces?avifaces:"",
2626                                         cifaces?cifaces:"");
2627                         }
2628                         printf("\n");
2629                 } else {
2630                         if (options.verbose) {
2631                                 printf("%s node[%d] active[%s] available[%s] configured[%s]\n",
2632                                         ctdb_addr_to_str(&ips->ips[ips->num-i].addr),
2633                                         ips->ips[ips->num-i].pnn,
2634                                         aciface?aciface:"",
2635                                         avifaces?avifaces:"",
2636                                         cifaces?cifaces:"");
2637                         } else {
2638                                 printf("%s %d\n",
2639                                         ctdb_addr_to_str(&ips->ips[ips->num-i].addr),
2640                                         ips->ips[ips->num-i].pnn);
2641                         }
2642                 }
2643                 talloc_free(info);
2644         }
2645
2646         talloc_free(tmp_ctx);
2647         return 0;
2648 }
2649
2650 /*
2651   public ip info
2652  */
2653 static int control_ipinfo(struct ctdb_context *ctdb, int argc, const char **argv)
2654 {
2655         int i, ret;
2656         ctdb_sock_addr addr;
2657         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
2658         struct ctdb_control_public_ip_info *info;
2659
2660         if (argc != 1) {
2661                 talloc_free(tmp_ctx);
2662                 usage();
2663         }
2664
2665         if (parse_ip(argv[0], NULL, 0, &addr) == 0) {
2666                 DEBUG(DEBUG_ERR,("Wrongly formed ip address '%s'\n", argv[0]));
2667                 return -1;
2668         }
2669
2670         /* read the public ip info from this node */
2671         ret = ctdb_ctrl_get_public_ip_info(ctdb, TIMELIMIT(), options.pnn,
2672                                            tmp_ctx, &addr, &info);
2673         if (ret != 0) {
2674                 DEBUG(DEBUG_ERR, ("Unable to get public ip[%s]info from node %u\n",
2675                                   argv[0], options.pnn));
2676                 talloc_free(tmp_ctx);
2677                 return ret;
2678         }
2679
2680         printf("Public IP[%s] info on node %u\n",
2681                ctdb_addr_to_str(&info->ip.addr),
2682                options.pnn);
2683
2684         printf("IP:%s\nCurrentNode:%d\nNumInterfaces:%u\n",
2685                ctdb_addr_to_str(&info->ip.addr),
2686                info->ip.pnn, info->num);
2687
2688         for (i=0; i<info->num; i++) {
2689                 info->ifaces[i].name[CTDB_IFACE_SIZE] = '\0';
2690
2691                 printf("Interface[%u]: Name:%s Link:%s References:%u%s\n",
2692                        i+1, info->ifaces[i].name,
2693                        info->ifaces[i].link_state?"up":"down",
2694                        (unsigned int)info->ifaces[i].references,
2695                        (i==info->active_idx)?" (active)":"");
2696         }
2697
2698         talloc_free(tmp_ctx);
2699         return 0;
2700 }
2701
2702 /*
2703   display interfaces status
2704  */
2705 static int control_ifaces(struct ctdb_context *ctdb, int argc, const char **argv)
2706 {
2707         int i;
2708         struct ctdb_ifaces_list *ifaces;
2709
2710         /* read the public ip list from this node */
2711         if (!ctdb_getifaces(ctdb_connection, options.pnn, &ifaces)) {
2712                 DEBUG(DEBUG_ERR, ("Unable to get interfaces from node %u\n",
2713                                   options.pnn));
2714                 return -1;
2715         }
2716
2717         if (options.machinereadable){
2718                 printf(":Name:LinkStatus:References:\n");
2719         } else {
2720                 printf("Interfaces on node %u\n", options.pnn);
2721         }
2722
2723         for (i=0; i<ifaces->num; i++) {
2724                 if (options.machinereadable){
2725                         printf(":%s:%s:%u\n",
2726                                ifaces->ifaces[i].name,
2727                                ifaces->ifaces[i].link_state?"1":"0",
2728                                (unsigned int)ifaces->ifaces[i].references);
2729                 } else {
2730                         printf("name:%s link:%s references:%u\n",
2731                                ifaces->ifaces[i].name,
2732                                ifaces->ifaces[i].link_state?"up":"down",
2733                                (unsigned int)ifaces->ifaces[i].references);
2734                 }
2735         }
2736
2737         ctdb_free_ifaces(ifaces);
2738         return 0;
2739 }
2740
2741
2742 /*
2743   set link status of an interface
2744  */
2745 static int control_setifacelink(struct ctdb_context *ctdb, int argc, const char **argv)
2746 {
2747         int ret;
2748         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
2749         struct ctdb_control_iface_info info;
2750
2751         ZERO_STRUCT(info);
2752
2753         if (argc != 2) {
2754                 usage();
2755         }
2756
2757         if (strlen(argv[0]) > CTDB_IFACE_SIZE) {
2758                 DEBUG(DEBUG_ERR, ("interfaces name '%s' too long\n",
2759                                   argv[0]));
2760                 talloc_free(tmp_ctx);
2761                 return -1;
2762         }
2763         strcpy(info.name, argv[0]);
2764
2765         if (strcmp(argv[1], "up") == 0) {
2766                 info.link_state = 1;
2767         } else if (strcmp(argv[1], "down") == 0) {
2768                 info.link_state = 0;
2769         } else {
2770                 DEBUG(DEBUG_ERR, ("link state invalid '%s' should be 'up' or 'down'\n",
2771                                   argv[1]));
2772                 talloc_free(tmp_ctx);
2773                 return -1;
2774         }
2775
2776         /* read the public ip list from this node */
2777         ret = ctdb_ctrl_set_iface_link(ctdb, TIMELIMIT(), options.pnn,
2778                                    tmp_ctx, &info);
2779         if (ret != 0) {
2780                 DEBUG(DEBUG_ERR, ("Unable to set link state for interfaces %s node %u\n",
2781                                   argv[0], options.pnn));
2782                 talloc_free(tmp_ctx);
2783                 return ret;
2784         }
2785
2786         talloc_free(tmp_ctx);
2787         return 0;
2788 }
2789
2790 /*
2791   display pid of a ctdb daemon
2792  */
2793 static int control_getpid(struct ctdb_context *ctdb, int argc, const char **argv)
2794 {
2795         uint32_t pid;
2796         int ret;
2797
2798         ret = ctdb_ctrl_getpid(ctdb, TIMELIMIT(), options.pnn, &pid);
2799         if (ret != 0) {
2800                 DEBUG(DEBUG_ERR, ("Unable to get daemon pid from node %u\n", options.pnn));
2801                 return ret;
2802         }
2803         printf("Pid:%d\n", pid);
2804
2805         return 0;
2806 }
2807
2808 /*
2809   disable a remote node
2810  */
2811 static int control_disable(struct ctdb_context *ctdb, int argc, const char **argv)
2812 {
2813         int ret;
2814         struct ctdb_node_map *nodemap=NULL;
2815
2816         /* check if the node is already disabled */
2817         if (ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE, ctdb, &nodemap) != 0) {
2818                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from local node\n"));
2819                 exit(10);
2820         }
2821         if (nodemap->nodes[options.pnn].flags & NODE_FLAGS_PERMANENTLY_DISABLED) {
2822                 DEBUG(DEBUG_ERR,("Node %d is already disabled.\n", options.pnn));
2823                 return 0;
2824         }
2825
2826         do {
2827                 ret = ctdb_ctrl_modflags(ctdb, TIMELIMIT(), options.pnn, NODE_FLAGS_PERMANENTLY_DISABLED, 0);
2828                 if (ret != 0) {
2829                         DEBUG(DEBUG_ERR, ("Unable to disable node %u\n", options.pnn));
2830                         return ret;
2831                 }
2832
2833                 sleep(1);
2834
2835                 /* read the nodemap and verify the change took effect */
2836                 if (ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE, ctdb, &nodemap) != 0) {
2837                         DEBUG(DEBUG_ERR, ("Unable to get nodemap from local node\n"));
2838                         exit(10);
2839                 }
2840
2841         } while (!(nodemap->nodes[options.pnn].flags & NODE_FLAGS_PERMANENTLY_DISABLED));
2842         ret = control_ipreallocate(ctdb, argc, argv);
2843         if (ret != 0) {
2844                 DEBUG(DEBUG_ERR, ("IP Reallocate failed on node %u\n", options.pnn));
2845                 return ret;
2846         }
2847
2848         return 0;
2849 }
2850
2851 /*
2852   enable a disabled remote node
2853  */
2854 static int control_enable(struct ctdb_context *ctdb, int argc, const char **argv)
2855 {
2856         int ret;
2857
2858         struct ctdb_node_map *nodemap=NULL;
2859
2860
2861         /* check if the node is already enabled */
2862         if (ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE, ctdb, &nodemap) != 0) {
2863                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from local node\n"));
2864                 exit(10);
2865         }
2866         if (!(nodemap->nodes[options.pnn].flags & NODE_FLAGS_PERMANENTLY_DISABLED)) {
2867                 DEBUG(DEBUG_ERR,("Node %d is already enabled.\n", options.pnn));
2868                 return 0;
2869         }
2870
2871         do {
2872                 ret = ctdb_ctrl_modflags(ctdb, TIMELIMIT(), options.pnn, 0, NODE_FLAGS_PERMANENTLY_DISABLED);
2873                 if (ret != 0) {
2874                         DEBUG(DEBUG_ERR, ("Unable to enable node %u\n", options.pnn));
2875                         return ret;
2876                 }
2877
2878                 sleep(1);
2879
2880                 /* read the nodemap and verify the change took effect */
2881                 if (ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE, ctdb, &nodemap) != 0) {
2882                         DEBUG(DEBUG_ERR, ("Unable to get nodemap from local node\n"));
2883                         exit(10);
2884                 }
2885
2886         } while (nodemap->nodes[options.pnn].flags & NODE_FLAGS_PERMANENTLY_DISABLED);
2887
2888         ret = control_ipreallocate(ctdb, argc, argv);
2889         if (ret != 0) {
2890                 DEBUG(DEBUG_ERR, ("IP Reallocate failed on node %u\n", options.pnn));
2891                 return ret;
2892         }
2893
2894         return 0;
2895 }
2896
2897 /*
2898   stop a remote node
2899  */
2900 static int control_stop(struct ctdb_context *ctdb, int argc, const char **argv)
2901 {
2902         int ret;
2903         struct ctdb_node_map *nodemap=NULL;
2904
2905         do {
2906                 ret = ctdb_ctrl_stop_node(ctdb, TIMELIMIT(), options.pnn);
2907                 if (ret != 0) {
2908                         DEBUG(DEBUG_ERR, ("Unable to stop node %u   try again\n", options.pnn));
2909                 }
2910         
2911                 sleep(1);
2912
2913                 /* read the nodemap and verify the change took effect */
2914                 if (ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE, ctdb, &nodemap) != 0) {
2915                         DEBUG(DEBUG_ERR, ("Unable to get nodemap from local node\n"));
2916                         exit(10);
2917                 }
2918
2919         } while (!(nodemap->nodes[options.pnn].flags & NODE_FLAGS_STOPPED));
2920         ret = control_ipreallocate(ctdb, argc, argv);
2921         if (ret != 0) {
2922                 DEBUG(DEBUG_ERR, ("IP Reallocate failed on node %u\n", options.pnn));
2923                 return ret;
2924         }
2925
2926         return 0;
2927 }
2928
2929 /*
2930   restart a stopped remote node
2931  */
2932 static int control_continue(struct ctdb_context *ctdb, int argc, const char **argv)
2933 {
2934         int ret;
2935
2936         struct ctdb_node_map *nodemap=NULL;
2937
2938         do {
2939                 ret = ctdb_ctrl_continue_node(ctdb, TIMELIMIT(), options.pnn);
2940                 if (ret != 0) {
2941                         DEBUG(DEBUG_ERR, ("Unable to continue node %u\n", options.pnn));
2942                         return ret;
2943                 }
2944         
2945                 sleep(1);
2946
2947                 /* read the nodemap and verify the change took effect */
2948                 if (ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE, ctdb, &nodemap) != 0) {
2949                         DEBUG(DEBUG_ERR, ("Unable to get nodemap from local node\n"));
2950                         exit(10);
2951                 }
2952
2953         } while (nodemap->nodes[options.pnn].flags & NODE_FLAGS_STOPPED);
2954         ret = control_ipreallocate(ctdb, argc, argv);
2955         if (ret != 0) {
2956                 DEBUG(DEBUG_ERR, ("IP Reallocate failed on node %u\n", options.pnn));
2957                 return ret;
2958         }
2959
2960         return 0;
2961 }
2962
2963 static uint32_t get_generation(struct ctdb_context *ctdb)
2964 {
2965         struct ctdb_vnn_map *vnnmap=NULL;
2966         int ret;
2967
2968         /* wait until the recmaster is not in recovery mode */
2969         while (1) {
2970                 uint32_t recmode, recmaster;
2971                 
2972                 if (vnnmap != NULL) {
2973                         talloc_free(vnnmap);
2974                         vnnmap = NULL;
2975                 }
2976
2977                 /* get the recmaster */
2978                 if (!ctdb_getrecmaster(ctdb_connection, CTDB_CURRENT_NODE, &recmaster)) {
2979                         DEBUG(DEBUG_ERR, ("Unable to get recmaster from node %u\n", options.pnn));
2980                         exit(10);
2981                 }
2982
2983                 /* get recovery mode */
2984                 if (!ctdb_getrecmode(ctdb_connection, recmaster, &recmode)) {
2985                         DEBUG(DEBUG_ERR, ("Unable to get recmode from node %u\n", options.pnn));
2986                         exit(10);
2987                 }
2988
2989                 /* get the current generation number */
2990                 ret = ctdb_ctrl_getvnnmap(ctdb, TIMELIMIT(), recmaster, ctdb, &vnnmap);
2991                 if (ret != 0) {
2992                         DEBUG(DEBUG_ERR, ("Unable to get vnnmap from recmaster (%u)\n", recmaster));
2993                         exit(10);
2994                 }
2995
2996                 if ((recmode == CTDB_RECOVERY_NORMAL)
2997                 &&  (vnnmap->generation != 1)){
2998                         return vnnmap->generation;
2999                 }
3000                 sleep(1);
3001         }
3002 }
3003
3004 /*
3005   ban a node from the cluster
3006  */
3007 static int control_ban(struct ctdb_context *ctdb, int argc, const char **argv)
3008 {
3009         int ret;
3010         struct ctdb_node_map *nodemap=NULL;
3011         struct ctdb_ban_time bantime;
3012
3013         if (argc < 1) {
3014                 usage();
3015         }
3016         
3017         /* verify the node exists */
3018         ret = ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE, ctdb, &nodemap);
3019         if (ret != 0) {
3020                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from local node\n"));
3021                 return ret;
3022         }
3023
3024         if (nodemap->nodes[options.pnn].flags & NODE_FLAGS_BANNED) {
3025                 DEBUG(DEBUG_ERR,("Node %u is already banned.\n", options.pnn));
3026                 return -1;
3027         }
3028
3029         bantime.pnn  = options.pnn;
3030         bantime.time = strtoul(argv[0], NULL, 0);
3031
3032         ret = ctdb_ctrl_set_ban(ctdb, TIMELIMIT(), options.pnn, &bantime);
3033         if (ret != 0) {
3034                 DEBUG(DEBUG_ERR,("Banning node %d for %d seconds failed.\n", bantime.pnn, bantime.time));
3035                 return -1;
3036         }       
3037
3038         ret = control_ipreallocate(ctdb, argc, argv);
3039         if (ret != 0) {
3040                 DEBUG(DEBUG_ERR, ("IP Reallocate failed on node %u\n", options.pnn));
3041                 return ret;
3042         }
3043
3044         return 0;
3045 }
3046
3047
3048 /*
3049   unban a node from the cluster
3050  */
3051 static int control_unban(struct ctdb_context *ctdb, int argc, const char **argv)
3052 {
3053         int ret;
3054         struct ctdb_node_map *nodemap=NULL;
3055         struct ctdb_ban_time bantime;
3056
3057         /* verify the node exists */
3058         ret = ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE, ctdb, &nodemap);
3059         if (ret != 0) {
3060                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from local node\n"));
3061                 return ret;
3062         }
3063
3064         if (!(nodemap->nodes[options.pnn].flags & NODE_FLAGS_BANNED)) {
3065                 DEBUG(DEBUG_ERR,("Node %u is not banned.\n", options.pnn));
3066                 return -1;
3067         }
3068
3069         bantime.pnn  = options.pnn;
3070         bantime.time = 0;
3071
3072         ret = ctdb_ctrl_set_ban(ctdb, TIMELIMIT(), options.pnn, &bantime);
3073         if (ret != 0) {
3074                 DEBUG(DEBUG_ERR,("Unbanning node %d failed.\n", bantime.pnn));
3075                 return -1;
3076         }       
3077
3078         ret = control_ipreallocate(ctdb, argc, argv);
3079         if (ret != 0) {
3080                 DEBUG(DEBUG_ERR, ("IP Reallocate failed on node %u\n", options.pnn));
3081                 return ret;
3082         }
3083
3084         return 0;
3085 }
3086
3087
3088 /*
3089   show ban information for a node
3090  */
3091 static int control_showban(struct ctdb_context *ctdb, int argc, const char **argv)
3092 {
3093         int ret;
3094         struct ctdb_node_map *nodemap=NULL;
3095         struct ctdb_ban_time *bantime;
3096
3097         /* verify the node exists */
3098         ret = ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE, ctdb, &nodemap);
3099         if (ret != 0) {
3100                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from local node\n"));
3101                 return ret;
3102         }
3103
3104         ret = ctdb_ctrl_get_ban(ctdb, TIMELIMIT(), options.pnn, ctdb, &bantime);
3105         if (ret != 0) {
3106                 DEBUG(DEBUG_ERR,("Showing ban info for node %d failed.\n", options.pnn));
3107                 return -1;
3108         }       
3109
3110         if (bantime->time == 0) {
3111                 printf("Node %u is not banned\n", bantime->pnn);
3112         } else {
3113                 printf("Node %u is banned banned for %d seconds\n", bantime->pnn, bantime->time);
3114         }
3115
3116         return 0;
3117 }
3118
3119 /*
3120   shutdown a daemon
3121  */
3122 static int control_shutdown(struct ctdb_context *ctdb, int argc, const char **argv)
3123 {
3124         int ret;
3125
3126         ret = ctdb_ctrl_shutdown(ctdb, TIMELIMIT(), options.pnn);
3127         if (ret != 0) {
3128                 DEBUG(DEBUG_ERR, ("Unable to shutdown node %u\n", options.pnn));
3129                 return ret;
3130         }
3131
3132         return 0;
3133 }
3134
3135 /*
3136   trigger a recovery
3137  */
3138 static int control_recover(struct ctdb_context *ctdb, int argc, const char **argv)
3139 {
3140         int ret;
3141         uint32_t generation, next_generation;
3142
3143         /* record the current generation number */
3144         generation = get_generation(ctdb);
3145
3146         ret = ctdb_ctrl_freeze_priority(ctdb, TIMELIMIT(), options.pnn, 1);
3147         if (ret != 0) {
3148                 DEBUG(DEBUG_ERR, ("Unable to freeze node\n"));
3149                 return ret;
3150         }
3151
3152         ret = ctdb_ctrl_setrecmode(ctdb, TIMELIMIT(), options.pnn, CTDB_RECOVERY_ACTIVE);
3153         if (ret != 0) {
3154                 DEBUG(DEBUG_ERR, ("Unable to set recovery mode\n"));
3155                 return ret;
3156         }
3157
3158         /* wait until we are in a new generation */
3159         while (1) {
3160                 next_generation = get_generation(ctdb);
3161                 if (next_generation != generation) {
3162                         return 0;
3163                 }
3164                 sleep(1);
3165         }
3166
3167         return 0;
3168 }
3169
3170
3171 /*
3172   display monitoring mode of a remote node
3173  */
3174 static int control_getmonmode(struct ctdb_context *ctdb, int argc, const char **argv)
3175 {
3176         uint32_t monmode;
3177         int ret;
3178
3179         ret = ctdb_ctrl_getmonmode(ctdb, TIMELIMIT(), options.pnn, &monmode);
3180         if (ret != 0) {
3181                 DEBUG(DEBUG_ERR, ("Unable to get monmode from node %u\n", options.pnn));
3182                 return ret;
3183         }
3184         if (!options.machinereadable){
3185                 printf("Monitoring mode:%s (%d)\n",monmode==CTDB_MONITORING_ACTIVE?"ACTIVE":"DISABLED",monmode);
3186         } else {
3187                 printf(":mode:\n");
3188                 printf(":%d:\n",monmode);
3189         }
3190         return 0;
3191 }
3192
3193
3194 /*
3195   display capabilities of a remote node
3196  */
3197 static int control_getcapabilities(struct ctdb_context *ctdb, int argc, const char **argv)
3198 {
3199         uint32_t capabilities;
3200
3201         if (!ctdb_getcapabilities(ctdb_connection, options.pnn, &capabilities)) {
3202                 DEBUG(DEBUG_ERR, ("Unable to get capabilities from node %u\n", options.pnn));
3203                 return -1;
3204         }
3205         
3206         if (!options.machinereadable){
3207                 printf("RECMASTER: %s\n", (capabilities&CTDB_CAP_RECMASTER)?"YES":"NO");
3208                 printf("LMASTER: %s\n", (capabilities&CTDB_CAP_LMASTER)?"YES":"NO");
3209                 printf("LVS: %s\n", (capabilities&CTDB_CAP_LVS)?"YES":"NO");
3210                 printf("NATGW: %s\n", (capabilities&CTDB_CAP_NATGW)?"YES":"NO");
3211         } else {
3212                 printf(":RECMASTER:LMASTER:LVS:NATGW:\n");
3213                 printf(":%d:%d:%d:%d:\n",
3214                         !!(capabilities&CTDB_CAP_RECMASTER),
3215                         !!(capabilities&CTDB_CAP_LMASTER),
3216                         !!(capabilities&CTDB_CAP_LVS),
3217                         !!(capabilities&CTDB_CAP_NATGW));
3218         }
3219         return 0;
3220 }
3221
3222 /*
3223   display lvs configuration
3224  */
3225 static int control_lvs(struct ctdb_context *ctdb, int argc, const char **argv)
3226 {
3227         uint32_t *capabilities;
3228         struct ctdb_node_map *nodemap=NULL;
3229         int i, ret;
3230         int healthy_count = 0;
3231
3232         if (!ctdb_getnodemap(ctdb_connection, options.pnn, &nodemap)) {
3233                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from node %u\n", options.pnn));
3234                 return -1;
3235         }
3236
3237         capabilities = talloc_array(ctdb, uint32_t, nodemap->num);
3238         CTDB_NO_MEMORY(ctdb, capabilities);
3239         
3240         ret = 0;
3241
3242         /* collect capabilities for all connected nodes */
3243         for (i=0; i<nodemap->num; i++) {
3244                 if (nodemap->nodes[i].flags & NODE_FLAGS_INACTIVE) {
3245                         continue;
3246                 }
3247                 if (nodemap->nodes[i].flags & NODE_FLAGS_PERMANENTLY_DISABLED) {
3248                         continue;
3249                 }
3250         
3251                 if (!ctdb_getcapabilities(ctdb_connection, i, &capabilities[i])) {
3252                         DEBUG(DEBUG_ERR, ("Unable to get capabilities from node %u\n", i));
3253                         ret = -1;
3254                         goto done;
3255                 }
3256
3257                 if (!(capabilities[i] & CTDB_CAP_LVS)) {
3258                         continue;
3259                 }
3260
3261                 if (!(nodemap->nodes[i].flags & NODE_FLAGS_UNHEALTHY)) {
3262                         healthy_count++;
3263                 }
3264         }
3265
3266         /* Print all LVS nodes */
3267         for (i=0; i<nodemap->num; i++) {
3268                 if (nodemap->nodes[i].flags & NODE_FLAGS_INACTIVE) {
3269                         continue;
3270                 }
3271                 if (nodemap->nodes[i].flags & NODE_FLAGS_PERMANENTLY_DISABLED) {
3272                         continue;
3273                 }
3274                 if (!(capabilities[i] & CTDB_CAP_LVS)) {
3275                         continue;
3276                 }
3277
3278                 if (healthy_count != 0) {
3279                         if (nodemap->nodes[i].flags & NODE_FLAGS_UNHEALTHY) {
3280                                 continue;
3281                         }
3282                 }
3283
3284                 printf("%d:%s\n", i, 
3285                         ctdb_addr_to_str(&nodemap->nodes[i].addr));
3286         }
3287
3288 done:
3289         ctdb_free_nodemap(nodemap);
3290         return ret;
3291 }
3292
3293 /*
3294   display who is the lvs master
3295  */
3296 static int control_lvsmaster(struct ctdb_context *ctdb, int argc, const char **argv)
3297 {
3298         uint32_t *capabilities;
3299         struct ctdb_node_map *nodemap=NULL;
3300         int i, ret;
3301         int healthy_count = 0;
3302
3303         if (!ctdb_getnodemap(ctdb_connection, options.pnn, &nodemap)) {
3304                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from node %u\n", options.pnn));
3305                 return -1;
3306         }
3307
3308         capabilities = talloc_array(ctdb, uint32_t, nodemap->num);
3309         CTDB_NO_MEMORY(ctdb, capabilities);
3310
3311         ret = -1;
3312         
3313         /* collect capabilities for all connected nodes */
3314         for (i=0; i<nodemap->num; i++) {
3315                 if (nodemap->nodes[i].flags & NODE_FLAGS_INACTIVE) {
3316                         continue;
3317                 }
3318                 if (nodemap->nodes[i].flags & NODE_FLAGS_PERMANENTLY_DISABLED) {
3319                         continue;
3320                 }
3321         
3322                 if (!ctdb_getcapabilities(ctdb_connection, i, &capabilities[i])) {
3323                         DEBUG(DEBUG_ERR, ("Unable to get capabilities from node %u\n", i));
3324                         ret = -1;
3325                         goto done;
3326                 }
3327
3328                 if (!(capabilities[i] & CTDB_CAP_LVS)) {
3329                         continue;
3330                 }
3331
3332                 if (!(nodemap->nodes[i].flags & NODE_FLAGS_UNHEALTHY)) {
3333                         healthy_count++;
3334                 }
3335         }
3336
3337         /* find and show the lvsmaster */
3338         for (i=0; i<nodemap->num; i++) {
3339                 if (nodemap->nodes[i].flags & NODE_FLAGS_INACTIVE) {
3340                         continue;
3341                 }
3342                 if (nodemap->nodes[i].flags & NODE_FLAGS_PERMANENTLY_DISABLED) {
3343                         continue;
3344                 }
3345                 if (!(capabilities[i] & CTDB_CAP_LVS)) {
3346                         continue;
3347                 }
3348
3349                 if (healthy_count != 0) {
3350                         if (nodemap->nodes[i].flags & NODE_FLAGS_UNHEALTHY) {
3351                                 continue;
3352                         }
3353                 }
3354
3355                 if (options.machinereadable){
3356                         printf("%d\n", i);
3357                 } else {
3358                         printf("Node %d is LVS master\n", i);
3359                 }
3360                 ret = 0;
3361                 goto done;
3362         }
3363
3364         printf("There is no LVS master\n");
3365 done:
3366         ctdb_free_nodemap(nodemap);
3367         return ret;
3368 }
3369
3370 /*
3371   disable monitoring on a  node
3372  */
3373 static int control_disable_monmode(struct ctdb_context *ctdb, int argc, const char **argv)
3374 {
3375         
3376         int ret;
3377
3378         ret = ctdb_ctrl_disable_monmode(ctdb, TIMELIMIT(), options.pnn);
3379         if (ret != 0) {
3380                 DEBUG(DEBUG_ERR, ("Unable to disable monmode on node %u\n", options.pnn));
3381                 return ret;
3382         }
3383         printf("Monitoring mode:%s\n","DISABLED");
3384
3385         return 0;
3386 }
3387
3388 /*
3389   enable monitoring on a  node
3390  */
3391 static int control_enable_monmode(struct ctdb_context *ctdb, int argc, const char **argv)
3392 {
3393         
3394         int ret;
3395
3396         ret = ctdb_ctrl_enable_monmode(ctdb, TIMELIMIT(), options.pnn);
3397         if (ret != 0) {
3398                 DEBUG(DEBUG_ERR, ("Unable to enable monmode on node %u\n", options.pnn));
3399                 return ret;
3400         }
3401         printf("Monitoring mode:%s\n","ACTIVE");
3402
3403         return 0;
3404 }
3405
3406 /*
3407   display remote list of keys/data for a db
3408  */
3409 static int control_catdb(struct ctdb_context *ctdb, int argc, const char **argv)
3410 {
3411         const char *db_name;
3412         struct ctdb_db_context *ctdb_db;
3413         int ret;
3414         struct ctdb_dump_db_context c;
3415         uint8_t flags;
3416
3417         if (argc < 1) {
3418                 usage();
3419         }
3420
3421         db_name = argv[0];
3422
3423         if (!db_exists(ctdb, db_name, NULL, &flags)) {
3424                 return -1;
3425         }
3426
3427         ctdb_db = ctdb_attach(ctdb, TIMELIMIT(), db_name, flags & CTDB_DB_FLAGS_PERSISTENT, 0);
3428         if (ctdb_db == NULL) {
3429                 DEBUG(DEBUG_ERR,("Unable to attach to database '%s'\n", db_name));
3430                 return -1;
3431         }
3432
3433         if (options.printlmaster) {
3434                 ret = ctdb_ctrl_getvnnmap(ctdb, TIMELIMIT(), options.pnn,
3435                                           ctdb, &ctdb->vnn_map);
3436                 if (ret != 0) {
3437                         DEBUG(DEBUG_ERR, ("Unable to get vnnmap from node %u\n",
3438                                           options.pnn));
3439                         return ret;
3440                 }
3441         }
3442
3443         ZERO_STRUCT(c);
3444         c.f = stdout;
3445         c.printemptyrecords = (bool)options.printemptyrecords;
3446         c.printdatasize = (bool)options.printdatasize;
3447         c.printlmaster = (bool)options.printlmaster;
3448         c.printhash = (bool)options.printhash;
3449         c.printrecordflags = (bool)options.printrecordflags;
3450
3451         /* traverse and dump the cluster tdb */
3452         ret = ctdb_dump_db(ctdb_db, &c);
3453         if (ret == -1) {
3454                 DEBUG(DEBUG_ERR, ("Unable to dump database\n"));
3455                 DEBUG(DEBUG_ERR, ("Maybe try 'ctdb getdbstatus %s'"
3456                                   " and 'ctdb getvar AllowUnhealthyDBRead'\n",
3457                                   db_name));
3458                 return -1;
3459         }
3460         talloc_free(ctdb_db);
3461
3462         printf("Dumped %d records\n", ret);
3463         return 0;
3464 }
3465
3466 struct cattdb_data {
3467         struct ctdb_context *ctdb;
3468         uint32_t count;
3469 };
3470
3471 static int cattdb_traverse(struct tdb_context *tdb, TDB_DATA key, TDB_DATA data, void *private_data)
3472 {
3473         struct cattdb_data *d = private_data;
3474         struct ctdb_dump_db_context c;
3475
3476         d->count++;
3477
3478         ZERO_STRUCT(c);
3479         c.f = stdout;
3480         c.printemptyrecords = (bool)options.printemptyrecords;
3481         c.printdatasize = (bool)options.printdatasize;
3482         c.printlmaster = false;
3483         c.printhash = (bool)options.printhash;
3484         c.printrecordflags = true;
3485
3486         return ctdb_dumpdb_record(d->ctdb, key, data, &c);
3487 }
3488
3489 /*
3490   cat the local tdb database using same format as catdb
3491  */
3492 static int control_cattdb(struct ctdb_context *ctdb, int argc, const char **argv)
3493 {
3494         const char *db_name;
3495         struct ctdb_db_context *ctdb_db;
3496         struct cattdb_data d;
3497         uint8_t flags;
3498
3499         if (argc < 1) {
3500                 usage();
3501         }
3502
3503         db_name = argv[0];
3504
3505         if (!db_exists(ctdb, db_name, NULL, &flags)) {
3506                 return -1;
3507         }
3508
3509         ctdb_db = ctdb_attach(ctdb, TIMELIMIT(), db_name, flags & CTDB_DB_FLAGS_PERSISTENT, 0);
3510         if (ctdb_db == NULL) {
3511                 DEBUG(DEBUG_ERR,("Unable to attach to database '%s'\n", db_name));
3512                 return -1;
3513         }
3514
3515         /* traverse the local tdb */
3516         d.count = 0;
3517         d.ctdb  = ctdb;
3518         if (tdb_traverse_read(ctdb_db->ltdb->tdb, cattdb_traverse, &d) == -1) {
3519                 printf("Failed to cattdb data\n");
3520                 exit(10);
3521         }
3522         talloc_free(ctdb_db);
3523
3524         printf("Dumped %d records\n", d.count);
3525         return 0;
3526 }
3527
3528 /*
3529   display the content of a database key
3530  */
3531 static int control_readkey(struct ctdb_context *ctdb, int argc, const char **argv)
3532 {
3533         const char *db_name;
3534         struct ctdb_db_context *ctdb_db;
3535         struct ctdb_record_handle *h;
3536         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
3537         TDB_DATA key, data;
3538         uint8_t flags;
3539
3540         if (argc < 2) {
3541                 usage();
3542         }
3543
3544         db_name = argv[0];
3545
3546         if (!db_exists(ctdb, db_name, NULL, &flags)) {
3547                 return -1;
3548         }
3549
3550         ctdb_db = ctdb_attach(ctdb, TIMELIMIT(), db_name, flags & CTDB_DB_FLAGS_PERSISTENT, 0);
3551         if (ctdb_db == NULL) {
3552                 DEBUG(DEBUG_ERR,("Unable to attach to database '%s'\n", db_name));
3553                 return -1;
3554         }
3555
3556         key.dptr  = discard_const(argv[1]);
3557         key.dsize = strlen((char *)key.dptr);
3558
3559         h = ctdb_fetch_lock(ctdb_db, tmp_ctx, key, &data);
3560         if (h == NULL) {
3561                 printf("Failed to fetch record '%s' on node %d\n", 
3562                         (const char *)key.dptr, ctdb_get_pnn(ctdb));
3563                 talloc_free(tmp_ctx);
3564                 exit(10);
3565         }
3566
3567         printf("Data: size:%d ptr:[%s]\n", (int)data.dsize, data.dptr);
3568
3569         talloc_free(ctdb_db);
3570         talloc_free(tmp_ctx);
3571         return 0;
3572 }
3573
3574 /*
3575   display the content of a database key
3576  */
3577 static int control_writekey(struct ctdb_context *ctdb, int argc, const char **argv)
3578 {
3579         const char *db_name;
3580         struct ctdb_db_context *ctdb_db;
3581         struct ctdb_record_handle *h;
3582         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
3583         TDB_DATA key, data;
3584         uint8_t flags;
3585
3586         if (argc < 3) {
3587                 usage();
3588         }
3589
3590         db_name = argv[0];
3591
3592         if (!db_exists(ctdb, db_name, NULL, &flags)) {
3593                 return -1;
3594         }
3595
3596         ctdb_db = ctdb_attach(ctdb, TIMELIMIT(), db_name, flags & CTDB_DB_FLAGS_PERSISTENT, 0);
3597         if (ctdb_db == NULL) {
3598                 DEBUG(DEBUG_ERR,("Unable to attach to database '%s'\n", db_name));
3599                 return -1;
3600         }
3601
3602         key.dptr  = discard_const(argv[1]);
3603         key.dsize = strlen((char *)key.dptr);
3604
3605         h = ctdb_fetch_lock(ctdb_db, tmp_ctx, key, &data);
3606         if (h == NULL) {
3607                 printf("Failed to fetch record '%s' on node %d\n", 
3608                         (const char *)key.dptr, ctdb_get_pnn(ctdb));
3609                 talloc_free(tmp_ctx);
3610                 exit(10);
3611         }
3612
3613         data.dptr  = discard_const(argv[2]);
3614         data.dsize = strlen((char *)data.dptr);
3615
3616         if (ctdb_record_store(h, data) != 0) {
3617                 printf("Failed to store record\n");
3618         }
3619
3620         talloc_free(h);
3621         talloc_free(ctdb_db);
3622         talloc_free(tmp_ctx);
3623         return 0;
3624 }
3625
3626 /*
3627   fetch a record from a persistent database
3628  */
3629 static int control_pfetch(struct ctdb_context *ctdb, int argc, const char **argv)
3630 {
3631         const char *db_name;
3632         struct ctdb_db_context *ctdb_db;
3633         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
3634         struct ctdb_transaction_handle *h;
3635         TDB_DATA key, data;
3636         int fd, ret;
3637         bool persistent;
3638         uint8_t flags;
3639
3640         if (argc < 2) {
3641                 talloc_free(tmp_ctx);
3642                 usage();
3643         }
3644
3645         db_name = argv[0];
3646
3647         if (!db_exists(ctdb, db_name, NULL, &flags)) {
3648                 talloc_free(tmp_ctx);
3649                 return -1;
3650         }
3651
3652         persistent = flags & CTDB_DB_FLAGS_PERSISTENT;
3653         if (!persistent) {
3654                 DEBUG(DEBUG_ERR,("Database '%s' is not persistent\n", db_name));
3655                 talloc_free(tmp_ctx);
3656                 return -1;
3657         }
3658
3659         ctdb_db = ctdb_attach(ctdb, TIMELIMIT(), db_name, persistent, 0);
3660         if (ctdb_db == NULL) {
3661                 DEBUG(DEBUG_ERR,("Unable to attach to database '%s'\n", db_name));
3662                 talloc_free(tmp_ctx);
3663                 return -1;
3664         }
3665
3666         h = ctdb_transaction_start(ctdb_db, tmp_ctx);
3667         if (h == NULL) {
3668                 DEBUG(DEBUG_ERR,("Failed to start transaction on database %s\n", db_name));
3669                 talloc_free(tmp_ctx);
3670                 return -1;
3671         }
3672
3673         key.dptr  = discard_const(argv[1]);
3674         key.dsize = strlen(argv[1]);
3675         ret = ctdb_transaction_fetch(h, tmp_ctx, key, &data);
3676         if (ret != 0) {
3677                 DEBUG(DEBUG_ERR,("Failed to fetch record\n"));
3678                 talloc_free(tmp_ctx);
3679                 return -1;
3680         }
3681
3682         if (data.dsize == 0 || data.dptr == NULL) {
3683                 DEBUG(DEBUG_ERR,("Record is empty\n"));
3684                 talloc_free(tmp_ctx);
3685                 return -1;
3686         }
3687
3688         if (argc == 3) {
3689           fd = open(argv[2], O_WRONLY|O_CREAT|O_TRUNC, 0600);
3690                 if (fd == -1) {
3691                         DEBUG(DEBUG_ERR,("Failed to open output file %s\n", argv[2]));
3692                         talloc_free(tmp_ctx);
3693                         return -1;
3694                 }
3695                 write(fd, data.dptr, data.dsize);
3696                 close(fd);
3697         } else {
3698                 write(1, data.dptr, data.dsize);
3699         }
3700
3701         /* abort the transaction */
3702         talloc_free(h);
3703
3704
3705         talloc_free(tmp_ctx);
3706         return 0;
3707 }
3708
3709 /*
3710   fetch a record from a tdb-file
3711  */
3712 static int control_tfetch(struct ctdb_context *ctdb, int argc, const char **argv)
3713 {
3714         const char *tdb_file;
3715         TDB_CONTEXT *tdb;
3716         TDB_DATA key, data;
3717         TALLOC_CTX *tmp_ctx = talloc_new(NULL);
3718         int fd;
3719
3720         if (argc < 2) {
3721                 usage();
3722         }
3723
3724         tdb_file = argv[0];
3725
3726         tdb = tdb_open(tdb_file, 0, 0, O_RDONLY, 0);
3727         if (tdb == NULL) {
3728                 printf("Failed to open TDB file %s\n", tdb_file);
3729                 return -1;
3730         }
3731
3732         if (!strncmp(argv[1], "0x", 2)) {
3733                 key = hextodata(tmp_ctx, argv[1] + 2);
3734                 if (key.dsize == 0) {
3735                         printf("Failed to convert \"%s\" into a TDB_DATA\n", argv[1]);
3736                         return -1;
3737                 }
3738         } else {
3739                 key.dptr  = discard_const(argv[1]);
3740                 key.dsize = strlen(argv[1]);
3741         }
3742
3743         data = tdb_fetch(tdb, key);
3744         if (data.dptr == NULL || data.dsize < sizeof(struct ctdb_ltdb_header)) {
3745                 printf("Failed to read record %s from tdb %s\n", argv[1], tdb_file);
3746                 tdb_close(tdb);
3747                 return -1;
3748         }
3749
3750         tdb_close(tdb);
3751
3752         if (argc == 3) {
3753           fd = open(argv[2], O_WRONLY|O_CREAT|O_TRUNC, 0600);
3754                 if (fd == -1) {
3755                         printf("Failed to open output file %s\n", argv[2]);
3756                         return -1;
3757                 }
3758                 if (options.verbose){
3759                         write(fd, data.dptr, data.dsize);
3760                 } else {
3761                         write(fd, data.dptr+sizeof(struct ctdb_ltdb_header), data.dsize-sizeof(struct ctdb_ltdb_header));
3762                 }
3763                 close(fd);
3764         } else {
3765                 if (options.verbose){
3766                         write(1, data.dptr, data.dsize);
3767                 } else {
3768                         write(1, data.dptr+sizeof(struct ctdb_ltdb_header), data.dsize-sizeof(struct ctdb_ltdb_header));
3769                 }
3770         }
3771
3772         talloc_free(tmp_ctx);
3773         return 0;
3774 }
3775
3776 /*
3777   store a record and header to a tdb-file
3778  */
3779 static int control_tstore(struct ctdb_context *ctdb, int argc, const char **argv)
3780 {
3781         const char *tdb_file;
3782         TDB_CONTEXT *tdb;
3783         TDB_DATA key, data;
3784         TALLOC_CTX *tmp_ctx = talloc_new(NULL);
3785
3786         if (argc < 3) {
3787                 usage();
3788         }
3789
3790         tdb_file = argv[0];
3791
3792         tdb = tdb_open(tdb_file, 0, 0, O_RDWR, 0);
3793         if (tdb == NULL) {
3794                 printf("Failed to open TDB file %s\n", tdb_file);
3795                 return -1;
3796         }
3797
3798         if (!strncmp(argv[1], "0x", 2)) {
3799                 key = hextodata(tmp_ctx, argv[1] + 2);
3800                 if (key.dsize == 0) {
3801                         printf("Failed to convert \"%s\" into a TDB_DATA\n", argv[1]);
3802                         return -1;
3803                 }
3804         } else {
3805                 key.dptr  = discard_const(argv[1]);
3806                 key.dsize = strlen(argv[1]);
3807         }
3808
3809         if (!strncmp(argv[2], "0x", 2)) {
3810                 data = hextodata(tmp_ctx, argv[2] + 2);
3811                 if (data.dsize == 0) {
3812                         printf("Failed to convert \"%s\" into a TDB_DATA\n", argv[2]);
3813                         return -1;
3814                 }
3815         } else {
3816                 data.dptr  = discard_const(argv[2]);
3817                 data.dsize = strlen(argv[2]);
3818         }
3819
3820         if (data.dsize < sizeof(struct ctdb_ltdb_header)) {
3821                 printf("Not enough data. You must specify the full ctdb_ltdb_header too when storing\n");
3822                 return -1;
3823         }
3824         if (tdb_store(tdb, key, data, TDB_REPLACE) != 0) {
3825                 printf("Failed to write record %s to tdb %s\n", argv[1], tdb_file);
3826                 tdb_close(tdb);
3827                 return -1;
3828         }
3829
3830         tdb_close(tdb);
3831
3832         talloc_free(tmp_ctx);
3833         return 0;
3834 }
3835
3836 /*
3837   write a record to a persistent database
3838  */
3839 static int control_pstore(struct ctdb_context *ctdb, int argc, const char **argv)
3840 {
3841         const char *db_name;
3842         struct ctdb_db_context *ctdb_db;
3843         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
3844         struct ctdb_transaction_handle *h;
3845         struct stat st;
3846         TDB_DATA key, data;
3847         int fd, ret;
3848
3849         if (argc < 3) {
3850                 talloc_free(tmp_ctx);
3851                 usage();
3852         }
3853
3854         fd = open(argv[2], O_RDONLY);
3855         if (fd == -1) {
3856                 DEBUG(DEBUG_ERR,("Failed to open file containing record data : %s  %s\n", argv[2], strerror(errno)));
3857                 talloc_free(tmp_ctx);
3858                 return -1;
3859         }
3860         
3861         ret = fstat(fd, &st);
3862         if (ret == -1) {
3863                 DEBUG(DEBUG_ERR,("fstat of file %s failed: %s\n", argv[2], strerror(errno)));
3864                 close(fd);
3865                 talloc_free(tmp_ctx);
3866                 return -1;
3867         }
3868
3869         if (!S_ISREG(st.st_mode)) {
3870                 DEBUG(DEBUG_ERR,("Not a regular file %s\n", argv[2]));
3871                 close(fd);
3872                 talloc_free(tmp_ctx);
3873                 return -1;
3874         }
3875
3876         data.dsize = st.st_size;
3877         if (data.dsize == 0) {
3878                 data.dptr  = NULL;
3879         } else {
3880                 data.dptr = talloc_size(tmp_ctx, data.dsize);
3881                 if (data.dptr == NULL) {
3882                         DEBUG(DEBUG_ERR,("Failed to talloc %d of memory to store record data\n", (int)data.dsize));
3883                         close(fd);
3884                         talloc_free(tmp_ctx);
3885                         return -1;
3886                 }
3887                 ret = read(fd, data.dptr, data.dsize);
3888                 if (ret != data.dsize) {
3889                         DEBUG(DEBUG_ERR,("Failed to read %d bytes of record data\n", (int)data.dsize));
3890                         close(fd);
3891                         talloc_free(tmp_ctx);
3892                         return -1;
3893                 }
3894         }
3895         close(fd);
3896
3897
3898         db_name = argv[0];
3899
3900         ctdb_db = ctdb_attach(ctdb, TIMELIMIT(), db_name, true, 0);
3901         if (ctdb_db == NULL) {
3902                 DEBUG(DEBUG_ERR,("Unable to attach to database '%s'\n", db_name));
3903                 talloc_free(tmp_ctx);
3904                 return -1;
3905         }
3906
3907         h = ctdb_transaction_start(ctdb_db, tmp_ctx);
3908         if (h == NULL) {
3909                 DEBUG(DEBUG_ERR,("Failed to start transaction on database %s\n", db_name));
3910                 talloc_free(tmp_ctx);
3911                 return -1;
3912         }
3913
3914         key.dptr  = discard_const(argv[1]);
3915         key.dsize = strlen(argv[1]);
3916         ret = ctdb_transaction_store(h, key, data);
3917         if (ret != 0) {
3918                 DEBUG(DEBUG_ERR,("Failed to store record\n"));
3919                 talloc_free(tmp_ctx);
3920                 return -1;
3921         }
3922
3923         ret = ctdb_transaction_commit(h);
3924         if (ret != 0) {
3925                 DEBUG(DEBUG_ERR,("Failed to commit transaction\n"));
3926                 talloc_free(tmp_ctx);
3927                 return -1;
3928         }
3929
3930
3931         talloc_free(tmp_ctx);
3932         return 0;
3933 }
3934
3935 /*
3936  * delete a record from a persistent database
3937  */
3938 static int control_pdelete(struct ctdb_context *ctdb, int argc, const char **argv)
3939 {
3940         const char *db_name;
3941         struct ctdb_db_context *ctdb_db;
3942         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
3943         struct ctdb_transaction_handle *h;
3944         TDB_DATA key;
3945         int ret;
3946         bool persistent;
3947         uint8_t flags;
3948
3949         if (argc < 2) {
3950                 talloc_free(tmp_ctx);
3951                 usage();
3952         }
3953
3954         db_name = argv[0];
3955
3956         if (!db_exists(ctdb, db_name, NULL, &flags)) {
3957                 talloc_free(tmp_ctx);
3958                 return -1;
3959         }
3960
3961         persistent = flags & CTDB_DB_FLAGS_PERSISTENT;
3962         if (!persistent) {
3963                 DEBUG(DEBUG_ERR, ("Database '%s' is not persistent\n", db_name));
3964                 talloc_free(tmp_ctx);
3965                 return -1;
3966         }
3967
3968         ctdb_db = ctdb_attach(ctdb, TIMELIMIT(), db_name, persistent, 0);
3969         if (ctdb_db == NULL) {
3970                 DEBUG(DEBUG_ERR, ("Unable to attach to database '%s'\n", db_name));
3971                 talloc_free(tmp_ctx);
3972                 return -1;
3973         }
3974
3975         h = ctdb_transaction_start(ctdb_db, tmp_ctx);
3976         if (h == NULL) {
3977                 DEBUG(DEBUG_ERR, ("Failed to start transaction on database %s\n", db_name));
3978                 talloc_free(tmp_ctx);
3979                 return -1;
3980         }
3981
3982         key.dptr = discard_const(argv[1]);
3983         key.dsize = strlen(argv[1]);
3984         ret = ctdb_transaction_store(h, key, tdb_null);
3985         if (ret != 0) {
3986                 DEBUG(DEBUG_ERR, ("Failed to delete record\n"));
3987                 talloc_free(tmp_ctx);
3988                 return -1;
3989         }
3990
3991         ret = ctdb_transaction_commit(h);
3992         if (ret != 0) {
3993                 DEBUG(DEBUG_ERR, ("Failed to commit transaction\n"));
3994                 talloc_free(tmp_ctx);
3995                 return -1;
3996         }
3997
3998         talloc_free(tmp_ctx);
3999         return 0;
4000 }
4001
4002 /*
4003   check if a service is bound to a port or not
4004  */
4005 static int control_chktcpport(struct ctdb_context *ctdb, int argc, const char **argv)
4006 {
4007         int s, ret;
4008         unsigned v;
4009         int port;
4010         struct sockaddr_in sin;
4011
4012         if (argc != 1) {
4013                 printf("Use: ctdb chktcport <port>\n");
4014                 return EINVAL;
4015         }
4016
4017         port = atoi(argv[0]);
4018
4019         s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
4020         if (s == -1) {
4021                 printf("Failed to open local socket\n");
4022                 return errno;
4023         }
4024
4025         v = fcntl(s, F_GETFL, 0);
4026         fcntl(s, F_SETFL, v | O_NONBLOCK);
4027
4028         bzero(&sin, sizeof(sin));
4029         sin.sin_family = PF_INET;
4030         sin.sin_port   = htons(port);
4031         ret = bind(s, (struct sockaddr *)&sin, sizeof(sin));
4032         close(s);
4033         if (ret == -1) {
4034                 printf("Failed to bind to local socket: %d %s\n", errno, strerror(errno));
4035                 return errno;
4036         }
4037
4038         return 0;
4039 }
4040
4041
4042
4043 static void log_handler(struct ctdb_context *ctdb, uint64_t srvid, 
4044                              TDB_DATA data, void *private_data)
4045 {
4046         DEBUG(DEBUG_ERR,("Log data received\n"));
4047         if (data.dsize > 0) {
4048                 printf("%s", data.dptr);
4049         }
4050
4051         exit(0);
4052 }
4053
4054 /*
4055   display a list of log messages from the in memory ringbuffer
4056  */
4057 static int control_getlog(struct ctdb_context *ctdb, int argc, const char **argv)
4058 {
4059         int ret, i;
4060         bool main_daemon;
4061         struct ctdb_get_log_addr log_addr;
4062         TDB_DATA data;
4063         struct timeval tv;
4064
4065         /* Since this can fail, do it first */
4066         log_addr.pnn = ctdb_ctrl_getpnn(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE);
4067         if (log_addr.pnn == -1) {
4068                 DEBUG(DEBUG_ERR, ("Failed to get pnn of local node\n"));
4069                 return -1;
4070         }
4071
4072         /* Process options */
4073         main_daemon = true;
4074         log_addr.level = DEBUG_NOTICE;
4075         for (i = 0; i < argc; i++) {
4076                 if (strcmp(argv[i], "recoverd") == 0) {
4077                         main_daemon = false;
4078                 } else {
4079                         if (isalpha(argv[i][0]) || argv[i][0] == '-') { 
4080                                 log_addr.level = get_debug_by_desc(argv[i]);
4081                         } else {
4082                                 log_addr.level = strtol(argv[i], NULL, 0);
4083                         }
4084                 }
4085         }
4086
4087         /* Our message port is our PID */
4088         log_addr.srvid = getpid();
4089
4090         data.dptr = (unsigned char *)&log_addr;
4091         data.dsize = sizeof(log_addr);
4092
4093         DEBUG(DEBUG_ERR, ("Pulling logs from node %u\n", options.pnn));
4094
4095         ctdb_client_set_message_handler(ctdb, log_addr.srvid, log_handler, NULL);
4096         sleep(1);
4097
4098         DEBUG(DEBUG_ERR,("Listen for response on %d\n", (int)log_addr.srvid));
4099
4100         if (main_daemon) {
4101                 int32_t res;
4102                 char *errmsg;
4103                 TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
4104
4105                 ret = ctdb_control(ctdb, options.pnn, 0, CTDB_CONTROL_GET_LOG,
4106                                    0, data, tmp_ctx, NULL, &res, NULL, &errmsg);
4107                 if (ret != 0 || res != 0) {
4108                         DEBUG(DEBUG_ERR,("Failed to get logs - %s\n", errmsg));
4109                         talloc_free(tmp_ctx);
4110                         return -1;
4111                 }
4112                 talloc_free(tmp_ctx);
4113         } else {
4114                 ret = ctdb_client_send_message(ctdb, options.pnn,
4115                                                CTDB_SRVID_GETLOG, data);
4116                 if (ret != 0) {
4117                         DEBUG(DEBUG_ERR,("Failed to send getlog request message to %u\n", options.pnn));
4118                         return -1;
4119                 }
4120         }
4121
4122         tv = timeval_current();
4123         /* this loop will terminate when we have received the reply */
4124         while (timeval_elapsed(&tv) < (double)options.timelimit) {
4125                 event_loop_once(ctdb->ev);
4126         }
4127
4128         DEBUG(DEBUG_INFO,("Timed out waiting for log data.\n"));
4129
4130         return 0;
4131 }
4132
4133 /*
4134   clear the in memory log area
4135  */
4136 static int control_clearlog(struct ctdb_context *ctdb, int argc, const char **argv)
4137 {
4138         int ret;
4139
4140         if (argc == 0 || (argc >= 1 && strcmp(argv[0], "recoverd") != 0)) {
4141                 /* "recoverd" not given - get logs from main daemon */
4142                 int32_t res;
4143                 char *errmsg;
4144                 TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
4145
4146                 ret = ctdb_control(ctdb, options.pnn, 0, CTDB_CONTROL_CLEAR_LOG,
4147                                    0, tdb_null, tmp_ctx, NULL, &res, NULL, &errmsg);
4148                 if (ret != 0 || res != 0) {
4149                         DEBUG(DEBUG_ERR,("Failed to clear logs\n"));
4150                         talloc_free(tmp_ctx);
4151                         return -1;
4152                 }
4153
4154                 talloc_free(tmp_ctx);
4155         } else {
4156                 TDB_DATA data; /* unused in recoverd... */
4157                 data.dsize = 0;
4158
4159                 ret = ctdb_client_send_message(ctdb, options.pnn, CTDB_SRVID_CLEARLOG, data);
4160                 if (ret != 0) {
4161                         DEBUG(DEBUG_ERR,("Failed to send clearlog request message to %u\n", options.pnn));
4162                         return -1;
4163                 }
4164         }
4165
4166         return 0;
4167 }
4168
4169
4170 static uint32_t reloadips_finished;
4171
4172 static void reloadips_handler(struct ctdb_context *ctdb, uint64_t srvid, 
4173                              TDB_DATA data, void *private_data)
4174 {
4175         reloadips_finished = 1;
4176 }
4177
4178 static int reloadips_all(struct ctdb_context *ctdb)
4179 {
4180         struct reloadips_all_reply rips;
4181         struct ctdb_node_map *nodemap=NULL;
4182         TDB_DATA data;
4183         uint32_t recmaster;
4184         int ret, i;
4185
4186         /* check that there are valid nodes available */
4187         if (ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE, ctdb, &nodemap) != 0) {
4188                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from local node\n"));
4189                 return 1;
4190         }
4191         for (i=0; i<nodemap->num;i++) {
4192                 if (nodemap->nodes[i].flags != 0) {
4193                         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));
4194                         return 1;
4195                 }
4196         }
4197
4198
4199         rips.pnn = ctdb_ctrl_getpnn(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE);
4200         if (rips.pnn == -1) {
4201                 DEBUG(DEBUG_ERR, ("Failed to get pnn of local node\n"));
4202                 return 1;
4203         }
4204         rips.srvid = getpid();
4205
4206
4207         /* register a message port for receiveing the reply so that we
4208            can receive the reply
4209         */
4210         ctdb_client_set_message_handler(ctdb, rips.srvid, reloadips_handler, NULL);
4211
4212         if (!ctdb_getrecmaster(ctdb_connection, CTDB_CURRENT_NODE, &recmaster)) {
4213                 DEBUG(DEBUG_ERR, ("Unable to get recmaster from node\n"));
4214                 return -1;
4215         }
4216
4217
4218         data.dptr = (uint8_t *)&rips;
4219         data.dsize = sizeof(rips);
4220
4221         ret = ctdb_client_send_message(ctdb, recmaster, CTDB_SRVID_RELOAD_ALL_IPS, data);
4222         if (ret != 0) {
4223                 DEBUG(DEBUG_ERR,("Failed to send reload all ips request message to %u\n", options.pnn));
4224                 return 1;
4225         }
4226
4227         reloadips_finished = 0;
4228         while (reloadips_finished == 0) {
4229                 event_loop_once(ctdb->ev);
4230         }
4231
4232         return 0;
4233 }
4234
4235 /*
4236   reload public ips on a specific node
4237  */
4238 static int control_reloadips(struct ctdb_context *ctdb, int argc, const char **argv)
4239 {
4240         int ret;
4241         int32_t res;
4242         char *errmsg;
4243         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
4244
4245         if (options.pnn == CTDB_BROADCAST_ALL) {
4246                 return reloadips_all(ctdb);
4247         }
4248
4249         ret = ctdb_control(ctdb, options.pnn, 0, CTDB_CONTROL_RELOAD_PUBLIC_IPS,
4250                            0, tdb_null, tmp_ctx, NULL, &res, NULL, &errmsg);
4251         if (ret != 0 || res != 0) {
4252                 DEBUG(DEBUG_ERR,("Failed to reload ips\n"));
4253                 talloc_free(tmp_ctx);
4254                 return -1;
4255         }
4256
4257         talloc_free(tmp_ctx);
4258         return 0;
4259 }
4260
4261 /*
4262   display a list of the databases on a remote ctdb
4263  */
4264 static int control_getdbmap(struct ctdb_context *ctdb, int argc, const char **argv)
4265 {
4266         int i, ret;
4267         struct ctdb_dbid_map *dbmap=NULL;
4268
4269         ret = ctdb_ctrl_getdbmap(ctdb, TIMELIMIT(), options.pnn, ctdb, &dbmap);
4270         if (ret != 0) {
4271                 DEBUG(DEBUG_ERR, ("Unable to get dbids from node %u\n", options.pnn));
4272                 return ret;
4273         }
4274
4275         if(options.machinereadable){
4276                 printf(":ID:Name:Path:Persistent:Sticky:Unhealthy:ReadOnly:\n");
4277                 for(i=0;i<dbmap->num;i++){
4278                         const char *path;
4279                         const char *name;
4280                         const char *health;
4281                         bool persistent;
4282                         bool readonly;
4283                         bool sticky;
4284
4285                         ctdb_ctrl_getdbpath(ctdb, TIMELIMIT(), options.pnn,
4286                                             dbmap->dbs[i].dbid, ctdb, &path);
4287                         ctdb_ctrl_getdbname(ctdb, TIMELIMIT(), options.pnn,
4288                                             dbmap->dbs[i].dbid, ctdb, &name);
4289                         ctdb_ctrl_getdbhealth(ctdb, TIMELIMIT(), options.pnn,
4290                                               dbmap->dbs[i].dbid, ctdb, &health);
4291                         persistent = dbmap->dbs[i].flags & CTDB_DB_FLAGS_PERSISTENT;
4292                         readonly   = dbmap->dbs[i].flags & CTDB_DB_FLAGS_READONLY;
4293                         sticky     = dbmap->dbs[i].flags & CTDB_DB_FLAGS_STICKY;
4294                         printf(":0x%08X:%s:%s:%d:%d:%d:%d:\n",
4295                                dbmap->dbs[i].dbid, name, path,
4296                                !!(persistent), !!(sticky),
4297                                !!(health), !!(readonly));
4298                 }
4299                 return 0;
4300         }
4301
4302         printf("Number of databases:%d\n", dbmap->num);
4303         for(i=0;i<dbmap->num;i++){
4304                 const char *path;
4305                 const char *name;
4306                 const char *health;
4307                 bool persistent;
4308                 bool readonly;
4309                 bool sticky;
4310
4311                 ctdb_ctrl_getdbpath(ctdb, TIMELIMIT(), options.pnn, dbmap->dbs[i].dbid, ctdb, &path);
4312                 ctdb_ctrl_getdbname(ctdb, TIMELIMIT(), options.pnn, dbmap->dbs[i].dbid, ctdb, &name);
4313                 ctdb_ctrl_getdbhealth(ctdb, TIMELIMIT(), options.pnn, dbmap->dbs[i].dbid, ctdb, &health);
4314                 persistent = dbmap->dbs[i].flags & CTDB_DB_FLAGS_PERSISTENT;
4315                 readonly   = dbmap->dbs[i].flags & CTDB_DB_FLAGS_READONLY;
4316                 sticky     = dbmap->dbs[i].flags & CTDB_DB_FLAGS_STICKY;
4317                 printf("dbid:0x%08x name:%s path:%s%s%s%s%s\n",
4318                        dbmap->dbs[i].dbid, name, path,
4319                        persistent?" PERSISTENT":"",
4320                        sticky?" STICKY":"",
4321                        readonly?" READONLY":"",
4322                        health?" UNHEALTHY":"");
4323         }
4324
4325         return 0;
4326 }
4327
4328 /*
4329   display the status of a database on a remote ctdb
4330  */
4331 static int control_getdbstatus(struct ctdb_context *ctdb, int argc, const char **argv)
4332 {
4333         const char *db_name;
4334         uint32_t db_id;
4335         uint8_t flags;
4336         const char *path;
4337         const char *health;
4338
4339         if (argc < 1) {
4340                 usage();
4341         }
4342
4343         db_name = argv[0];
4344
4345         if (!db_exists(ctdb, db_name, &db_id, &flags)) {
4346                 return -1;
4347         }
4348
4349         ctdb_ctrl_getdbpath(ctdb, TIMELIMIT(), options.pnn, db_id, ctdb, &path);
4350         ctdb_ctrl_getdbhealth(ctdb, TIMELIMIT(), options.pnn, db_id, ctdb, &health);
4351         printf("dbid: 0x%08x\nname: %s\npath: %s\nPERSISTENT: %s\nSTICKY: %s\nREADONLY: %s\nHEALTH: %s\n",
4352                db_id, db_name, path,
4353                (flags & CTDB_DB_FLAGS_PERSISTENT ? "yes" : "no"),
4354                (flags & CTDB_DB_FLAGS_STICKY ? "yes" : "no"),
4355                (flags & CTDB_DB_FLAGS_READONLY ? "yes" : "no"),
4356                (health ? health : "OK"));
4357
4358         return 0;
4359 }
4360
4361 /*
4362   check if the local node is recmaster or not
4363   it will return 1 if this node is the recmaster and 0 if it is not
4364   or if the local ctdb daemon could not be contacted
4365  */
4366 static int control_isnotrecmaster(struct ctdb_context *ctdb, int argc, const char **argv)
4367 {
4368         uint32_t mypnn, recmaster;
4369
4370         mypnn = ctdb_ctrl_getpnn(ctdb, TIMELIMIT(), options.pnn);
4371         if (mypnn == -1) {
4372                 printf("Failed to get pnn of node\n");
4373                 return 1;
4374         }
4375
4376         if (!ctdb_getrecmaster(ctdb_connection, options.pnn, &recmaster)) {
4377                 printf("Failed to get the recmaster\n");
4378                 return 1;
4379         }
4380
4381         if (recmaster != mypnn) {
4382                 printf("this node is not the recmaster\n");
4383                 return 1;
4384         }
4385
4386         printf("this node is the recmaster\n");
4387         return 0;
4388 }
4389
4390 /*
4391   ping a node
4392  */
4393 static int control_ping(struct ctdb_context *ctdb, int argc, const char **argv)
4394 {
4395         int ret;
4396         struct timeval tv = timeval_current();
4397         ret = ctdb_ctrl_ping(ctdb, options.pnn);
4398         if (ret == -1) {
4399                 printf("Unable to get ping response from node %u\n", options.pnn);
4400                 return -1;
4401         } else {
4402                 printf("response from %u time=%.6f sec  (%d clients)\n", 
4403                        options.pnn, timeval_elapsed(&tv), ret);
4404         }
4405         return 0;
4406 }
4407
4408
4409 /*
4410   get a tunable
4411  */
4412 static int control_getvar(struct ctdb_context *ctdb, int argc, const char **argv)
4413 {
4414         const char *name;
4415         uint32_t value;
4416         int ret;
4417
4418         if (argc < 1) {
4419                 usage();
4420         }
4421
4422         name = argv[0];
4423         ret = ctdb_ctrl_get_tunable(ctdb, TIMELIMIT(), options.pnn, name, &value);
4424         if (ret == -1) {
4425                 DEBUG(DEBUG_ERR, ("Unable to get tunable variable '%s'\n", name));
4426                 return -1;
4427         }
4428
4429         printf("%-23s = %u\n", name, value);
4430         return 0;
4431 }
4432
4433 /*
4434   set a tunable
4435  */
4436 static int control_setvar(struct ctdb_context *ctdb, int argc, const char **argv)
4437 {
4438         const char *name;
4439         uint32_t value;
4440         int ret;
4441
4442         if (argc < 2) {
4443                 usage();
4444         }
4445
4446         name = argv[0];
4447         value = strtoul(argv[1], NULL, 0);
4448
4449         ret = ctdb_ctrl_set_tunable(ctdb, TIMELIMIT(), options.pnn, name, value);
4450         if (ret == -1) {
4451                 DEBUG(DEBUG_ERR, ("Unable to set tunable variable '%s'\n", name));
4452                 return -1;
4453         }
4454         return 0;
4455 }
4456
4457 /*
4458   list all tunables
4459  */
4460 static int control_listvars(struct ctdb_context *ctdb, int argc, const char **argv)
4461 {
4462         uint32_t count;
4463         const char **list;
4464         int ret, i;
4465
4466         ret = ctdb_ctrl_list_tunables(ctdb, TIMELIMIT(), options.pnn, ctdb, &list, &count);
4467         if (ret == -1) {
4468                 DEBUG(DEBUG_ERR, ("Unable to list tunable variables\n"));
4469                 return -1;
4470         }
4471
4472         for (i=0;i<count;i++) {
4473                 control_getvar(ctdb, 1, &list[i]);
4474         }
4475
4476         talloc_free(list);
4477         
4478         return 0;
4479 }
4480
4481 /*
4482   display debug level on a node
4483  */
4484 static int control_getdebug(struct ctdb_context *ctdb, int argc, const char **argv)
4485 {
4486         int ret;
4487         int32_t level;
4488
4489         ret = ctdb_ctrl_get_debuglevel(ctdb, options.pnn, &level);
4490         if (ret != 0) {
4491                 DEBUG(DEBUG_ERR, ("Unable to get debuglevel response from node %u\n", options.pnn));
4492                 return ret;
4493         } else {
4494                 if (options.machinereadable){
4495                         printf(":Name:Level:\n");
4496                         printf(":%s:%d:\n",get_debug_by_level(level),level);
4497                 } else {
4498                         printf("Node %u is at debug level %s (%d)\n", options.pnn, get_debug_by_level(level), level);
4499                 }
4500         }
4501         return 0;
4502 }
4503
4504 /*
4505   display reclock file of a node
4506  */
4507 static int control_getreclock(struct ctdb_context *ctdb, int argc, const char **argv)
4508 {
4509         int ret;
4510         const char *reclock;
4511
4512         ret = ctdb_ctrl_getreclock(ctdb, TIMELIMIT(), options.pnn, ctdb, &reclock);
4513         if (ret != 0) {
4514                 DEBUG(DEBUG_ERR, ("Unable to get reclock file from node %u\n", options.pnn));
4515                 return ret;
4516         } else {
4517                 if (options.machinereadable){
4518                         if (reclock != NULL) {
4519                                 printf("%s", reclock);
4520                         }
4521                 } else {
4522                         if (reclock == NULL) {
4523                                 printf("No reclock file used.\n");
4524                         } else {
4525                                 printf("Reclock file:%s\n", reclock);
4526                         }
4527                 }
4528         }
4529         return 0;
4530 }
4531
4532 /*
4533   set the reclock file of a node
4534  */
4535 static int control_setreclock(struct ctdb_context *ctdb, int argc, const char **argv)
4536 {
4537         int ret;
4538         const char *reclock;
4539
4540         if (argc == 0) {
4541                 reclock = NULL;
4542         } else if (argc == 1) {
4543                 reclock = argv[0];
4544         } else {
4545                 usage();
4546         }
4547
4548         ret = ctdb_ctrl_setreclock(ctdb, TIMELIMIT(), options.pnn, reclock);
4549         if (ret != 0) {
4550                 DEBUG(DEBUG_ERR, ("Unable to get reclock file from node %u\n", options.pnn));
4551                 return ret;
4552         }
4553         return 0;
4554 }
4555
4556 /*
4557   set the natgw state on/off
4558  */
4559 static int control_setnatgwstate(struct ctdb_context *ctdb, int argc, const char **argv)
4560 {
4561         int ret;
4562         uint32_t natgwstate;
4563
4564         if (argc == 0) {
4565                 usage();
4566         }
4567
4568         if (!strcmp(argv[0], "on")) {
4569                 natgwstate = 1;
4570         } else if (!strcmp(argv[0], "off")) {
4571                 natgwstate = 0;
4572         } else {
4573                 usage();
4574         }
4575
4576         ret = ctdb_ctrl_setnatgwstate(ctdb, TIMELIMIT(), options.pnn, natgwstate);
4577         if (ret != 0) {
4578                 DEBUG(DEBUG_ERR, ("Unable to set the natgw state for node %u\n", options.pnn));
4579                 return ret;
4580         }
4581
4582         return 0;
4583 }
4584
4585 /*
4586   set the lmaster role on/off
4587  */
4588 static int control_setlmasterrole(struct ctdb_context *ctdb, int argc, const char **argv)
4589 {
4590         int ret;
4591         uint32_t lmasterrole;
4592
4593         if (argc == 0) {
4594                 usage();
4595         }
4596
4597         if (!strcmp(argv[0], "on")) {
4598                 lmasterrole = 1;
4599         } else if (!strcmp(argv[0], "off")) {
4600                 lmasterrole = 0;
4601         } else {
4602                 usage();
4603         }
4604
4605         ret = ctdb_ctrl_setlmasterrole(ctdb, TIMELIMIT(), options.pnn, lmasterrole);
4606         if (ret != 0) {
4607                 DEBUG(DEBUG_ERR, ("Unable to set the lmaster role for node %u\n", options.pnn));
4608                 return ret;
4609         }
4610
4611         return 0;
4612 }
4613
4614 /*
4615   set the recmaster role on/off
4616  */
4617 static int control_setrecmasterrole(struct ctdb_context *ctdb, int argc, const char **argv)
4618 {
4619         int ret;
4620         uint32_t recmasterrole;
4621
4622         if (argc == 0) {
4623                 usage();
4624         }
4625
4626         if (!strcmp(argv[0], "on")) {
4627                 recmasterrole = 1;
4628         } else if (!strcmp(argv[0], "off")) {
4629                 recmasterrole = 0;
4630         } else {
4631                 usage();
4632         }
4633
4634         ret = ctdb_ctrl_setrecmasterrole(ctdb, TIMELIMIT(), options.pnn, recmasterrole);
4635         if (ret != 0) {
4636                 DEBUG(DEBUG_ERR, ("Unable to set the recmaster role for node %u\n", options.pnn));
4637                 return ret;
4638         }
4639
4640         return 0;
4641 }
4642
4643 /*
4644   set debug level on a node or all nodes
4645  */
4646 static int control_setdebug(struct ctdb_context *ctdb, int argc, const char **argv)
4647 {
4648         int i, ret;
4649         int32_t level;
4650
4651         if (argc == 0) {
4652                 printf("You must specify the debug level. Valid levels are:\n");
4653                 for (i=0; debug_levels[i].description != NULL; i++) {
4654                         printf("%s (%d)\n", debug_levels[i].description, debug_levels[i].level);
4655                 }
4656
4657                 return 0;
4658         }
4659
4660         if (isalpha(argv[0][0]) || argv[0][0] == '-') { 
4661                 level = get_debug_by_desc(argv[0]);
4662         } else {
4663                 level = strtol(argv[0], NULL, 0);
4664         }
4665
4666         for (i=0; debug_levels[i].description != NULL; i++) {
4667                 if (level == debug_levels[i].level) {
4668                         break;
4669                 }
4670         }
4671         if (debug_levels[i].description == NULL) {
4672                 printf("Invalid debug level, must be one of\n");
4673                 for (i=0; debug_levels[i].description != NULL; i++) {
4674                         printf("%s (%d)\n", debug_levels[i].description, debug_levels[i].level);
4675                 }
4676                 return -1;
4677         }
4678
4679         ret = ctdb_ctrl_set_debuglevel(ctdb, options.pnn, level);
4680         if (ret != 0) {
4681                 DEBUG(DEBUG_ERR, ("Unable to set debug level on node %u\n", options.pnn));
4682         }
4683         return 0;
4684 }
4685
4686
4687 /*
4688   thaw a node
4689  */
4690 static int control_thaw(struct ctdb_context *ctdb, int argc, const char **argv)
4691 {
4692         int ret;
4693         uint32_t priority;
4694         
4695         if (argc == 1) {
4696                 priority = strtol(argv[0], NULL, 0);
4697         } else {
4698                 priority = 0;
4699         }
4700         DEBUG(DEBUG_ERR,("Thaw by priority %u\n", priority));
4701
4702         ret = ctdb_ctrl_thaw_priority(ctdb, TIMELIMIT(), options.pnn, priority);
4703         if (ret != 0) {
4704                 DEBUG(DEBUG_ERR, ("Unable to thaw node %u\n", options.pnn));
4705         }               
4706         return 0;
4707 }
4708
4709
4710 /*
4711   attach to a database
4712  */
4713 static int control_attach(struct ctdb_context *ctdb, int argc, const char **argv)
4714 {
4715         const char *db_name;
4716         struct ctdb_db_context *ctdb_db;
4717         bool persistent = false;
4718
4719         if (argc < 1) {
4720                 usage();
4721         }
4722         db_name = argv[0];
4723         if (argc > 2) {
4724                 usage();
4725         }
4726         if (argc == 2) {
4727                 if (strcmp(argv[1], "persistent") != 0) {
4728                         usage();
4729                 }
4730                 persistent = true;
4731         }
4732
4733         ctdb_db = ctdb_attach(ctdb, TIMELIMIT(), db_name, persistent, 0);
4734         if (ctdb_db == NULL) {
4735                 DEBUG(DEBUG_ERR,("Unable to attach to database '%s'\n", db_name));
4736                 return -1;
4737         }
4738
4739         return 0;
4740 }
4741
4742 /*
4743   set db priority
4744  */
4745 static int control_setdbprio(struct ctdb_context *ctdb, int argc, const char **argv)
4746 {
4747         struct ctdb_db_priority db_prio;
4748         int ret;
4749
4750         if (argc < 2) {
4751                 usage();
4752         }
4753
4754         db_prio.db_id    = strtoul(argv[0], NULL, 0);
4755         db_prio.priority = strtoul(argv[1], NULL, 0);
4756
4757         ret = ctdb_ctrl_set_db_priority(ctdb, TIMELIMIT(), options.pnn, &db_prio);
4758         if (ret != 0) {
4759                 DEBUG(DEBUG_ERR,("Unable to set db prio\n"));
4760                 return -1;
4761         }
4762
4763         return 0;
4764 }
4765
4766 /*
4767   get db priority
4768  */
4769 static int control_getdbprio(struct ctdb_context *ctdb, int argc, const char **argv)
4770 {
4771         uint32_t db_id, priority;
4772         int ret;
4773
4774         if (argc < 1) {
4775                 usage();
4776         }
4777
4778         if (!db_exists(ctdb, argv[0], &db_id, NULL)) {
4779                 return -1;
4780         }
4781
4782         ret = ctdb_ctrl_get_db_priority(ctdb, TIMELIMIT(), options.pnn, db_id, &priority);
4783         if (ret != 0) {
4784                 DEBUG(DEBUG_ERR,("Unable to get db prio\n"));
4785                 return -1;
4786         }
4787
4788         DEBUG(DEBUG_ERR,("Priority:%u\n", priority));
4789
4790         return 0;
4791 }
4792
4793 /*
4794   set the sticky records capability for a database
4795  */
4796 static int control_setdbsticky(struct ctdb_context *ctdb, int argc, const char **argv)
4797 {
4798         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
4799         uint32_t db_id;
4800         int ret;
4801
4802         if (argc < 1) {
4803                 usage();
4804         }
4805
4806         if (!db_exists(ctdb, argv[0], &db_id, NULL)) {
4807                 return -1;
4808         }
4809
4810         ret = ctdb_ctrl_set_db_sticky(ctdb, options.pnn, db_id);
4811         if (ret != 0) {
4812                 DEBUG(DEBUG_ERR,("Unable to set db to support sticky records\n"));
4813                 talloc_free(tmp_ctx);
4814                 return -1;
4815         }
4816
4817         talloc_free(tmp_ctx);
4818         return 0;
4819 }
4820
4821 /*
4822   set the readonly capability for a database
4823  */
4824 static int control_setdbreadonly(struct ctdb_context *ctdb, int argc, const char **argv)
4825 {
4826         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
4827         uint32_t db_id;
4828         int ret;
4829
4830         if (argc < 1) {
4831                 usage();
4832         }
4833
4834         if (!db_exists(ctdb, argv[0], &db_id, NULL)) {
4835                 return -1;
4836         }
4837
4838         ret = ctdb_ctrl_set_db_readonly(ctdb, options.pnn, db_id);
4839         if (ret != 0) {
4840                 DEBUG(DEBUG_ERR,("Unable to set db to support readonly\n"));
4841                 talloc_free(tmp_ctx);
4842                 return -1;
4843         }
4844
4845         talloc_free(tmp_ctx);
4846         return 0;
4847 }
4848
4849 /*
4850   get db seqnum
4851  */
4852 static int control_getdbseqnum(struct ctdb_context *ctdb, int argc, const char **argv)
4853 {
4854         bool ret;
4855         uint32_t db_id;
4856         uint64_t seqnum;
4857
4858         if (argc < 1) {
4859                 usage();
4860         }
4861
4862         if (!db_exists(ctdb, argv[0], &db_id, NULL)) {
4863                 return -1;
4864         }
4865
4866         ret = ctdb_getdbseqnum(ctdb_connection, options.pnn, db_id, &seqnum);
4867         if (!ret) {
4868                 DEBUG(DEBUG_ERR, ("Unable to get seqnum from node."));
4869                 return -1;
4870         }
4871
4872         printf("Sequence number:%lld\n", (long long)seqnum);
4873
4874         return 0;
4875 }
4876
4877 /*
4878  * set db seqnum
4879  */
4880 static int control_setdbseqnum(struct ctdb_context *ctdb, int argc, const char **argv)
4881 {
4882         bool ret;
4883         struct ctdb_db_context *ctdb_db;
4884         uint32_t db_id;
4885         uint8_t flags;
4886         uint64_t old_seqnum, new_seqnum;
4887         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
4888         struct ctdb_transaction_handle *h;
4889         TDB_DATA key, data;
4890         bool persistent;
4891
4892         if (argc != 2) {
4893                 talloc_free(tmp_ctx);
4894                 usage();
4895         }
4896
4897         if (!db_exists(ctdb, argv[0], &db_id, &flags)) {
4898                 talloc_free(tmp_ctx);
4899                 return -1;
4900         }
4901
4902         persistent = flags & CTDB_DB_FLAGS_PERSISTENT;
4903         if (!persistent) {
4904                 DEBUG(DEBUG_ERR,("Database '%s' is not persistent\n", argv[0]));
4905                 talloc_free(tmp_ctx);
4906                 return -1;
4907         }
4908
4909         ret = ctdb_getdbseqnum(ctdb_connection, options.pnn, db_id, &old_seqnum);
4910         if (!ret) {
4911                 DEBUG(DEBUG_ERR, ("Unable to get seqnum from node."));
4912                 talloc_free(tmp_ctx);
4913                 return -1;
4914         }
4915
4916         new_seqnum = strtoull(argv[1], NULL, 0);
4917         if (new_seqnum <= old_seqnum) {
4918                 DEBUG(DEBUG_ERR, ("New sequence number is less than current sequence number\n"));
4919                 talloc_free(tmp_ctx);
4920                 return -1;
4921         }
4922
4923         ctdb_db = ctdb_attach(ctdb, TIMELIMIT(), argv[0], persistent, 0);
4924         if (ctdb_db == NULL) {
4925                 DEBUG(DEBUG_ERR,("Unable to attach to database '%s'\n", argv[0]));
4926                 talloc_free(tmp_ctx);
4927                 return -1;
4928         }
4929
4930         h = ctdb_transaction_start(ctdb_db, tmp_ctx);
4931         if (h == NULL) {
4932                 DEBUG(DEBUG_ERR,("Failed to start transaction on database %s\n", argv[0]));
4933                 talloc_free(tmp_ctx);
4934                 return -1;
4935         }
4936
4937         key.dptr  = (uint8_t *)discard_const(CTDB_DB_SEQNUM_KEY);
4938         key.dsize = strlen(CTDB_DB_SEQNUM_KEY) + 1;
4939
4940         data.dsize = sizeof(new_seqnum);
4941         data.dptr = talloc_size(tmp_ctx, data.dsize);
4942         *data.dptr = new_seqnum;
4943
4944         ret = ctdb_transaction_store(h, key, data);
4945         if (ret != 0) {
4946                 DEBUG(DEBUG_ERR,("Failed to store record\n"));
4947                 talloc_free(tmp_ctx);
4948                 return -1;
4949         }
4950
4951         ret = ctdb_transaction_commit(h);
4952         if (ret != 0) {
4953                 DEBUG(DEBUG_ERR,("Failed to commit transaction\n"));
4954                 talloc_free(tmp_ctx);
4955                 return -1;
4956         }
4957
4958         talloc_free(tmp_ctx);
4959         return 0;
4960 }
4961
4962 /*
4963   run an eventscript on a node
4964  */
4965 static int control_eventscript(struct ctdb_context *ctdb, int argc, const char **argv)
4966 {
4967         TDB_DATA data;
4968         int ret;
4969         int32_t res;
4970         char *errmsg;
4971         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
4972
4973         if (argc != 1) {
4974                 DEBUG(DEBUG_ERR,("Invalid arguments\n"));
4975                 return -1;
4976         }
4977
4978         data.dptr = (unsigned char *)discard_const(argv[0]);
4979         data.dsize = strlen((char *)data.dptr) + 1;
4980
4981         DEBUG(DEBUG_ERR, ("Running eventscripts with arguments \"%s\" on node %u\n", data.dptr, options.pnn));
4982
4983         ret = ctdb_control(ctdb, options.pnn, 0, CTDB_CONTROL_RUN_EVENTSCRIPTS,
4984                            0, data, tmp_ctx, NULL, &res, NULL, &errmsg);
4985         if (ret != 0 || res != 0) {
4986                 DEBUG(DEBUG_ERR,("Failed to run eventscripts - %s\n", errmsg));
4987                 talloc_free(tmp_ctx);
4988                 return -1;
4989         }
4990         talloc_free(tmp_ctx);
4991         return 0;
4992 }
4993
4994 #define DB_VERSION 1
4995 #define MAX_DB_NAME 64
4996 struct db_file_header {
4997         unsigned long version;
4998         time_t timestamp;
4999         unsigned long persistent;
5000         unsigned long size;
5001         const char name[MAX_DB_NAME];
5002 };
5003
5004 struct backup_data {
5005         struct ctdb_marshall_buffer *records;
5006         uint32_t len;
5007         uint32_t total;
5008         bool traverse_error;
5009 };
5010
5011 static int backup_traverse(struct tdb_context *tdb, TDB_DATA key, TDB_DATA data, void *private)
5012 {
5013         struct backup_data *bd = talloc_get_type(private, struct backup_data);
5014         struct ctdb_rec_data *rec;
5015
5016         /* add the record */
5017         rec = ctdb_marshall_record(bd->records, 0, key, NULL, data);
5018         if (rec == NULL) {
5019                 bd->traverse_error = true;
5020                 DEBUG(DEBUG_ERR,("Failed to marshall record\n"));
5021                 return -1;
5022         }
5023         bd->records = talloc_realloc_size(NULL, bd->records, rec->length + bd->len);
5024         if (bd->records == NULL) {
5025                 DEBUG(DEBUG_ERR,("Failed to expand marshalling buffer\n"));
5026                 bd->traverse_error = true;
5027                 return -1;
5028         }
5029         bd->records->count++;
5030         memcpy(bd->len+(uint8_t *)bd->records, rec, rec->length);
5031         bd->len += rec->length;
5032         talloc_free(rec);
5033
5034         bd->total++;
5035         return 0;
5036 }
5037
5038 /*
5039  * backup a database to a file 
5040  */
5041 static int control_backupdb(struct ctdb_context *ctdb, int argc, const char **argv)
5042 {
5043         int ret;
5044         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
5045         struct db_file_header dbhdr;
5046         struct ctdb_db_context *ctdb_db;
5047         struct backup_data *bd;
5048         int fh = -1;
5049         int status = -1;
5050         const char *reason = NULL;
5051         uint32_t db_id;
5052         uint8_t flags;
5053
5054         if (argc != 2) {
5055                 DEBUG(DEBUG_ERR,("Invalid arguments\n"));
5056                 return -1;
5057         }
5058
5059         if (!db_exists(ctdb, argv[0], &db_id, &flags)) {
5060                 return -1;
5061         }
5062
5063         ret = ctdb_ctrl_getdbhealth(ctdb, TIMELIMIT(), options.pnn,
5064                                     db_id, tmp_ctx, &reason);
5065         if (ret != 0) {
5066                 DEBUG(DEBUG_ERR,("Unable to get dbhealth for database '%s'\n",
5067                                  argv[0]));
5068                 talloc_free(tmp_ctx);
5069                 return -1;
5070         }
5071         if (reason) {
5072                 uint32_t allow_unhealthy = 0;
5073
5074                 ctdb_ctrl_get_tunable(ctdb, TIMELIMIT(), options.pnn,
5075                                       "AllowUnhealthyDBRead",
5076                                       &allow_unhealthy);
5077
5078                 if (allow_unhealthy != 1) {
5079                         DEBUG(DEBUG_ERR,("database '%s' is unhealthy: %s\n",
5080                                          argv[0], reason));
5081
5082                         DEBUG(DEBUG_ERR,("disallow backup : tunable AllowUnhealthyDBRead = %u\n",
5083                                          allow_unhealthy));
5084                         talloc_free(tmp_ctx);
5085                         return -1;
5086                 }
5087
5088                 DEBUG(DEBUG_WARNING,("WARNING database '%s' is unhealthy - see 'ctdb getdbstatus %s'\n",
5089                                      argv[0], argv[0]));
5090                 DEBUG(DEBUG_WARNING,("WARNING! allow backup of unhealthy database: "
5091                                      "tunnable AllowUnhealthyDBRead = %u\n",
5092                                      allow_unhealthy));
5093         }
5094
5095         ctdb_db = ctdb_attach(ctdb, TIMELIMIT(), argv[0], flags & CTDB_DB_FLAGS_PERSISTENT, 0);
5096         if (ctdb_db == NULL) {
5097                 DEBUG(DEBUG_ERR,("Unable to attach to database '%s'\n", argv[0]));
5098                 talloc_free(tmp_ctx);
5099                 return -1;
5100         }
5101
5102
5103         ret = tdb_transaction_start(ctdb_db->ltdb->tdb);
5104         if (ret == -1) {
5105                 DEBUG(DEBUG_ERR,("Failed to start transaction\n"));
5106                 talloc_free(tmp_ctx);
5107                 return -1;
5108         }
5109
5110
5111         bd = talloc_zero(tmp_ctx, struct backup_data);
5112         if (bd == NULL) {
5113                 DEBUG(DEBUG_ERR,("Failed to allocate backup_data\n"));
5114                 talloc_free(tmp_ctx);
5115                 return -1;
5116         }
5117
5118         bd->records = talloc_zero(bd, struct ctdb_marshall_buffer);
5119         if (bd->records == NULL) {
5120                 DEBUG(DEBUG_ERR,("Failed to allocate ctdb_marshall_buffer\n"));
5121                 talloc_free(tmp_ctx);
5122                 return -1;
5123         }
5124
5125         bd->len = offsetof(struct ctdb_marshall_buffer, data);
5126         bd->records->db_id = ctdb_db->db_id;
5127         /* traverse the database collecting all records */
5128         if (tdb_traverse_read(ctdb_db->ltdb->tdb, backup_traverse, bd) == -1 ||
5129             bd->traverse_error) {
5130                 DEBUG(DEBUG_ERR,("Traverse error\n"));
5131                 talloc_free(tmp_ctx);
5132                 return -1;              
5133         }
5134
5135         tdb_transaction_cancel(ctdb_db->ltdb->tdb);
5136
5137
5138         fh = open(argv[1], O_RDWR|O_CREAT, 0600);
5139         if (fh == -1) {
5140                 DEBUG(DEBUG_ERR,("Failed to open file '%s'\n", argv[1]));
5141                 talloc_free(tmp_ctx);
5142                 return -1;
5143         }
5144
5145         dbhdr.version = DB_VERSION;
5146         dbhdr.timestamp = time(NULL);
5147         dbhdr.persistent = flags & CTDB_DB_FLAGS_PERSISTENT;
5148         dbhdr.size = bd->len;
5149         if (strlen(argv[0]) >= MAX_DB_NAME) {
5150                 DEBUG(DEBUG_ERR,("Too long dbname\n"));
5151                 goto done;
5152         }
5153         strncpy(discard_const(dbhdr.name), argv[0], MAX_DB_NAME);
5154         ret = write(fh, &dbhdr, sizeof(dbhdr));
5155         if (ret == -1) {
5156                 DEBUG(DEBUG_ERR,("write failed: %s\n", strerror(errno)));
5157                 goto done;
5158         }
5159         ret = write(fh, bd->records, bd->len);
5160         if (ret == -1) {
5161                 DEBUG(DEBUG_ERR,("write failed: %s\n", strerror(errno)));
5162                 goto done;
5163         }
5164
5165         status = 0;
5166 done:
5167         if (fh != -1) {
5168                 ret = close(fh);
5169                 if (ret == -1) {
5170                         DEBUG(DEBUG_ERR,("close failed: %s\n", strerror(errno)));
5171                 }
5172         }
5173
5174         DEBUG(DEBUG_ERR,("Database backed up to %s\n", argv[1]));
5175
5176         talloc_free(tmp_ctx);
5177         return status;
5178 }
5179
5180 /*
5181  * restore a database from a file 
5182  */
5183 static int control_restoredb(struct ctdb_context *ctdb, int argc, const char **argv)
5184 {
5185         int ret;
5186         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
5187         TDB_DATA outdata;
5188         TDB_DATA data;
5189         struct db_file_header dbhdr;
5190         struct ctdb_db_context *ctdb_db;
5191         struct ctdb_node_map *nodemap=NULL;
5192         struct ctdb_vnn_map *vnnmap=NULL;
5193         int i, fh;
5194         struct ctdb_control_wipe_database w;
5195         uint32_t *nodes;
5196         uint32_t generation;
5197         struct tm *tm;
5198         char tbuf[100];
5199         char *dbname;
5200
5201         if (argc < 1 || argc > 2) {
5202                 DEBUG(DEBUG_ERR,("Invalid arguments\n"));
5203                 return -1;
5204         }
5205
5206         fh = open(argv[0], O_RDONLY);
5207         if (fh == -1) {
5208                 DEBUG(DEBUG_ERR,("Failed to open file '%s'\n", argv[0]));
5209                 talloc_free(tmp_ctx);
5210                 return -1;
5211         }
5212
5213         read(fh, &dbhdr, sizeof(dbhdr));
5214         if (dbhdr.version != DB_VERSION) {
5215                 DEBUG(DEBUG_ERR,("Invalid version of database dump. File is version %lu but expected version was %u\n", dbhdr.version, DB_VERSION));
5216                 talloc_free(tmp_ctx);
5217                 return -1;
5218         }
5219
5220         dbname = discard_const(dbhdr.name);
5221         if (argc == 2) {
5222                 dbname = discard_const(argv[1]);
5223         }
5224
5225         outdata.dsize = dbhdr.size;
5226         outdata.dptr = talloc_size(tmp_ctx, outdata.dsize);
5227         if (outdata.dptr == NULL) {
5228                 DEBUG(DEBUG_ERR,("Failed to allocate data of size '%lu'\n", dbhdr.size));
5229                 close(fh);
5230                 talloc_free(tmp_ctx);
5231                 return -1;
5232         }               
5233         read(fh, outdata.dptr, outdata.dsize);
5234         close(fh);
5235
5236         tm = localtime(&dbhdr.timestamp);
5237         strftime(tbuf,sizeof(tbuf)-1,"%Y/%m/%d %H:%M:%S", tm);
5238         printf("Restoring database '%s' from backup @ %s\n",
5239                 dbname, tbuf);
5240
5241
5242         ctdb_db = ctdb_attach(ctdb, TIMELIMIT(), dbname, dbhdr.persistent, 0);
5243         if (ctdb_db == NULL) {
5244                 DEBUG(DEBUG_ERR,("Unable to attach to database '%s'\n", dbname));
5245                 talloc_free(tmp_ctx);
5246                 return -1;
5247         }
5248
5249         ret = ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), options.pnn, ctdb, &nodemap);
5250         if (ret != 0) {
5251                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from node %u\n", options.pnn));
5252                 talloc_free(tmp_ctx);
5253                 return ret;
5254         }
5255
5256
5257         ret = ctdb_ctrl_getvnnmap(ctdb, TIMELIMIT(), options.pnn, tmp_ctx, &vnnmap);
5258         if (ret != 0) {
5259                 DEBUG(DEBUG_ERR, ("Unable to get vnnmap from node %u\n", options.pnn));
5260                 talloc_free(tmp_ctx);
5261                 return ret;
5262         }
5263
5264         /* freeze all nodes */
5265         nodes = list_of_active_nodes(ctdb, nodemap, tmp_ctx, true);
5266         for (i=1; i<=NUM_DB_PRIORITIES; i++) {
5267                 if (ctdb_client_async_control(ctdb, CTDB_CONTROL_FREEZE,
5268                                         nodes, i,
5269                                         TIMELIMIT(),
5270                                         false, tdb_null,
5271                                         NULL, NULL,
5272                                         NULL) != 0) {
5273                         DEBUG(DEBUG_ERR, ("Unable to freeze nodes.\n"));
5274                         ctdb_ctrl_setrecmode(ctdb, TIMELIMIT(), options.pnn, CTDB_RECOVERY_ACTIVE);
5275                         talloc_free(tmp_ctx);
5276                         return -1;
5277                 }
5278         }
5279
5280         generation = vnnmap->generation;
5281         data.dptr = (void *)&generation;
5282         data.dsize = sizeof(generation);
5283
5284         /* start a cluster wide transaction */
5285         nodes = list_of_active_nodes(ctdb, nodemap, tmp_ctx, true);
5286         if (ctdb_client_async_control(ctdb, CTDB_CONTROL_TRANSACTION_START,
5287                                         nodes, 0,
5288                                         TIMELIMIT(), false, data,
5289                                         NULL, NULL,
5290                                         NULL) != 0) {
5291                 DEBUG(DEBUG_ERR, ("Unable to start cluster wide transactions.\n"));
5292                 return -1;
5293         }
5294
5295
5296         w.db_id = ctdb_db->db_id;
5297         w.transaction_id = generation;
5298
5299         data.dptr = (void *)&w;
5300         data.dsize = sizeof(w);
5301
5302         /* wipe all the remote databases. */
5303         nodes = list_of_active_nodes(ctdb, nodemap, tmp_ctx, true);
5304         if (ctdb_client_async_control(ctdb, CTDB_CONTROL_WIPE_DATABASE,
5305                                         nodes, 0,
5306                                         TIMELIMIT(), false, data,
5307                                         NULL, NULL,
5308                                         NULL) != 0) {
5309                 DEBUG(DEBUG_ERR, ("Unable to wipe database.\n"));
5310                 ctdb_ctrl_setrecmode(ctdb, TIMELIMIT(), options.pnn, CTDB_RECOVERY_ACTIVE);
5311                 talloc_free(tmp_ctx);
5312                 return -1;
5313         }
5314         
5315         /* push the database */
5316         nodes = list_of_active_nodes(ctdb, nodemap, tmp_ctx, true);
5317         if (ctdb_client_async_control(ctdb, CTDB_CONTROL_PUSH_DB,
5318                                         nodes, 0,
5319                                         TIMELIMIT(), false, outdata,
5320                                         NULL, NULL,
5321                                         NULL) != 0) {
5322                 DEBUG(DEBUG_ERR, ("Failed to push database.\n"));
5323                 ctdb_ctrl_setrecmode(ctdb, TIMELIMIT(), options.pnn, CTDB_RECOVERY_ACTIVE);
5324                 talloc_free(tmp_ctx);
5325                 return -1;
5326         }
5327
5328         data.dptr = (void *)&ctdb_db->db_id;
5329         data.dsize = sizeof(ctdb_db->db_id);
5330
5331         /* mark the database as healthy */
5332         nodes = list_of_active_nodes(ctdb, nodemap, tmp_ctx, true);
5333         if (ctdb_client_async_control(ctdb, CTDB_CONTROL_DB_SET_HEALTHY,
5334                                         nodes, 0,
5335                                         TIMELIMIT(), false, data,
5336                                         NULL, NULL,
5337                                         NULL) != 0) {
5338                 DEBUG(DEBUG_ERR, ("Failed to mark database as healthy.\n"));
5339                 ctdb_ctrl_setrecmode(ctdb, TIMELIMIT(), options.pnn, CTDB_RECOVERY_ACTIVE);
5340                 talloc_free(tmp_ctx);
5341                 return -1;
5342         }
5343
5344         data.dptr = (void *)&generation;
5345         data.dsize = sizeof(generation);
5346
5347         /* commit all the changes */
5348         if (ctdb_client_async_control(ctdb, CTDB_CONTROL_TRANSACTION_COMMIT,
5349                                         nodes, 0,
5350                                         TIMELIMIT(), false, data,
5351                                         NULL, NULL,
5352                                         NULL) != 0) {
5353                 DEBUG(DEBUG_ERR, ("Unable to commit databases.\n"));
5354                 ctdb_ctrl_setrecmode(ctdb, TIMELIMIT(), options.pnn, CTDB_RECOVERY_ACTIVE);
5355                 talloc_free(tmp_ctx);
5356                 return -1;
5357         }
5358
5359
5360         /* thaw all nodes */
5361         nodes = list_of_active_nodes(ctdb, nodemap, tmp_ctx, true);
5362         if (ctdb_client_async_control(ctdb, CTDB_CONTROL_THAW,
5363                                         nodes, 0,
5364                                         TIMELIMIT(),
5365                                         false, tdb_null,
5366                                         NULL, NULL,
5367                                         NULL) != 0) {
5368                 DEBUG(DEBUG_ERR, ("Unable to thaw nodes.\n"));
5369                 ctdb_ctrl_setrecmode(ctdb, TIMELIMIT(), options.pnn, CTDB_RECOVERY_ACTIVE);
5370                 talloc_free(tmp_ctx);
5371                 return -1;
5372         }
5373
5374
5375         talloc_free(tmp_ctx);
5376         return 0;
5377 }
5378
5379 /*
5380  * dump a database backup from a file
5381  */
5382 static int control_dumpdbbackup(struct ctdb_context *ctdb, int argc, const char **argv)
5383 {
5384         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
5385         TDB_DATA outdata;
5386         struct db_file_header dbhdr;
5387         int i, fh;
5388         struct tm *tm;
5389         char tbuf[100];
5390         struct ctdb_rec_data *rec = NULL;
5391         struct ctdb_marshall_buffer *m;
5392         struct ctdb_dump_db_context c;
5393
5394         if (argc != 1) {
5395                 DEBUG(DEBUG_ERR,("Invalid arguments\n"));
5396                 return -1;
5397         }
5398
5399         fh = open(argv[0], O_RDONLY);
5400         if (fh == -1) {
5401                 DEBUG(DEBUG_ERR,("Failed to open file '%s'\n", argv[0]));
5402                 talloc_free(tmp_ctx);
5403                 return -1;
5404         }
5405
5406         read(fh, &dbhdr, sizeof(dbhdr));
5407         if (dbhdr.version != DB_VERSION) {
5408                 DEBUG(DEBUG_ERR,("Invalid version of database dump. File is version %lu but expected version was %u\n", dbhdr.version, DB_VERSION));
5409                 talloc_free(tmp_ctx);
5410                 return -1;
5411         }
5412
5413         outdata.dsize = dbhdr.size;
5414         outdata.dptr = talloc_size(tmp_ctx, outdata.dsize);
5415         if (outdata.dptr == NULL) {
5416                 DEBUG(DEBUG_ERR,("Failed to allocate data of size '%lu'\n", dbhdr.size));
5417                 close(fh);
5418                 talloc_free(tmp_ctx);
5419                 return -1;
5420         }
5421         read(fh, outdata.dptr, outdata.dsize);
5422         close(fh);
5423         m = (struct ctdb_marshall_buffer *)outdata.dptr;
5424
5425         tm = localtime(&dbhdr.timestamp);
5426         strftime(tbuf,sizeof(tbuf)-1,"%Y/%m/%d %H:%M:%S", tm);
5427         printf("Backup of database name:'%s' dbid:0x%x08x from @ %s\n",
5428                 dbhdr.name, m->db_id, tbuf);
5429
5430         ZERO_STRUCT(c);
5431         c.f = stdout;
5432         c.printemptyrecords = (bool)options.printemptyrecords;
5433         c.printdatasize = (bool)options.printdatasize;
5434         c.printlmaster = false;
5435         c.printhash = (bool)options.printhash;
5436         c.printrecordflags = (bool)options.printrecordflags;
5437
5438         for (i=0; i < m->count; i++) {
5439                 uint32_t reqid = 0;
5440                 TDB_DATA key, data;
5441
5442                 /* we do not want the header splitted, so we pass NULL*/
5443                 rec = ctdb_marshall_loop_next(m, rec, &reqid,
5444                                               NULL, &key, &data);
5445
5446                 ctdb_dumpdb_record(ctdb, key, data, &c);
5447         }
5448
5449         printf("Dumped %d records\n", i);
5450         talloc_free(tmp_ctx);
5451         return 0;
5452 }
5453
5454 /*
5455  * wipe a database from a file
5456  */
5457 static int control_wipedb(struct ctdb_context *ctdb, int argc,
5458                           const char **argv)
5459 {
5460         int ret;
5461         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
5462         TDB_DATA data;
5463         struct ctdb_db_context *ctdb_db;
5464         struct ctdb_node_map *nodemap = NULL;
5465         struct ctdb_vnn_map *vnnmap = NULL;
5466         int i;
5467         struct ctdb_control_wipe_database w;
5468         uint32_t *nodes;
5469         uint32_t generation;
5470         uint8_t flags;
5471
5472         if (argc != 1) {
5473                 DEBUG(DEBUG_ERR,("Invalid arguments\n"));
5474                 return -1;
5475         }
5476
5477         if (!db_exists(ctdb, argv[0], NULL, &flags)) {
5478                 return -1;
5479         }
5480
5481         ctdb_db = ctdb_attach(ctdb, TIMELIMIT(), argv[0], flags & CTDB_DB_FLAGS_PERSISTENT, 0);
5482         if (ctdb_db == NULL) {
5483                 DEBUG(DEBUG_ERR, ("Unable to attach to database '%s'\n",
5484                                   argv[0]));
5485                 talloc_free(tmp_ctx);
5486                 return -1;
5487         }
5488
5489         ret = ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), options.pnn, ctdb,
5490                                    &nodemap);
5491         if (ret != 0) {
5492                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from node %u\n",
5493                                   options.pnn));
5494                 talloc_free(tmp_ctx);
5495                 return ret;
5496         }
5497
5498         ret = ctdb_ctrl_getvnnmap(ctdb, TIMELIMIT(), options.pnn, tmp_ctx,
5499                                   &vnnmap);
5500         if (ret != 0) {
5501                 DEBUG(DEBUG_ERR, ("Unable to get vnnmap from node %u\n",
5502                                   options.pnn));
5503                 talloc_free(tmp_ctx);
5504                 return ret;
5505         }
5506
5507         /* freeze all nodes */
5508         nodes = list_of_active_nodes(ctdb, nodemap, tmp_ctx, true);
5509         for (i=1; i<=NUM_DB_PRIORITIES; i++) {
5510                 ret = ctdb_client_async_control(ctdb, CTDB_CONTROL_FREEZE,
5511                                                 nodes, i,
5512                                                 TIMELIMIT(),
5513                                                 false, tdb_null,
5514                                                 NULL, NULL,
5515                                                 NULL);
5516                 if (ret != 0) {
5517                         DEBUG(DEBUG_ERR, ("Unable to freeze nodes.\n"));
5518                         ctdb_ctrl_setrecmode(ctdb, TIMELIMIT(), options.pnn,
5519                                              CTDB_RECOVERY_ACTIVE);
5520                         talloc_free(tmp_ctx);
5521                         return -1;
5522                 }
5523         }
5524
5525         generation = vnnmap->generation;
5526         data.dptr = (void *)&generation;
5527         data.dsize = sizeof(generation);
5528
5529         /* start a cluster wide transaction */
5530         nodes = list_of_active_nodes(ctdb, nodemap, tmp_ctx, true);
5531         ret = ctdb_client_async_control(ctdb, CTDB_CONTROL_TRANSACTION_START,
5532                                         nodes, 0,
5533                                         TIMELIMIT(), false, data,
5534                                         NULL, NULL,
5535                                         NULL);
5536         if (ret!= 0) {
5537                 DEBUG(DEBUG_ERR, ("Unable to start cluster wide "
5538                                   "transactions.\n"));
5539                 return -1;
5540         }
5541
5542         w.db_id = ctdb_db->db_id;
5543         w.transaction_id = generation;
5544
5545         data.dptr = (void *)&w;
5546         data.dsize = sizeof(w);
5547
5548         /* wipe all the remote databases. */
5549         nodes = list_of_active_nodes(ctdb, nodemap, tmp_ctx, true);
5550         if (ctdb_client_async_control(ctdb, CTDB_CONTROL_WIPE_DATABASE,
5551                                         nodes, 0,
5552                                         TIMELIMIT(), false, data,
5553                                         NULL, NULL,
5554                                         NULL) != 0) {
5555                 DEBUG(DEBUG_ERR, ("Unable to wipe database.\n"));
5556                 ctdb_ctrl_setrecmode(ctdb, TIMELIMIT(), options.pnn, CTDB_RECOVERY_ACTIVE);
5557                 talloc_free(tmp_ctx);
5558                 return -1;
5559         }
5560
5561         data.dptr = (void *)&ctdb_db->db_id;
5562         data.dsize = sizeof(ctdb_db->db_id);
5563
5564         /* mark the database as healthy */
5565         nodes = list_of_active_nodes(ctdb, nodemap, tmp_ctx, true);
5566         if (ctdb_client_async_control(ctdb, CTDB_CONTROL_DB_SET_HEALTHY,
5567                                         nodes, 0,
5568                                         TIMELIMIT(), false, data,
5569                                         NULL, NULL,
5570                                         NULL) != 0) {
5571                 DEBUG(DEBUG_ERR, ("Failed to mark database as healthy.\n"));
5572                 ctdb_ctrl_setrecmode(ctdb, TIMELIMIT(), options.pnn, CTDB_RECOVERY_ACTIVE);
5573                 talloc_free(tmp_ctx);
5574                 return -1;
5575         }
5576
5577         data.dptr = (void *)&generation;
5578         data.dsize = sizeof(generation);
5579
5580         /* commit all the changes */
5581         if (ctdb_client_async_control(ctdb, CTDB_CONTROL_TRANSACTION_COMMIT,
5582                                         nodes, 0,
5583                                         TIMELIMIT(), false, data,
5584                                         NULL, NULL,
5585                                         NULL) != 0) {
5586                 DEBUG(DEBUG_ERR, ("Unable to commit databases.\n"));
5587                 ctdb_ctrl_setrecmode(ctdb, TIMELIMIT(), options.pnn, CTDB_RECOVERY_ACTIVE);
5588                 talloc_free(tmp_ctx);
5589                 return -1;
5590         }
5591
5592         /* thaw all nodes */
5593         nodes = list_of_active_nodes(ctdb, nodemap, tmp_ctx, true);
5594         if (ctdb_client_async_control(ctdb, CTDB_CONTROL_THAW,
5595                                         nodes, 0,
5596                                         TIMELIMIT(),
5597                                         false, tdb_null,
5598                                         NULL, NULL,
5599                                         NULL) != 0) {
5600                 DEBUG(DEBUG_ERR, ("Unable to thaw nodes.\n"));
5601                 ctdb_ctrl_setrecmode(ctdb, TIMELIMIT(), options.pnn, CTDB_RECOVERY_ACTIVE);
5602                 talloc_free(tmp_ctx);
5603                 return -1;
5604         }
5605
5606         DEBUG(DEBUG_ERR, ("Database wiped.\n"));
5607
5608         talloc_free(tmp_ctx);
5609         return 0;
5610 }
5611
5612 /*
5613   dump memory usage
5614  */
5615 static int control_dumpmemory(struct ctdb_context *ctdb, int argc, const char **argv)
5616 {
5617         TDB_DATA data;
5618         int ret;
5619         int32_t res;
5620         char *errmsg;
5621         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
5622         ret = ctdb_control(ctdb, options.pnn, 0, CTDB_CONTROL_DUMP_MEMORY,
5623                            0, tdb_null, tmp_ctx, &data, &res, NULL, &errmsg);
5624         if (ret != 0 || res != 0) {
5625                 DEBUG(DEBUG_ERR,("Failed to dump memory - %s\n", errmsg));
5626                 talloc_free(tmp_ctx);
5627                 return -1;
5628         }
5629         write(1, data.dptr, data.dsize);
5630         talloc_free(tmp_ctx);
5631         return 0;
5632 }
5633
5634 /*
5635   handler for memory dumps
5636 */
5637 static void mem_dump_handler(struct ctdb_context *ctdb, uint64_t srvid, 
5638                              TDB_DATA data, void *private_data)
5639 {
5640         write(1, data.dptr, data.dsize);
5641         exit(0);
5642 }
5643
5644 /*
5645   dump memory usage on the recovery daemon
5646  */
5647 static int control_rddumpmemory(struct ctdb_context *ctdb, int argc, const char **argv)
5648 {
5649         int ret;
5650         TDB_DATA data;
5651         struct rd_memdump_reply rd;
5652
5653         rd.pnn = ctdb_ctrl_getpnn(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE);
5654         if (rd.pnn == -1) {
5655                 DEBUG(DEBUG_ERR, ("Failed to get pnn of local node\n"));
5656                 return -1;
5657         }
5658         rd.srvid = getpid();
5659
5660         /* register a message port for receiveing the reply so that we
5661            can receive the reply
5662         */
5663         ctdb_client_set_message_handler(ctdb, rd.srvid, mem_dump_handler, NULL);
5664
5665
5666         data.dptr = (uint8_t *)&rd;
5667         data.dsize = sizeof(rd);
5668
5669         ret = ctdb_client_send_message(ctdb, options.pnn, CTDB_SRVID_MEM_DUMP, data);
5670         if (ret != 0) {
5671                 DEBUG(DEBUG_ERR,("Failed to send memdump request message to %u\n", options.pnn));
5672                 return -1;
5673         }
5674
5675         /* this loop will terminate when we have received the reply */
5676         while (1) {     
5677                 event_loop_once(ctdb->ev);
5678         }
5679
5680         return 0;
5681 }
5682
5683 /*
5684   send a message to a srvid
5685  */
5686 static int control_msgsend(struct ctdb_context *ctdb, int argc, const char **argv)
5687 {
5688         unsigned long srvid;
5689         int ret;
5690         TDB_DATA data;
5691
5692         if (argc < 2) {
5693                 usage();
5694         }
5695
5696         srvid      = strtoul(argv[0], NULL, 0);
5697
5698         data.dptr = (uint8_t *)discard_const(argv[1]);
5699         data.dsize= strlen(argv[1]);
5700
5701         ret = ctdb_client_send_message(ctdb, CTDB_BROADCAST_CONNECTED, srvid, data);
5702         if (ret != 0) {
5703                 DEBUG(DEBUG_ERR,("Failed to send memdump request message to %u\n", options.pnn));
5704                 return -1;
5705         }
5706
5707         return 0;
5708 }
5709
5710 /*
5711   handler for msglisten
5712 */
5713 static void msglisten_handler(struct ctdb_context *ctdb, uint64_t srvid, 
5714                              TDB_DATA data, void *private_data)
5715 {
5716         int i;
5717
5718         printf("Message received: ");
5719         for (i=0;i<data.dsize;i++) {
5720                 printf("%c", data.dptr[i]);
5721         }
5722         printf("\n");
5723 }
5724
5725 /*
5726   listen for messages on a messageport
5727  */
5728 static int control_msglisten(struct ctdb_context *ctdb, int argc, const char **argv)
5729 {
5730         uint64_t srvid;
5731
5732         srvid = getpid();
5733
5734         /* register a message port and listen for messages
5735         */
5736         ctdb_client_set_message_handler(ctdb, srvid, msglisten_handler, NULL);
5737         printf("Listening for messages on srvid:%d\n", (int)srvid);
5738
5739         while (1) {     
5740                 event_loop_once(ctdb->ev);
5741         }
5742
5743         return 0;
5744 }
5745
5746 /*
5747   list all nodes in the cluster
5748   we parse the nodes file directly
5749  */
5750 static int control_listnodes(struct ctdb_context *ctdb, int argc, const char **argv)
5751 {
5752         TALLOC_CTX *mem_ctx = talloc_new(NULL);
5753         struct pnn_node *pnn_nodes;
5754         struct pnn_node *pnn_node;
5755
5756         pnn_nodes = read_nodes_file(mem_ctx);
5757         if (pnn_nodes == NULL) {
5758                 DEBUG(DEBUG_ERR,("Failed to read nodes file\n"));
5759                 talloc_free(mem_ctx);
5760                 return -1;
5761         }
5762
5763         for(pnn_node=pnn_nodes;pnn_node;pnn_node=pnn_node->next) {
5764                 ctdb_sock_addr addr;
5765                 if (parse_ip(pnn_node->addr, NULL, 63999, &addr) == 0) {
5766                         DEBUG(DEBUG_ERR,("Wrongly formed ip address '%s' in nodes file\n", pnn_node->addr));
5767                         talloc_free(mem_ctx);
5768                         return -1;
5769                 }
5770                 if (options.machinereadable){
5771                         printf(":%d:%s:\n", pnn_node->pnn, pnn_node->addr);
5772                 } else {
5773                         printf("%s\n", pnn_node->addr);
5774                 }
5775         }
5776         talloc_free(mem_ctx);
5777
5778         return 0;
5779 }
5780
5781 /*
5782   reload the nodes file on the local node
5783  */
5784 static int control_reload_nodes_file(struct ctdb_context *ctdb, int argc, const char **argv)
5785 {
5786         int i, ret;
5787         int mypnn;
5788         struct ctdb_node_map *nodemap=NULL;
5789
5790         mypnn = ctdb_ctrl_getpnn(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE);
5791         if (mypnn == -1) {
5792                 DEBUG(DEBUG_ERR, ("Failed to read pnn of local node\n"));
5793                 return -1;
5794         }
5795
5796         ret = ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE, ctdb, &nodemap);
5797         if (ret != 0) {
5798                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from local node\n"));
5799                 return ret;
5800         }
5801
5802         /* reload the nodes file on all remote nodes */
5803         for (i=0;i<nodemap->num;i++) {
5804                 if (nodemap->nodes[i].pnn == mypnn) {
5805                         continue;
5806                 }
5807                 DEBUG(DEBUG_NOTICE, ("Reloading nodes file on node %u\n", nodemap->nodes[i].pnn));
5808                 ret = ctdb_ctrl_reload_nodes_file(ctdb, TIMELIMIT(),
5809                         nodemap->nodes[i].pnn);
5810                 if (ret != 0) {
5811                         DEBUG(DEBUG_ERR, ("ERROR: Failed to reload nodes file on node %u. You MUST fix that node manually!\n", nodemap->nodes[i].pnn));
5812                 }
5813         }
5814
5815         /* reload the nodes file on the local node */
5816         DEBUG(DEBUG_NOTICE, ("Reloading nodes file on node %u\n", mypnn));
5817         ret = ctdb_ctrl_reload_nodes_file(ctdb, TIMELIMIT(), mypnn);
5818         if (ret != 0) {
5819                 DEBUG(DEBUG_ERR, ("ERROR: Failed to reload nodes file on node %u. You MUST fix that node manually!\n", mypnn));
5820         }
5821
5822         /* initiate a recovery */
5823         control_recover(ctdb, argc, argv);
5824
5825         return 0;
5826 }
5827
5828
5829 static const struct {
5830         const char *name;
5831         int (*fn)(struct ctdb_context *, int, const char **);
5832         bool auto_all;
5833         bool without_daemon; /* can be run without daemon running ? */
5834         const char *msg;
5835         const char *args;
5836 } ctdb_commands[] = {
5837         { "version",         control_version,           true,   true,   "show version of ctdb" },
5838         { "status",          control_status,            true,   false,  "show node status" },
5839         { "uptime",          control_uptime,            true,   false,  "show node uptime" },
5840         { "ping",            control_ping,              true,   false,  "ping all nodes" },
5841         { "getvar",          control_getvar,            true,   false,  "get a tunable variable",               "<name>"},
5842         { "setvar",          control_setvar,            true,   false,  "set a tunable variable",               "<name> <value>"},
5843         { "listvars",        control_listvars,          true,   false,  "list tunable variables"},
5844         { "statistics",      control_statistics,        false,  false, "show statistics" },
5845         { "statisticsreset", control_statistics_reset,  true,   false,  "reset statistics"},
5846         { "stats",           control_stats,             false,  false,  "show rolling statistics", "[number of history records]" },
5847         { "ip",              control_ip,                false,  false,  "show which public ip's that ctdb manages" },
5848         { "ipinfo",          control_ipinfo,            true,   false,  "show details about a public ip that ctdb manages", "<ip>" },
5849         { "ifaces",          control_ifaces,            true,   false,  "show which interfaces that ctdb manages" },
5850         { "setifacelink",    control_setifacelink,      true,   false,  "set interface link status", "<iface> <status>" },
5851         { "process-exists",  control_process_exists,    true,   false,  "check if a process exists on a node",  "<pid>"},
5852         { "getdbmap",        control_getdbmap,          true,   false,  "show the database map" },
5853         { "getdbstatus",     control_getdbstatus,       true,   false,  "show the status of a database", "<dbname|dbid>" },
5854         { "catdb",           control_catdb,             true,   false,  "dump a ctdb database" ,                     "<dbname|dbid>"},
5855         { "cattdb",          control_cattdb,            true,   false,  "dump a local tdb database" ,                     "<dbname|dbid>"},
5856         { "getmonmode",      control_getmonmode,        true,   false,  "show monitoring mode" },
5857         { "getcapabilities", control_getcapabilities,   true,   false,  "show node capabilities" },
5858         { "pnn",             control_pnn,               true,   false,  "show the pnn of the currnet node" },
5859         { "lvs",             control_lvs,               true,   false,  "show lvs configuration" },
5860         { "lvsmaster",       control_lvsmaster,         true,   false,  "show which node is the lvs master" },
5861         { "disablemonitor",      control_disable_monmode,true,  false,  "set monitoring mode to DISABLE" },
5862         { "enablemonitor",      control_enable_monmode, true,   false,  "set monitoring mode to ACTIVE" },
5863         { "setdebug",        control_setdebug,          true,   false,  "set debug level",                      "<EMERG|ALERT|CRIT|ERR|WARNING|NOTICE|INFO|DEBUG>" },
5864         { "getdebug",        control_getdebug,          true,   false,  "get debug level" },
5865         { "getlog",          control_getlog,            true,   false,  "get the log data from the in memory ringbuffer", "[<level>] [recoverd]" },
5866         { "clearlog",          control_clearlog,        true,   false,  "clear the log data from the in memory ringbuffer", "[recoverd]" },
5867         { "attach",          control_attach,            true,   false,  "attach to a database",                 "<dbname> [persistent]" },
5868         { "dumpmemory",      control_dumpmemory,        true,   false,  "dump memory map to stdout" },
5869         { "rddumpmemory",    control_rddumpmemory,      true,   false,  "dump memory map from the recovery daemon to stdout" },
5870         { "getpid",          control_getpid,            true,   false,  "get ctdbd process ID" },
5871         { "disable",         control_disable,           true,   false,  "disable a nodes public IP" },
5872         { "enable",          control_enable,            true,   false,  "enable a nodes public IP" },
5873         { "stop",            control_stop,              true,   false,  "stop a node" },
5874         { "continue",        control_continue,          true,   false,  "re-start a stopped node" },
5875         { "ban",             control_ban,               true,   false,  "ban a node from the cluster",          "<bantime|0>"},
5876         { "unban",           control_unban,             true,   false,  "unban a node" },
5877         { "showban",         control_showban,           true,   false,  "show ban information"},
5878         { "shutdown",        control_shutdown,          true,   false,  "shutdown ctdbd" },
5879         { "recover",         control_recover,           true,   false,  "force recovery" },
5880         { "sync",            control_ipreallocate,      true,   false,  "wait until ctdbd has synced all state changes" },
5881         { "ipreallocate",    control_ipreallocate,      true,   false,  "force the recovery daemon to perform a ip reallocation procedure" },
5882         { "thaw",            control_thaw,              true,   false,  "thaw databases", "[priority:1-3]" },
5883         { "isnotrecmaster",  control_isnotrecmaster,    false,  false,  "check if the local node is recmaster or not" },
5884         { "killtcp",         kill_tcp,                  false,  false, "kill a tcp connection.", "<srcip:port> <dstip:port>" },
5885         { "gratiousarp",     control_gratious_arp,      false,  false, "send a gratious arp", "<ip> <interface>" },
5886         { "tickle",          tickle_tcp,                false,  false, "send a tcp tickle ack", "<srcip:port> <dstip:port>" },
5887         { "gettickles",      control_get_tickles,       false,  false, "get the list of tickles registered for this ip", "<ip> [<port>]" },
5888         { "addtickle",       control_add_tickle,        false,  false, "add a tickle for this ip", "<ip>:<port> <ip>:<port>" },
5889
5890         { "deltickle",       control_del_tickle,        false,  false, "delete a tickle from this ip", "<ip>:<port> <ip>:<port>" },
5891
5892         { "regsrvid",        regsrvid,                  false,  false, "register a server id", "<pnn> <type> <id>" },
5893         { "unregsrvid",      unregsrvid,                false,  false, "unregister a server id", "<pnn> <type> <id>" },
5894         { "chksrvid",        chksrvid,                  false,  false, "check if a server id exists", "<pnn> <type> <id>" },
5895         { "getsrvids",       getsrvids,                 false,  false, "get a list of all server ids"},
5896         { "check_srvids",    check_srvids,              false,  false, "check if a srvid exists", "<id>+" },
5897         { "vacuum",          ctdb_vacuum,               false,  true, "vacuum the databases of empty records", "[max_records]"},
5898         { "repack",          ctdb_repack,               false,  false, "repack all databases", "[max_freelist]"},
5899         { "listnodes",       control_listnodes,         false,  true, "list all nodes in the cluster"},
5900         { "reloadnodes",     control_reload_nodes_file, false,  false, "reload the nodes file and restart the transport on all nodes"},
5901         { "moveip",          control_moveip,            false,  false, "move/failover an ip address to another node", "<ip> <node>"},
5902         { "rebalanceip",     control_rebalanceip,       false,  false, "release an ip from the node and let recd rebalance it", "<ip>"},
5903         { "addip",           control_addip,             true,   false, "add a ip address to a node", "<ip/mask> <iface>"},
5904         { "delip",           control_delip,             false,  false, "delete an ip address from a node", "<ip>"},
5905         { "eventscript",     control_eventscript,       true,   false, "run the eventscript with the given parameters on a node", "<arguments>"},
5906         { "backupdb",        control_backupdb,          false,  false, "backup the database into a file.", "<dbname|dbid> <file>"},
5907         { "restoredb",        control_restoredb,        false,  false, "restore the database from a file.", "<file> [dbname]"},
5908         { "dumpdbbackup",    control_dumpdbbackup,      false,  true,  "dump database backup from a file.", "<file>"},
5909         { "wipedb",           control_wipedb,        false,     false, "wipe the contents of a database.", "<dbname|dbid>"},
5910         { "recmaster",        control_recmaster,        true,   false, "show the pnn for the recovery master."},
5911         { "scriptstatus",     control_scriptstatus,     true,   false, "show the status of the monitoring scripts (or all scripts)", "[all]"},
5912         { "enablescript",     control_enablescript,  false,     false, "enable an eventscript", "<script>"},
5913         { "disablescript",    control_disablescript,  false,    false, "disable an eventscript", "<script>"},
5914         { "natgwlist",        control_natgwlist,        false,  false, "show the nodes belonging to this natgw configuration"},
5915         { "xpnn",             control_xpnn,             true,   true,  "find the pnn of the local node without talking to the daemon (unreliable)" },
5916         { "getreclock",       control_getreclock,       false,  false, "Show the reclock file of a node"},
5917         { "setreclock",       control_setreclock,       false,  false, "Set/clear the reclock file of a node", "[filename]"},
5918         { "setnatgwstate",    control_setnatgwstate,    false,  false, "Set NATGW state to on/off", "{on|off}"},
5919         { "setlmasterrole",   control_setlmasterrole,   false,  false, "Set LMASTER role to on/off", "{on|off}"},
5920         { "setrecmasterrole", control_setrecmasterrole, false,  false, "Set RECMASTER role to on/off", "{on|off}"},
5921         { "setdbprio",        control_setdbprio,        false,  false, "Set DB priority", "<dbname|dbid> <prio:1-3>"},
5922         { "getdbprio",        control_getdbprio,        false,  false, "Get DB priority", "<dbname|dbid>"},
5923         { "setdbreadonly",    control_setdbreadonly,    false,  false, "Set DB readonly capable", "<dbname|dbid>"},
5924         { "setdbsticky",      control_setdbsticky,      false,  false, "Set DB sticky-records capable", "<dbname|dbid>"},
5925         { "msglisten",        control_msglisten,        false,  false, "Listen on a srvid port for messages", "<msg srvid>"},
5926         { "msgsend",          control_msgsend,  false,  false, "Send a message to srvid", "<srvid> <message>"},
5927         { "sync",            control_ipreallocate,      false,  false,  "wait until ctdbd has synced all state changes" },
5928         { "pfetch",          control_pfetch,            false,  false,  "fetch a record from a persistent database", "<dbname|dbid> <key> [<file>]" },
5929         { "pstore",          control_pstore,            false,  false,  "write a record to a persistent database", "<dbname|dbid> <key> <file containing record>" },
5930         { "pdelete",         control_pdelete,           false,  false,  "delete a record from a persistent database", "<dbname|dbid> <key>" },
5931         { "tfetch",          control_tfetch,            false,  true,  "fetch a record from a [c]tdb-file [-v]", "<tdb-file> <key> [<file>]" },
5932         { "tstore",          control_tstore,            false,  true,  "store a record (including ltdb header)", "<tdb-file> <key> <data+header>" },
5933         { "readkey",         control_readkey,           true,   false,  "read the content off a database key", "<tdb-file> <key>" },
5934         { "writekey",        control_writekey,          true,   false,  "write to a database key", "<tdb-file> <key> <value>" },
5935         { "checktcpport",    control_chktcpport,        false,  true,  "check if a service is bound to a specific tcp port or not", "<port>" },
5936         { "rebalancenode",     control_rebalancenode,   false,  false, "release a node by allowing it to takeover ips", "<pnn>"},
5937         { "getdbseqnum",     control_getdbseqnum,       false,  false, "get the sequence number off a database", "<dbname|dbid>" },
5938         { "setdbseqnum",     control_setdbseqnum,       false,  false, "set the sequence number for a database", "<dbname|dbid> <seqnum>" },
5939         { "nodestatus",      control_nodestatus,        true,   false,  "show and return node status" },
5940         { "dbstatistics",    control_dbstatistics,      false,  false, "show db statistics", "<dbname|dbid>" },
5941         { "reloadips",       control_reloadips,         false,  false, "reload the public addresses file on a node" },
5942         { "ipiface",         control_ipiface,           true,   true,  "Find which interface an ip address is hsoted on", "<ip>" },
5943 };
5944
5945 /*
5946   show usage message
5947  */
5948 static void usage(void)
5949 {
5950         int i;
5951         printf(
5952 "Usage: ctdb [options] <control>\n" \
5953 "Options:\n" \
5954 "   -n <node>          choose node number, or 'all' (defaults to local node)\n"
5955 "   -Y                 generate machinereadable output\n"
5956 "   -v                 generate verbose output\n"
5957 "   -t <timelimit>     set timelimit for control in seconds (default %u)\n", options.timelimit);
5958         printf("Controls:\n");
5959         for (i=0;i<ARRAY_SIZE(ctdb_commands);i++) {
5960                 printf("  %-15s %-27s  %s\n", 
5961                        ctdb_commands[i].name, 
5962                        ctdb_commands[i].args?ctdb_commands[i].args:"",
5963                        ctdb_commands[i].msg);
5964         }
5965         exit(1);
5966 }
5967
5968
5969 static void ctdb_alarm(int sig)
5970 {
5971         printf("Maximum runtime exceeded - exiting\n");
5972         _exit(ERR_TIMEOUT);
5973 }
5974
5975 /*
5976   main program
5977 */
5978 int main(int argc, const char *argv[])
5979 {
5980         struct ctdb_context *ctdb;
5981         char *nodestring = NULL;
5982         struct poptOption popt_options[] = {
5983                 POPT_AUTOHELP
5984                 POPT_CTDB_CMDLINE
5985                 { "timelimit", 't', POPT_ARG_INT, &options.timelimit, 0, "timelimit", "integer" },
5986                 { "node",      'n', POPT_ARG_STRING, &nodestring, 0, "node", "integer|all" },
5987                 { "machinereadable", 'Y', POPT_ARG_NONE, &options.machinereadable, 0, "enable machinereadable output", NULL },
5988                 { "verbose",    'v', POPT_ARG_NONE, &options.verbose, 0, "enable verbose output", NULL },
5989                 { "maxruntime", 'T', POPT_ARG_INT, &options.maxruntime, 0, "die if runtime exceeds this limit (in seconds)", "integer" },
5990                 { "print-emptyrecords", 0, POPT_ARG_NONE, &options.printemptyrecords, 0, "print the empty records when dumping databases (catdb, cattdb, dumpdbbackup)", NULL },
5991                 { "print-datasize", 0, POPT_ARG_NONE, &options.printdatasize, 0, "do not print record data when dumping databases, only the data size", NULL },
5992                 { "print-lmaster", 0, POPT_ARG_NONE, &options.printlmaster, 0, "print the record's lmaster in catdb", NULL },
5993                 { "print-hash", 0, POPT_ARG_NONE, &options.printhash, 0, "print the record's hash when dumping databases", NULL },
5994                 { "print-recordflags", 0, POPT_ARG_NONE, &options.printrecordflags, 0, "print the record flags in catdb and dumpdbbackup", NULL },
5995                 POPT_TABLEEND
5996         };
5997         int opt;
5998         const char **extra_argv;
5999         int extra_argc = 0;
6000         int ret=-1, i;
6001         poptContext pc;
6002         struct event_context *ev;
6003         const char *control;
6004         const char *socket_name;
6005
6006         setlinebuf(stdout);
6007         
6008         /* set some defaults */
6009         options.maxruntime = 0;
6010         options.timelimit = 3;
6011         options.pnn = CTDB_CURRENT_NODE;
6012
6013         pc = poptGetContext(argv[0], argc, argv, popt_options, POPT_CONTEXT_KEEP_FIRST);
6014
6015         while ((opt = poptGetNextOpt(pc)) != -1) {
6016                 switch (opt) {
6017                 default:
6018                         DEBUG(DEBUG_ERR, ("Invalid option %s: %s\n", 
6019                                 poptBadOption(pc, 0), poptStrerror(opt)));
6020                         exit(1);
6021                 }
6022         }
6023
6024         /* setup the remaining options for the main program to use */
6025         extra_argv = poptGetArgs(pc);
6026         if (extra_argv) {
6027                 extra_argv++;
6028                 while (extra_argv[extra_argc]) extra_argc++;
6029         }
6030
6031         if (extra_argc < 1) {
6032                 usage();
6033         }
6034
6035         if (options.maxruntime == 0) {
6036                 const char *ctdb_timeout;
6037                 ctdb_timeout = getenv("CTDB_TIMEOUT");
6038                 if (ctdb_timeout != NULL) {
6039                         options.maxruntime = strtoul(ctdb_timeout, NULL, 0);
6040                 } else {
6041                         /* default timeout is 120 seconds */
6042                         options.maxruntime = 120;
6043                 }
6044         }
6045
6046         signal(SIGALRM, ctdb_alarm);
6047         alarm(options.maxruntime);
6048
6049         control = extra_argv[0];
6050
6051         ev = event_context_init(NULL);
6052         if (!ev) {
6053                 DEBUG(DEBUG_ERR, ("Failed to initialize event system\n"));
6054                 exit(1);
6055         }
6056
6057         for (i=0;i<ARRAY_SIZE(ctdb_commands);i++) {
6058                 if (strcmp(control, ctdb_commands[i].name) == 0) {
6059                         break;
6060                 }
6061         }
6062
6063         if (i == ARRAY_SIZE(ctdb_commands)) {
6064                 DEBUG(DEBUG_ERR, ("Unknown control '%s'\n", control));
6065                 exit(1);
6066         }
6067
6068         if (ctdb_commands[i].without_daemon == true) {
6069                 if (nodestring != NULL) {
6070                         DEBUG(DEBUG_ERR, ("Can't specify node(s) with \"ctdb %s\"\n", control));
6071                         exit(1);
6072                 }
6073                 close(2);
6074                 return ctdb_commands[i].fn(NULL, extra_argc-1, extra_argv+1);
6075         }
6076
6077         /* initialise ctdb */
6078         ctdb = ctdb_cmdline_client(ev, TIMELIMIT());
6079
6080         if (ctdb == NULL) {
6081                 DEBUG(DEBUG_ERR, ("Failed to init ctdb\n"));
6082                 exit(1);
6083         }
6084
6085         /* initialize a libctdb connection as well */
6086         socket_name = ctdb_get_socketname(ctdb);
6087         ctdb_connection = ctdb_connect(socket_name,
6088                                        ctdb_log_file, stderr);
6089         if (ctdb_connection == NULL) {
6090                 DEBUG(DEBUG_ERR, ("Failed to connect to daemon from libctdb\n"));
6091                 exit(1);
6092         }                               
6093
6094         /* setup the node number(s) to contact */
6095         if (!parse_nodestring(ctdb, nodestring, CTDB_CURRENT_NODE, false,
6096                               &options.nodes, &options.pnn)) {
6097                 usage();
6098         }
6099
6100         if (options.pnn == CTDB_CURRENT_NODE) {
6101                 options.pnn = options.nodes[0];
6102         }
6103
6104         if (ctdb_commands[i].auto_all && 
6105             ((options.pnn == CTDB_BROADCAST_ALL) ||
6106              (options.pnn == CTDB_MULTICAST))) {
6107                 int j;
6108
6109                 ret = 0;
6110                 for (j = 0; j < talloc_array_length(options.nodes); j++) {
6111                         options.pnn = options.nodes[j];
6112                         ret |= ctdb_commands[i].fn(ctdb, extra_argc-1, extra_argv+1);
6113                 }
6114         } else {
6115                 ret = ctdb_commands[i].fn(ctdb, extra_argc-1, extra_argv+1);
6116         }
6117
6118         ctdb_disconnect(ctdb_connection);
6119         talloc_free(ctdb);
6120         talloc_free(ev);
6121         (void)poptFreeContext(pc);
6122
6123         return ret;
6124
6125 }