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