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