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