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