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