d760f6bc770d1e1ec1c3cd68a7ed29983a243169
[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].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:Inactive:PartiallyOnline:\n");
629                 for(i=0;i<nodemap->num;i++){
630                         int partially_online = 0;
631                         int j;
632
633                         if (nodemap->nodes[i].flags & NODE_FLAGS_DELETED) {
634                                 continue;
635                         }
636                         if (nodemap->nodes[i].flags == 0) {
637                                 struct ctdb_control_get_ifaces *ifaces;
638
639                                 ret = ctdb_ctrl_get_ifaces(ctdb, TIMELIMIT(),
640                                                            nodemap->nodes[i].pnn,
641                                                            ctdb, &ifaces);
642                                 if (ret == 0) {
643                                         for (j=0; j < ifaces->num; j++) {
644                                                 if (ifaces->ifaces[j].link_state != 0) {
645                                                         continue;
646                                                 }
647                                                 partially_online = 1;
648                                                 break;
649                                         }
650                                         talloc_free(ifaces);
651                                 }
652                         }
653                         printf(":%d:%s:%d:%d:%d:%d:%d:%d:%d:\n", nodemap->nodes[i].pnn,
654                                 ctdb_addr_to_str(&nodemap->nodes[i].addr),
655                                !!(nodemap->nodes[i].flags&NODE_FLAGS_DISCONNECTED),
656                                !!(nodemap->nodes[i].flags&NODE_FLAGS_BANNED),
657                                !!(nodemap->nodes[i].flags&NODE_FLAGS_PERMANENTLY_DISABLED),
658                                !!(nodemap->nodes[i].flags&NODE_FLAGS_UNHEALTHY),
659                                !!(nodemap->nodes[i].flags&NODE_FLAGS_STOPPED),
660                                !!(nodemap->nodes[i].flags&NODE_FLAGS_INACTIVE),
661                                partially_online);
662                 }
663                 return 0;
664         }
665
666         printf("Number of nodes:%d\n", nodemap->num);
667         for(i=0;i<nodemap->num;i++){
668                 static const struct {
669                         uint32_t flag;
670                         const char *name;
671                 } flag_names[] = {
672                         { NODE_FLAGS_DISCONNECTED,          "DISCONNECTED" },
673                         { NODE_FLAGS_PERMANENTLY_DISABLED,  "DISABLED" },
674                         { NODE_FLAGS_BANNED,                "BANNED" },
675                         { NODE_FLAGS_UNHEALTHY,             "UNHEALTHY" },
676                         { NODE_FLAGS_DELETED,               "DELETED" },
677                         { NODE_FLAGS_STOPPED,               "STOPPED" },
678                         { NODE_FLAGS_INACTIVE,              "INACTIVE" },
679                 };
680                 char *flags_str = NULL;
681                 int j;
682
683                 if (nodemap->nodes[i].flags & NODE_FLAGS_DELETED) {
684                         continue;
685                 }
686                 if (nodemap->nodes[i].flags == 0) {
687                         struct ctdb_control_get_ifaces *ifaces;
688
689                         ret = ctdb_ctrl_get_ifaces(ctdb, TIMELIMIT(),
690                                                    nodemap->nodes[i].pnn,
691                                                    ctdb, &ifaces);
692                         if (ret == 0) {
693                                 for (j=0; j < ifaces->num; j++) {
694                                         if (ifaces->ifaces[j].link_state != 0) {
695                                                 continue;
696                                         }
697                                         flags_str = talloc_strdup(ctdb, "PARTIALLYONLINE");
698                                         break;
699                                 }
700                                 talloc_free(ifaces);
701                         }
702                 }
703                 for (j=0;j<ARRAY_SIZE(flag_names);j++) {
704                         if (nodemap->nodes[i].flags & flag_names[j].flag) {
705                                 if (flags_str == NULL) {
706                                         flags_str = talloc_strdup(ctdb, flag_names[j].name);
707                                 } else {
708                                         flags_str = talloc_asprintf_append(flags_str, "|%s",
709                                                                            flag_names[j].name);
710                                 }
711                                 CTDB_NO_MEMORY_FATAL(ctdb, flags_str);
712                         }
713                 }
714                 if (flags_str == NULL) {
715                         flags_str = talloc_strdup(ctdb, "OK");
716                         CTDB_NO_MEMORY_FATAL(ctdb, flags_str);
717                 }
718                 printf("pnn:%d %-16s %s%s\n", nodemap->nodes[i].pnn,
719                        ctdb_addr_to_str(&nodemap->nodes[i].addr),
720                        flags_str,
721                        nodemap->nodes[i].pnn == mypnn?" (THIS NODE)":"");
722                 talloc_free(flags_str);
723         }
724
725         ret = ctdb_ctrl_getvnnmap(ctdb, TIMELIMIT(), options.pnn, ctdb, &vnnmap);
726         if (ret != 0) {
727                 DEBUG(DEBUG_ERR, ("Unable to get vnnmap from node %u\n", options.pnn));
728                 return ret;
729         }
730         if (vnnmap->generation == INVALID_GENERATION) {
731                 printf("Generation:INVALID\n");
732         } else {
733                 printf("Generation:%d\n",vnnmap->generation);
734         }
735         printf("Size:%d\n",vnnmap->size);
736         for(i=0;i<vnnmap->size;i++){
737                 printf("hash:%d lmaster:%d\n", i, vnnmap->map[i]);
738         }
739
740         ret = ctdb_ctrl_getrecmode(ctdb, ctdb, TIMELIMIT(), options.pnn, &recmode);
741         if (ret != 0) {
742                 DEBUG(DEBUG_ERR, ("Unable to get recmode from node %u\n", options.pnn));
743                 return ret;
744         }
745         printf("Recovery mode:%s (%d)\n",recmode==CTDB_RECOVERY_NORMAL?"NORMAL":"RECOVERY",recmode);
746
747         ret = ctdb_ctrl_getrecmaster(ctdb, ctdb, TIMELIMIT(), options.pnn, &recmaster);
748         if (ret != 0) {
749                 DEBUG(DEBUG_ERR, ("Unable to get recmaster from node %u\n", options.pnn));
750                 return ret;
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         int ret;
1099         uint32_t recmaster;
1100
1101         ret = ctdb_ctrl_getrecmaster(ctdb, ctdb, TIMELIMIT(), options.pnn, &recmaster);
1102         if (ret != 0) {
1103                 DEBUG(DEBUG_ERR, ("Unable to get recmaster from node %u\n", options.pnn));
1104                 return ret;
1105         }
1106         printf("%d\n",recmaster);
1107
1108         return 0;
1109 }
1110
1111 /*
1112   add a tickle to a public address
1113  */
1114 static int control_add_tickle(struct ctdb_context *ctdb, int argc, const char **argv)
1115 {
1116         struct ctdb_tcp_connection t;
1117         TDB_DATA data;
1118         int ret;
1119
1120         if (argc < 2) {
1121                 usage();
1122         }
1123
1124         if (parse_ip_port(argv[0], &t.src_addr) == 0) {
1125                 DEBUG(DEBUG_ERR,("Wrongly formed ip address '%s'\n", argv[0]));
1126                 return -1;
1127         }
1128         if (parse_ip_port(argv[1], &t.dst_addr) == 0) {
1129                 DEBUG(DEBUG_ERR,("Wrongly formed ip address '%s'\n", argv[1]));
1130                 return -1;
1131         }
1132
1133         data.dptr = (uint8_t *)&t;
1134         data.dsize = sizeof(t);
1135
1136         /* tell all nodes about this tcp connection */
1137         ret = ctdb_control(ctdb, options.pnn, 0, CTDB_CONTROL_TCP_ADD_DELAYED_UPDATE,
1138                            0, data, ctdb, NULL, NULL, NULL, NULL);
1139         if (ret != 0) {
1140                 DEBUG(DEBUG_ERR,("Failed to add tickle\n"));
1141                 return -1;
1142         }
1143         
1144         return 0;
1145 }
1146
1147
1148 /*
1149   delete a tickle from a node
1150  */
1151 static int control_del_tickle(struct ctdb_context *ctdb, int argc, const char **argv)
1152 {
1153         struct ctdb_tcp_connection t;
1154         TDB_DATA data;
1155         int ret;
1156
1157         if (argc < 2) {
1158                 usage();
1159         }
1160
1161         if (parse_ip_port(argv[0], &t.src_addr) == 0) {
1162                 DEBUG(DEBUG_ERR,("Wrongly formed ip address '%s'\n", argv[0]));
1163                 return -1;
1164         }
1165         if (parse_ip_port(argv[1], &t.dst_addr) == 0) {
1166                 DEBUG(DEBUG_ERR,("Wrongly formed ip address '%s'\n", argv[1]));
1167                 return -1;
1168         }
1169
1170         data.dptr = (uint8_t *)&t;
1171         data.dsize = sizeof(t);
1172
1173         /* tell all nodes about this tcp connection */
1174         ret = ctdb_control(ctdb, options.pnn, 0, CTDB_CONTROL_TCP_REMOVE,
1175                            0, data, ctdb, NULL, NULL, NULL, NULL);
1176         if (ret != 0) {
1177                 DEBUG(DEBUG_ERR,("Failed to remove tickle\n"));
1178                 return -1;
1179         }
1180         
1181         return 0;
1182 }
1183
1184
1185 /*
1186   get a list of all tickles for this pnn
1187  */
1188 static int control_get_tickles(struct ctdb_context *ctdb, int argc, const char **argv)
1189 {
1190         struct ctdb_control_tcp_tickle_list *list;
1191         ctdb_sock_addr addr;
1192         int i, ret;
1193         unsigned port = 0;
1194
1195         if (argc < 1) {
1196                 usage();
1197         }
1198
1199         if (argc == 2) {
1200                 port = atoi(argv[1]);
1201         }
1202
1203         if (parse_ip(argv[0], NULL, 0, &addr) == 0) {
1204                 DEBUG(DEBUG_ERR,("Wrongly formed ip address '%s'\n", argv[0]));
1205                 return -1;
1206         }
1207
1208         ret = ctdb_ctrl_get_tcp_tickles(ctdb, TIMELIMIT(), options.pnn, ctdb, &addr, &list);
1209         if (ret == -1) {
1210                 DEBUG(DEBUG_ERR, ("Unable to list tickles\n"));
1211                 return -1;
1212         }
1213
1214         if (options.machinereadable){
1215                 printf(":source ip:port:destination ip:port:\n");
1216                 for (i=0;i<list->tickles.num;i++) {
1217                         if (port && port != ntohs(list->tickles.connections[i].dst_addr.ip.sin_port)) {
1218                                 continue;
1219                         }
1220                         printf(":%s:%u", ctdb_addr_to_str(&list->tickles.connections[i].src_addr), ntohs(list->tickles.connections[i].src_addr.ip.sin_port));
1221                         printf(":%s:%u:\n", ctdb_addr_to_str(&list->tickles.connections[i].dst_addr), ntohs(list->tickles.connections[i].dst_addr.ip.sin_port));
1222                 }
1223         } else {
1224                 printf("Tickles for ip:%s\n", ctdb_addr_to_str(&list->addr));
1225                 printf("Num tickles:%u\n", list->tickles.num);
1226                 for (i=0;i<list->tickles.num;i++) {
1227                         if (port && port != ntohs(list->tickles.connections[i].dst_addr.ip.sin_port)) {
1228                                 continue;
1229                         }
1230                         printf("SRC: %s:%u   ", ctdb_addr_to_str(&list->tickles.connections[i].src_addr), ntohs(list->tickles.connections[i].src_addr.ip.sin_port));
1231                         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));
1232                 }
1233         }
1234
1235         talloc_free(list);
1236         
1237         return 0;
1238 }
1239
1240
1241 static int move_ip(struct ctdb_context *ctdb, ctdb_sock_addr *addr, uint32_t pnn)
1242 {
1243         struct ctdb_all_public_ips *ips;
1244         struct ctdb_public_ip ip;
1245         int i, ret;
1246         uint32_t *nodes;
1247         uint32_t disable_time;
1248         TDB_DATA data;
1249         struct ctdb_node_map *nodemap=NULL;
1250         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
1251
1252         disable_time = 30;
1253         data.dptr  = (uint8_t*)&disable_time;
1254         data.dsize = sizeof(disable_time);
1255         ret = ctdb_client_send_message(ctdb, CTDB_BROADCAST_CONNECTED, CTDB_SRVID_DISABLE_IP_CHECK, data);
1256         if (ret != 0) {
1257                 DEBUG(DEBUG_ERR,("Failed to send message to disable ipcheck\n"));
1258                 return -1;
1259         }
1260
1261
1262
1263         /* read the public ip list from the node */
1264         ret = ctdb_ctrl_get_public_ips(ctdb, TIMELIMIT(), pnn, ctdb, &ips);
1265         if (ret != 0) {
1266                 DEBUG(DEBUG_ERR, ("Unable to get public ip list from node %u\n", pnn));
1267                 talloc_free(tmp_ctx);
1268                 return -1;
1269         }
1270
1271         for (i=0;i<ips->num;i++) {
1272                 if (ctdb_same_ip(addr, &ips->ips[i].addr)) {
1273                         break;
1274                 }
1275         }
1276         if (i==ips->num) {
1277                 DEBUG(DEBUG_ERR, ("Node %u can not host ip address '%s'\n",
1278                         pnn, ctdb_addr_to_str(addr)));
1279                 talloc_free(tmp_ctx);
1280                 return -1;
1281         }
1282
1283         ip.pnn  = pnn;
1284         ip.addr = *addr;
1285
1286         data.dptr  = (uint8_t *)&ip;
1287         data.dsize = sizeof(ip);
1288
1289         ret = ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), options.pnn, tmp_ctx, &nodemap);
1290         if (ret != 0) {
1291                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from node %u\n", options.pnn));
1292                 talloc_free(tmp_ctx);
1293                 return ret;
1294         }
1295
1296         nodes = list_of_active_nodes_except_pnn(ctdb, nodemap, tmp_ctx, pnn);
1297         ret = ctdb_client_async_control(ctdb, CTDB_CONTROL_RELEASE_IP,
1298                                         nodes, 0,
1299                                         LONGTIMELIMIT(),
1300                                         false, data,
1301                                         NULL, NULL,
1302                                         NULL);
1303         if (ret != 0) {
1304                 DEBUG(DEBUG_ERR,("Failed to release IP on nodes\n"));
1305                 talloc_free(tmp_ctx);
1306                 return -1;
1307         }
1308
1309         ret = ctdb_ctrl_takeover_ip(ctdb, LONGTIMELIMIT(), pnn, &ip);
1310         if (ret != 0) {
1311                 DEBUG(DEBUG_ERR,("Failed to take over IP on node %d\n", pnn));
1312                 talloc_free(tmp_ctx);
1313                 return -1;
1314         }
1315
1316         /* update the recovery daemon so it now knows to expect the new
1317            node assignment for this ip.
1318         */
1319         ret = ctdb_client_send_message(ctdb, CTDB_BROADCAST_CONNECTED, CTDB_SRVID_RECD_UPDATE_IP, data);
1320         if (ret != 0) {
1321                 DEBUG(DEBUG_ERR,("Failed to send message to update the ip on the recovery master.\n"));
1322                 return -1;
1323         }
1324
1325         talloc_free(tmp_ctx);
1326         return 0;
1327 }
1328
1329 /*
1330   move/failover an ip address to a specific node
1331  */
1332 static int control_moveip(struct ctdb_context *ctdb, int argc, const char **argv)
1333 {
1334         uint32_t pnn;
1335         int ret, retries = 0;
1336         ctdb_sock_addr addr;
1337
1338         if (argc < 2) {
1339                 usage();
1340                 return -1;
1341         }
1342
1343         if (parse_ip(argv[0], NULL, 0, &addr) == 0) {
1344                 DEBUG(DEBUG_ERR,("Wrongly formed ip address '%s'\n", argv[0]));
1345                 return -1;
1346         }
1347
1348
1349         if (sscanf(argv[1], "%u", &pnn) != 1) {
1350                 DEBUG(DEBUG_ERR, ("Badly formed pnn\n"));
1351                 return -1;
1352         }
1353
1354         do {
1355                 ret = move_ip(ctdb, &addr, pnn);
1356                 if (ret != 0) {
1357                         DEBUG(DEBUG_ERR,("Failed to move ip to node %d. Wait 3 second and try again.\n", pnn));
1358                         sleep(3);
1359                         retries++;
1360                 }
1361         } while (retries < 5 && ret != 0);
1362         if (ret != 0) {
1363                 DEBUG(DEBUG_ERR,("Failed to move ip to node %d. Giving up.\n", pnn));
1364                 return -1;
1365         }
1366
1367         return 0;
1368 }
1369
1370 void getips_store_callback(void *param, void *data)
1371 {
1372         struct ctdb_public_ip *node_ip = (struct ctdb_public_ip *)data;
1373         struct ctdb_all_public_ips *ips = param;
1374         int i;
1375
1376         i = ips->num++;
1377         ips->ips[i].pnn  = node_ip->pnn;
1378         ips->ips[i].addr = node_ip->addr;
1379 }
1380
1381 void getips_count_callback(void *param, void *data)
1382 {
1383         uint32_t *count = param;
1384
1385         (*count)++;
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         ret = ctdb_ctrl_getrecmaster(ctdb, ctdb, TIMELIMIT(), options.pnn, &recmaster);
1600         if (ret != 0) {
1601                 DEBUG(DEBUG_ERR, ("Unable to get recmaster from node %u\n", options.pnn));
1602                 return ret;
1603         }
1604
1605         /* verify the node exists */
1606         if (ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), recmaster, ctdb, &nodemap) != 0) {
1607                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from local node\n"));
1608                 return -1;
1609         }
1610
1611
1612         /* check tha there are nodes available that can act as a recmaster */
1613         for (i=0; i<nodemap->num; i++) {
1614                 if (nodemap->nodes[i].flags & (NODE_FLAGS_DELETED|NODE_FLAGS_BANNED|NODE_FLAGS_STOPPED)) {
1615                         continue;
1616                 }
1617                 break;
1618         }
1619         if (i == nodemap->num) {
1620                 DEBUG(DEBUG_ERR,("No possible nodes to host addresses.\n"));
1621                 return 0;
1622         }
1623
1624         /* verify the recovery master is not STOPPED, nor BANNED */
1625         if (nodemap->nodes[recmaster].flags & (NODE_FLAGS_DELETED|NODE_FLAGS_BANNED|NODE_FLAGS_STOPPED)) {
1626                 DEBUG(DEBUG_ERR,("No suitable recmaster found. Try again\n"));
1627                 retries++;
1628                 sleep(1);
1629                 goto again;
1630         } 
1631         
1632         /* verify the recovery master is not STOPPED, nor BANNED */
1633         if (nodemap->nodes[recmaster].flags & (NODE_FLAGS_DELETED|NODE_FLAGS_BANNED|NODE_FLAGS_STOPPED)) {
1634                 DEBUG(DEBUG_ERR,("No suitable recmaster found. Try again\n"));
1635                 retries++;
1636                 sleep(1);
1637                 goto again;
1638         } 
1639
1640         ipreallocate_finished = 0;
1641         ret = ctdb_client_send_message(ctdb, recmaster, CTDB_SRVID_TAKEOVER_RUN, data);
1642         if (ret != 0) {
1643                 DEBUG(DEBUG_ERR,("Failed to send ip takeover run request message to %u\n", options.pnn));
1644                 return -1;
1645         }
1646
1647         tv = timeval_current();
1648         /* this loop will terminate when we have received the reply */
1649         while (timeval_elapsed(&tv) < 5.0 && ipreallocate_finished == 0) {
1650                 event_loop_once(ctdb->ev);
1651         }
1652         if (ipreallocate_finished == 1) {
1653                 return 0;
1654         }
1655
1656         retries++;
1657         sleep(1);
1658         goto again;
1659
1660         return 0;
1661 }
1662
1663
1664 /*
1665   add a public ip address to a node
1666  */
1667 static int control_addip(struct ctdb_context *ctdb, int argc, const char **argv)
1668 {
1669         int i, ret;
1670         int len, retries = 0;
1671         unsigned mask;
1672         ctdb_sock_addr addr;
1673         struct ctdb_control_ip_iface *pub;
1674         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
1675         struct ctdb_all_public_ips *ips;
1676
1677
1678         if (argc != 2) {
1679                 talloc_free(tmp_ctx);
1680                 usage();
1681         }
1682
1683         if (!parse_ip_mask(argv[0], argv[1], &addr, &mask)) {
1684                 DEBUG(DEBUG_ERR, ("Badly formed ip/mask : %s\n", argv[0]));
1685                 talloc_free(tmp_ctx);
1686                 return -1;
1687         }
1688
1689         /* read the public ip list from the node */
1690         ret = ctdb_ctrl_get_public_ips(ctdb, TIMELIMIT(), options.pnn, tmp_ctx, &ips);
1691         if (ret != 0) {
1692                 DEBUG(DEBUG_ERR, ("Unable to get public ip list from node %u\n", options.pnn));
1693                 talloc_free(tmp_ctx);
1694                 return -1;
1695         }
1696         for (i=0;i<ips->num;i++) {
1697                 if (ctdb_same_ip(&addr, &ips->ips[i].addr)) {
1698                         DEBUG(DEBUG_ERR,("Can not add ip to node. Node already hosts this ip\n"));
1699                         return 0;
1700                 }
1701         }
1702
1703
1704
1705         /* Dont timeout. This command waits for an ip reallocation
1706            which sometimes can take wuite a while if there has
1707            been a recent recovery
1708         */
1709         alarm(0);
1710
1711         len = offsetof(struct ctdb_control_ip_iface, iface) + strlen(argv[1]) + 1;
1712         pub = talloc_size(tmp_ctx, len); 
1713         CTDB_NO_MEMORY(ctdb, pub);
1714
1715         pub->addr  = addr;
1716         pub->mask  = mask;
1717         pub->len   = strlen(argv[1])+1;
1718         memcpy(&pub->iface[0], argv[1], strlen(argv[1])+1);
1719
1720         do {
1721                 ret = ctdb_ctrl_add_public_ip(ctdb, TIMELIMIT(), options.pnn, pub);
1722                 if (ret != 0) {
1723                         DEBUG(DEBUG_ERR, ("Unable to add public ip to node %u. Wait 3 seconds and try again.\n", options.pnn));
1724                         sleep(3);
1725                         retries++;
1726                 }
1727         } while (retries < 5 && ret != 0);
1728         if (ret != 0) {
1729                 DEBUG(DEBUG_ERR, ("Unable to add public ip to node %u. Giving up.\n", options.pnn));
1730                 talloc_free(tmp_ctx);
1731                 return ret;
1732         }
1733
1734         do {
1735                 ret = control_ipreallocate(ctdb, argc, argv);
1736                 if (ret != 0) {
1737                         DEBUG(DEBUG_ERR, ("IP Reallocate failed on node %u. Wait 3 seconds and try again.\n", options.pnn));
1738                         sleep(3);
1739                         retries++;
1740                 }
1741         } while (retries < 5 && ret != 0);
1742         if (ret != 0) {
1743                 DEBUG(DEBUG_ERR, ("IP Reallocate failed on node %u. Giving up.\n", options.pnn));
1744                 talloc_free(tmp_ctx);
1745                 return ret;
1746         }
1747
1748         talloc_free(tmp_ctx);
1749         return 0;
1750 }
1751
1752 static int control_delip(struct ctdb_context *ctdb, int argc, const char **argv);
1753
1754 static int control_delip_all(struct ctdb_context *ctdb, int argc, const char **argv, ctdb_sock_addr *addr)
1755 {
1756         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
1757         struct ctdb_node_map *nodemap=NULL;
1758         struct ctdb_all_public_ips *ips;
1759         int ret, i, j;
1760
1761         ret = ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE, tmp_ctx, &nodemap);
1762         if (ret != 0) {
1763                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from current node\n"));
1764                 return ret;
1765         }
1766
1767         /* remove it from the nodes that are not hosting the ip currently */
1768         for(i=0;i<nodemap->num;i++){
1769                 if (nodemap->nodes[i].flags & NODE_FLAGS_INACTIVE) {
1770                         continue;
1771                 }
1772                 if (ctdb_ctrl_get_public_ips(ctdb, TIMELIMIT(), nodemap->nodes[i].pnn, tmp_ctx, &ips) != 0) {
1773                         DEBUG(DEBUG_ERR, ("Unable to get public ip list from node %d\n", nodemap->nodes[i].pnn));
1774                         continue;
1775                 }
1776
1777                 for (j=0;j<ips->num;j++) {
1778                         if (ctdb_same_ip(addr, &ips->ips[j].addr)) {
1779                                 break;
1780                         }
1781                 }
1782                 if (j==ips->num) {
1783                         continue;
1784                 }
1785
1786                 if (ips->ips[j].pnn == nodemap->nodes[i].pnn) {
1787                         continue;
1788                 }
1789
1790                 options.pnn = nodemap->nodes[i].pnn;
1791                 control_delip(ctdb, argc, argv);
1792         }
1793
1794
1795         /* remove it from every node (also the one hosting it) */
1796         for(i=0;i<nodemap->num;i++){
1797                 if (nodemap->nodes[i].flags & NODE_FLAGS_INACTIVE) {
1798                         continue;
1799                 }
1800                 if (ctdb_ctrl_get_public_ips(ctdb, TIMELIMIT(), nodemap->nodes[i].pnn, tmp_ctx, &ips) != 0) {
1801                         DEBUG(DEBUG_ERR, ("Unable to get public ip list from node %d\n", nodemap->nodes[i].pnn));
1802                         continue;
1803                 }
1804
1805                 for (j=0;j<ips->num;j++) {
1806                         if (ctdb_same_ip(addr, &ips->ips[j].addr)) {
1807                                 break;
1808                         }
1809                 }
1810                 if (j==ips->num) {
1811                         continue;
1812                 }
1813
1814                 options.pnn = nodemap->nodes[i].pnn;
1815                 control_delip(ctdb, argc, argv);
1816         }
1817
1818         talloc_free(tmp_ctx);
1819         return 0;
1820 }
1821         
1822 /*
1823   delete a public ip address from a node
1824  */
1825 static int control_delip(struct ctdb_context *ctdb, int argc, const char **argv)
1826 {
1827         int i, ret;
1828         int retries = 0;
1829         ctdb_sock_addr addr;
1830         struct ctdb_control_ip_iface pub;
1831         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
1832         struct ctdb_all_public_ips *ips;
1833
1834         if (argc != 1) {
1835                 talloc_free(tmp_ctx);
1836                 usage();
1837         }
1838
1839         if (parse_ip(argv[0], NULL, 0, &addr) == 0) {
1840                 DEBUG(DEBUG_ERR,("Wrongly formed ip address '%s'\n", argv[0]));
1841                 return -1;
1842         }
1843
1844         if (options.pnn == CTDB_BROADCAST_ALL) {
1845                 return control_delip_all(ctdb, argc, argv, &addr);
1846         }
1847
1848         pub.addr  = addr;
1849         pub.mask  = 0;
1850         pub.len   = 0;
1851
1852         ret = ctdb_ctrl_get_public_ips(ctdb, TIMELIMIT(), options.pnn, tmp_ctx, &ips);
1853         if (ret != 0) {
1854                 DEBUG(DEBUG_ERR, ("Unable to get public ip list from cluster\n"));
1855                 talloc_free(tmp_ctx);
1856                 return ret;
1857         }
1858         
1859         for (i=0;i<ips->num;i++) {
1860                 if (ctdb_same_ip(&addr, &ips->ips[i].addr)) {
1861                         break;
1862                 }
1863         }
1864
1865         if (i==ips->num) {
1866                 DEBUG(DEBUG_ERR, ("This node does not support this public address '%s'\n",
1867                         ctdb_addr_to_str(&addr)));
1868                 talloc_free(tmp_ctx);
1869                 return -1;
1870         }
1871
1872         if (ips->ips[i].pnn == options.pnn) {
1873                 ret = find_other_host_for_public_ip(ctdb, &addr);
1874                 if (ret != -1) {
1875                         do {
1876                                 ret = move_ip(ctdb, &addr, ret);
1877                                 if (ret != 0) {
1878                                         DEBUG(DEBUG_ERR,("Failed to move ip to node %d. Wait 3 seconds and try again.\n", options.pnn));
1879                                         sleep(3);
1880                                         retries++;
1881                                 }
1882                         } while (retries < 5 && ret != 0);
1883                         if (ret != 0) {
1884                                 DEBUG(DEBUG_ERR,("Failed to move ip to node %d. Giving up.\n", options.pnn));
1885                                 return -1;
1886                         }
1887                 }
1888         }
1889
1890         ret = ctdb_ctrl_del_public_ip(ctdb, TIMELIMIT(), options.pnn, &pub);
1891         if (ret != 0) {
1892                 DEBUG(DEBUG_ERR, ("Unable to del public ip from node %u\n", options.pnn));
1893                 talloc_free(tmp_ctx);
1894                 return ret;
1895         }
1896
1897         talloc_free(tmp_ctx);
1898         return 0;
1899 }
1900
1901 /*
1902   kill a tcp connection
1903  */
1904 static int kill_tcp(struct ctdb_context *ctdb, int argc, const char **argv)
1905 {
1906         int ret;
1907         struct ctdb_control_killtcp killtcp;
1908
1909         if (argc < 2) {
1910                 usage();
1911         }
1912
1913         if (!parse_ip_port(argv[0], &killtcp.src_addr)) {
1914                 DEBUG(DEBUG_ERR, ("Bad IP:port '%s'\n", argv[0]));
1915                 return -1;
1916         }
1917
1918         if (!parse_ip_port(argv[1], &killtcp.dst_addr)) {
1919                 DEBUG(DEBUG_ERR, ("Bad IP:port '%s'\n", argv[1]));
1920                 return -1;
1921         }
1922
1923         ret = ctdb_ctrl_killtcp(ctdb, TIMELIMIT(), options.pnn, &killtcp);
1924         if (ret != 0) {
1925                 DEBUG(DEBUG_ERR, ("Unable to killtcp from node %u\n", options.pnn));
1926                 return ret;
1927         }
1928
1929         return 0;
1930 }
1931
1932
1933 /*
1934   send a gratious arp
1935  */
1936 static int control_gratious_arp(struct ctdb_context *ctdb, int argc, const char **argv)
1937 {
1938         int ret;
1939         ctdb_sock_addr addr;
1940
1941         if (argc < 2) {
1942                 usage();
1943         }
1944
1945         if (!parse_ip(argv[0], NULL, 0, &addr)) {
1946                 DEBUG(DEBUG_ERR, ("Bad IP '%s'\n", argv[0]));
1947                 return -1;
1948         }
1949
1950         ret = ctdb_ctrl_gratious_arp(ctdb, TIMELIMIT(), options.pnn, &addr, argv[1]);
1951         if (ret != 0) {
1952                 DEBUG(DEBUG_ERR, ("Unable to send gratious_arp from node %u\n", options.pnn));
1953                 return ret;
1954         }
1955
1956         return 0;
1957 }
1958
1959 /*
1960   register a server id
1961  */
1962 static int regsrvid(struct ctdb_context *ctdb, int argc, const char **argv)
1963 {
1964         int ret;
1965         struct ctdb_server_id server_id;
1966
1967         if (argc < 3) {
1968                 usage();
1969         }
1970
1971         server_id.pnn       = strtoul(argv[0], NULL, 0);
1972         server_id.type      = strtoul(argv[1], NULL, 0);
1973         server_id.server_id = strtoul(argv[2], NULL, 0);
1974
1975         ret = ctdb_ctrl_register_server_id(ctdb, TIMELIMIT(), &server_id);
1976         if (ret != 0) {
1977                 DEBUG(DEBUG_ERR, ("Unable to register server_id from node %u\n", options.pnn));
1978                 return ret;
1979         }
1980         DEBUG(DEBUG_ERR,("Srvid registered. Sleeping for 999 seconds\n"));
1981         sleep(999);
1982         return -1;
1983 }
1984
1985 /*
1986   unregister a server id
1987  */
1988 static int unregsrvid(struct ctdb_context *ctdb, int argc, const char **argv)
1989 {
1990         int ret;
1991         struct ctdb_server_id server_id;
1992
1993         if (argc < 3) {
1994                 usage();
1995         }
1996
1997         server_id.pnn       = strtoul(argv[0], NULL, 0);
1998         server_id.type      = strtoul(argv[1], NULL, 0);
1999         server_id.server_id = strtoul(argv[2], NULL, 0);
2000
2001         ret = ctdb_ctrl_unregister_server_id(ctdb, TIMELIMIT(), &server_id);
2002         if (ret != 0) {
2003                 DEBUG(DEBUG_ERR, ("Unable to unregister server_id from node %u\n", options.pnn));
2004                 return ret;
2005         }
2006         return -1;
2007 }
2008
2009 /*
2010   check if a server id exists
2011  */
2012 static int chksrvid(struct ctdb_context *ctdb, int argc, const char **argv)
2013 {
2014         uint32_t status;
2015         int ret;
2016         struct ctdb_server_id server_id;
2017
2018         if (argc < 3) {
2019                 usage();
2020         }
2021
2022         server_id.pnn       = strtoul(argv[0], NULL, 0);
2023         server_id.type      = strtoul(argv[1], NULL, 0);
2024         server_id.server_id = strtoul(argv[2], NULL, 0);
2025
2026         ret = ctdb_ctrl_check_server_id(ctdb, TIMELIMIT(), options.pnn, &server_id, &status);
2027         if (ret != 0) {
2028                 DEBUG(DEBUG_ERR, ("Unable to check server_id from node %u\n", options.pnn));
2029                 return ret;
2030         }
2031
2032         if (status) {
2033                 printf("Server id %d:%d:%d EXISTS\n", server_id.pnn, server_id.type, server_id.server_id);
2034         } else {
2035                 printf("Server id %d:%d:%d does NOT exist\n", server_id.pnn, server_id.type, server_id.server_id);
2036         }
2037         return 0;
2038 }
2039
2040 /*
2041   get a list of all server ids that are registered on a node
2042  */
2043 static int getsrvids(struct ctdb_context *ctdb, int argc, const char **argv)
2044 {
2045         int i, ret;
2046         struct ctdb_server_id_list *server_ids;
2047
2048         ret = ctdb_ctrl_get_server_id_list(ctdb, ctdb, TIMELIMIT(), options.pnn, &server_ids);
2049         if (ret != 0) {
2050                 DEBUG(DEBUG_ERR, ("Unable to get server_id list from node %u\n", options.pnn));
2051                 return ret;
2052         }
2053
2054         for (i=0; i<server_ids->num; i++) {
2055                 printf("Server id %d:%d:%d\n", 
2056                         server_ids->server_ids[i].pnn, 
2057                         server_ids->server_ids[i].type, 
2058                         server_ids->server_ids[i].server_id); 
2059         }
2060
2061         return -1;
2062 }
2063
2064 /*
2065   send a tcp tickle ack
2066  */
2067 static int tickle_tcp(struct ctdb_context *ctdb, int argc, const char **argv)
2068 {
2069         int ret;
2070         ctdb_sock_addr  src, dst;
2071
2072         if (argc < 2) {
2073                 usage();
2074         }
2075
2076         if (!parse_ip_port(argv[0], &src)) {
2077                 DEBUG(DEBUG_ERR, ("Bad IP:port '%s'\n", argv[0]));
2078                 return -1;
2079         }
2080
2081         if (!parse_ip_port(argv[1], &dst)) {
2082                 DEBUG(DEBUG_ERR, ("Bad IP:port '%s'\n", argv[1]));
2083                 return -1;
2084         }
2085
2086         ret = ctdb_sys_send_tcp(&src, &dst, 0, 0, 0);
2087         if (ret==0) {
2088                 return 0;
2089         }
2090         DEBUG(DEBUG_ERR, ("Error while sending tickle ack\n"));
2091
2092         return -1;
2093 }
2094
2095
2096 /*
2097   display public ip status
2098  */
2099 static int control_ip(struct ctdb_context *ctdb, int argc, const char **argv)
2100 {
2101         int i, ret;
2102         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
2103         struct ctdb_all_public_ips *ips;
2104
2105         if (options.pnn == CTDB_BROADCAST_ALL) {
2106                 /* read the list of public ips from all nodes */
2107                 ret = control_get_all_public_ips(ctdb, tmp_ctx, &ips);
2108         } else {
2109                 /* read the public ip list from this node */
2110                 ret = ctdb_ctrl_get_public_ips(ctdb, TIMELIMIT(), options.pnn, tmp_ctx, &ips);
2111         }
2112         if (ret != 0) {
2113                 DEBUG(DEBUG_ERR, ("Unable to get public ips from node %u\n", options.pnn));
2114                 talloc_free(tmp_ctx);
2115                 return ret;
2116         }
2117
2118         if (options.machinereadable){
2119                 printf(":Public IP:Node:");
2120                 if (options.verbose){
2121                         printf("ActiveInterface:AvailableInterfaces:ConfiguredInterfaces:");
2122                 }
2123                 printf("\n");
2124         } else {
2125                 if (options.pnn == CTDB_BROADCAST_ALL) {
2126                         printf("Public IPs on ALL nodes\n");
2127                 } else {
2128                         printf("Public IPs on node %u\n", options.pnn);
2129                 }
2130         }
2131
2132         for (i=1;i<=ips->num;i++) {
2133                 struct ctdb_control_public_ip_info *info = NULL;
2134                 int32_t pnn;
2135                 char *aciface = NULL;
2136                 char *avifaces = NULL;
2137                 char *cifaces = NULL;
2138
2139                 if (options.pnn == CTDB_BROADCAST_ALL) {
2140                         pnn = ips->ips[ips->num-i].pnn;
2141                 } else {
2142                         pnn = options.pnn;
2143                 }
2144
2145                 if (pnn != -1) {
2146                         ret = ctdb_ctrl_get_public_ip_info(ctdb, TIMELIMIT(), pnn, ctdb,
2147                                                    &ips->ips[ips->num-i].addr, &info);
2148                 } else {
2149                         ret = -1;
2150                 }
2151
2152                 if (ret == 0) {
2153                         int j;
2154                         for (j=0; j < info->num; j++) {
2155                                 if (cifaces == NULL) {
2156                                         cifaces = talloc_strdup(info,
2157                                                                 info->ifaces[j].name);
2158                                 } else {
2159                                         cifaces = talloc_asprintf_append(cifaces,
2160                                                                          ",%s",
2161                                                                          info->ifaces[j].name);
2162                                 }
2163
2164                                 if (info->active_idx == j) {
2165                                         aciface = info->ifaces[j].name;
2166                                 }
2167
2168                                 if (info->ifaces[j].link_state == 0) {
2169                                         continue;
2170                                 }
2171
2172                                 if (avifaces == NULL) {
2173                                         avifaces = talloc_strdup(info, info->ifaces[j].name);
2174                                 } else {
2175                                         avifaces = talloc_asprintf_append(avifaces,
2176                                                                           ",%s",
2177                                                                           info->ifaces[j].name);
2178                                 }
2179                         }
2180                 }
2181
2182                 if (options.machinereadable){
2183                         printf(":%s:%d:",
2184                                 ctdb_addr_to_str(&ips->ips[ips->num-i].addr),
2185                                 ips->ips[ips->num-i].pnn);
2186                         if (options.verbose){
2187                                 printf("%s:%s:%s:",
2188                                         aciface?aciface:"",
2189                                         avifaces?avifaces:"",
2190                                         cifaces?cifaces:"");
2191                         }
2192                         printf("\n");
2193                 } else {
2194                         if (options.verbose) {
2195                                 printf("%s node[%d] active[%s] available[%s] configured[%s]\n",
2196                                         ctdb_addr_to_str(&ips->ips[ips->num-i].addr),
2197                                         ips->ips[ips->num-i].pnn,
2198                                         aciface?aciface:"",
2199                                         avifaces?avifaces:"",
2200                                         cifaces?cifaces:"");
2201                         } else {
2202                                 printf("%s %d\n",
2203                                         ctdb_addr_to_str(&ips->ips[ips->num-i].addr),
2204                                         ips->ips[ips->num-i].pnn);
2205                         }
2206                 }
2207                 talloc_free(info);
2208         }
2209
2210         talloc_free(tmp_ctx);
2211         return 0;
2212 }
2213
2214 /*
2215   public ip info
2216  */
2217 static int control_ipinfo(struct ctdb_context *ctdb, int argc, const char **argv)
2218 {
2219         int i, ret;
2220         ctdb_sock_addr addr;
2221         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
2222         struct ctdb_control_public_ip_info *info;
2223
2224         if (argc != 1) {
2225                 talloc_free(tmp_ctx);
2226                 usage();
2227         }
2228
2229         if (parse_ip(argv[0], NULL, 0, &addr) == 0) {
2230                 DEBUG(DEBUG_ERR,("Wrongly formed ip address '%s'\n", argv[0]));
2231                 return -1;
2232         }
2233
2234         /* read the public ip info from this node */
2235         ret = ctdb_ctrl_get_public_ip_info(ctdb, TIMELIMIT(), options.pnn,
2236                                            tmp_ctx, &addr, &info);
2237         if (ret != 0) {
2238                 DEBUG(DEBUG_ERR, ("Unable to get public ip[%s]info from node %u\n",
2239                                   argv[0], options.pnn));
2240                 talloc_free(tmp_ctx);
2241                 return ret;
2242         }
2243
2244         printf("Public IP[%s] info on node %u\n",
2245                ctdb_addr_to_str(&info->ip.addr),
2246                options.pnn);
2247
2248         printf("IP:%s\nCurrentNode:%d\nNumInterfaces:%u\n",
2249                ctdb_addr_to_str(&info->ip.addr),
2250                info->ip.pnn, info->num);
2251
2252         for (i=0; i<info->num; i++) {
2253                 info->ifaces[i].name[CTDB_IFACE_SIZE] = '\0';
2254
2255                 printf("Interface[%u]: Name:%s Link:%s References:%u%s\n",
2256                        i+1, info->ifaces[i].name,
2257                        info->ifaces[i].link_state?"up":"down",
2258                        (unsigned int)info->ifaces[i].references,
2259                        (i==info->active_idx)?" (active)":"");
2260         }
2261
2262         talloc_free(tmp_ctx);
2263         return 0;
2264 }
2265
2266 /*
2267   display interfaces status
2268  */
2269 static int control_ifaces(struct ctdb_context *ctdb, int argc, const char **argv)
2270 {
2271         int i, ret;
2272         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
2273         struct ctdb_control_get_ifaces *ifaces;
2274
2275         /* read the public ip list from this node */
2276         ret = ctdb_ctrl_get_ifaces(ctdb, TIMELIMIT(), options.pnn,
2277                                    tmp_ctx, &ifaces);
2278         if (ret != 0) {
2279                 DEBUG(DEBUG_ERR, ("Unable to get interfaces from node %u\n",
2280                                   options.pnn));
2281                 talloc_free(tmp_ctx);
2282                 return ret;
2283         }
2284
2285         if (options.machinereadable){
2286                 printf(":Name:LinkStatus:References:\n");
2287         } else {
2288                 printf("Interfaces on node %u\n", options.pnn);
2289         }
2290
2291         for (i=0; i<ifaces->num; i++) {
2292                 if (options.machinereadable){
2293                         printf(":%s:%s:%u\n",
2294                                ifaces->ifaces[i].name,
2295                                ifaces->ifaces[i].link_state?"1":"0",
2296                                (unsigned int)ifaces->ifaces[i].references);
2297                 } else {
2298                         printf("name:%s link:%s references:%u\n",
2299                                ifaces->ifaces[i].name,
2300                                ifaces->ifaces[i].link_state?"up":"down",
2301                                (unsigned int)ifaces->ifaces[i].references);
2302                 }
2303         }
2304
2305         talloc_free(tmp_ctx);
2306         return 0;
2307 }
2308
2309
2310 /*
2311   set link status of an interface
2312  */
2313 static int control_setifacelink(struct ctdb_context *ctdb, int argc, const char **argv)
2314 {
2315         int ret;
2316         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
2317         struct ctdb_control_iface_info info;
2318
2319         ZERO_STRUCT(info);
2320
2321         if (argc != 2) {
2322                 usage();
2323         }
2324
2325         if (strlen(argv[0]) > CTDB_IFACE_SIZE) {
2326                 DEBUG(DEBUG_ERR, ("interfaces name '%s' too long\n",
2327                                   argv[0]));
2328                 talloc_free(tmp_ctx);
2329                 return -1;
2330         }
2331         strcpy(info.name, argv[0]);
2332
2333         if (strcmp(argv[1], "up") == 0) {
2334                 info.link_state = 1;
2335         } else if (strcmp(argv[1], "down") == 0) {
2336                 info.link_state = 0;
2337         } else {
2338                 DEBUG(DEBUG_ERR, ("link state invalid '%s' should be 'up' or 'down'\n",
2339                                   argv[1]));
2340                 talloc_free(tmp_ctx);
2341                 return -1;
2342         }
2343
2344         /* read the public ip list from this node */
2345         ret = ctdb_ctrl_set_iface_link(ctdb, TIMELIMIT(), options.pnn,
2346                                    tmp_ctx, &info);
2347         if (ret != 0) {
2348                 DEBUG(DEBUG_ERR, ("Unable to set link state for interfaces %s node %u\n",
2349                                   argv[0], options.pnn));
2350                 talloc_free(tmp_ctx);
2351                 return ret;
2352         }
2353
2354         talloc_free(tmp_ctx);
2355         return 0;
2356 }
2357
2358 /*
2359   display pid of a ctdb daemon
2360  */
2361 static int control_getpid(struct ctdb_context *ctdb, int argc, const char **argv)
2362 {
2363         uint32_t pid;
2364         int ret;
2365
2366         ret = ctdb_ctrl_getpid(ctdb, TIMELIMIT(), options.pnn, &pid);
2367         if (ret != 0) {
2368                 DEBUG(DEBUG_ERR, ("Unable to get daemon pid from node %u\n", options.pnn));
2369                 return ret;
2370         }
2371         printf("Pid:%d\n", pid);
2372
2373         return 0;
2374 }
2375
2376 /*
2377   disable a remote node
2378  */
2379 static int control_disable(struct ctdb_context *ctdb, int argc, const char **argv)
2380 {
2381         int ret;
2382         struct ctdb_node_map *nodemap=NULL;
2383
2384         /* check if the node is already disabled */
2385         if (ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE, ctdb, &nodemap) != 0) {
2386                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from local node\n"));
2387                 exit(10);
2388         }
2389         if (nodemap->nodes[options.pnn].flags & NODE_FLAGS_PERMANENTLY_DISABLED) {
2390                 DEBUG(DEBUG_ERR,("Node %d is already disabled.\n", options.pnn));
2391                 return 0;
2392         }
2393
2394         do {
2395                 ret = ctdb_ctrl_modflags(ctdb, TIMELIMIT(), options.pnn, NODE_FLAGS_PERMANENTLY_DISABLED, 0);
2396                 if (ret != 0) {
2397                         DEBUG(DEBUG_ERR, ("Unable to disable node %u\n", options.pnn));
2398                         return ret;
2399                 }
2400
2401                 sleep(1);
2402
2403                 /* read the nodemap and verify the change took effect */
2404                 if (ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE, ctdb, &nodemap) != 0) {
2405                         DEBUG(DEBUG_ERR, ("Unable to get nodemap from local node\n"));
2406                         exit(10);
2407                 }
2408
2409         } while (!(nodemap->nodes[options.pnn].flags & NODE_FLAGS_PERMANENTLY_DISABLED));
2410         ret = control_ipreallocate(ctdb, argc, argv);
2411         if (ret != 0) {
2412                 DEBUG(DEBUG_ERR, ("IP Reallocate failed on node %u\n", options.pnn));
2413                 return ret;
2414         }
2415
2416         return 0;
2417 }
2418
2419 /*
2420   enable a disabled remote node
2421  */
2422 static int control_enable(struct ctdb_context *ctdb, int argc, const char **argv)
2423 {
2424         int ret;
2425
2426         struct ctdb_node_map *nodemap=NULL;
2427
2428
2429         /* check if the node is already enabled */
2430         if (ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE, ctdb, &nodemap) != 0) {
2431                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from local node\n"));
2432                 exit(10);
2433         }
2434         if (!(nodemap->nodes[options.pnn].flags & NODE_FLAGS_PERMANENTLY_DISABLED)) {
2435                 DEBUG(DEBUG_ERR,("Node %d is already enabled.\n", options.pnn));
2436                 return 0;
2437         }
2438
2439         do {
2440                 ret = ctdb_ctrl_modflags(ctdb, TIMELIMIT(), options.pnn, 0, NODE_FLAGS_PERMANENTLY_DISABLED);
2441                 if (ret != 0) {
2442                         DEBUG(DEBUG_ERR, ("Unable to enable node %u\n", options.pnn));
2443                         return ret;
2444                 }
2445
2446                 sleep(1);
2447
2448                 /* read the nodemap and verify the change took effect */
2449                 if (ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE, ctdb, &nodemap) != 0) {
2450                         DEBUG(DEBUG_ERR, ("Unable to get nodemap from local node\n"));
2451                         exit(10);
2452                 }
2453
2454         } while (nodemap->nodes[options.pnn].flags & NODE_FLAGS_PERMANENTLY_DISABLED);
2455
2456         ret = control_ipreallocate(ctdb, argc, argv);
2457         if (ret != 0) {
2458                 DEBUG(DEBUG_ERR, ("IP Reallocate failed on node %u\n", options.pnn));
2459                 return ret;
2460         }
2461
2462         return 0;
2463 }
2464
2465 /*
2466   stop a remote node
2467  */
2468 static int control_stop(struct ctdb_context *ctdb, int argc, const char **argv)
2469 {
2470         int ret;
2471         struct ctdb_node_map *nodemap=NULL;
2472
2473         do {
2474                 ret = ctdb_ctrl_stop_node(ctdb, TIMELIMIT(), options.pnn);
2475                 if (ret != 0) {
2476                         DEBUG(DEBUG_ERR, ("Unable to stop node %u   try again\n", options.pnn));
2477                 }
2478         
2479                 sleep(1);
2480
2481                 /* read the nodemap and verify the change took effect */
2482                 if (ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE, ctdb, &nodemap) != 0) {
2483                         DEBUG(DEBUG_ERR, ("Unable to get nodemap from local node\n"));
2484                         exit(10);
2485                 }
2486
2487         } while (!(nodemap->nodes[options.pnn].flags & NODE_FLAGS_STOPPED));
2488         ret = control_ipreallocate(ctdb, argc, argv);
2489         if (ret != 0) {
2490                 DEBUG(DEBUG_ERR, ("IP Reallocate failed on node %u\n", options.pnn));
2491                 return ret;
2492         }
2493
2494         return 0;
2495 }
2496
2497 /*
2498   restart a stopped remote node
2499  */
2500 static int control_continue(struct ctdb_context *ctdb, int argc, const char **argv)
2501 {
2502         int ret;
2503
2504         struct ctdb_node_map *nodemap=NULL;
2505
2506         do {
2507                 ret = ctdb_ctrl_continue_node(ctdb, TIMELIMIT(), options.pnn);
2508                 if (ret != 0) {
2509                         DEBUG(DEBUG_ERR, ("Unable to continue node %u\n", options.pnn));
2510                         return ret;
2511                 }
2512         
2513                 sleep(1);
2514
2515                 /* read the nodemap and verify the change took effect */
2516                 if (ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE, ctdb, &nodemap) != 0) {
2517                         DEBUG(DEBUG_ERR, ("Unable to get nodemap from local node\n"));
2518                         exit(10);
2519                 }
2520
2521         } while (nodemap->nodes[options.pnn].flags & NODE_FLAGS_STOPPED);
2522         ret = control_ipreallocate(ctdb, argc, argv);
2523         if (ret != 0) {
2524                 DEBUG(DEBUG_ERR, ("IP Reallocate failed on node %u\n", options.pnn));
2525                 return ret;
2526         }
2527
2528         return 0;
2529 }
2530
2531 static uint32_t get_generation(struct ctdb_context *ctdb)
2532 {
2533         struct ctdb_vnn_map *vnnmap=NULL;
2534         int ret;
2535
2536         /* wait until the recmaster is not in recovery mode */
2537         while (1) {
2538                 uint32_t recmode, recmaster;
2539                 
2540                 if (vnnmap != NULL) {
2541                         talloc_free(vnnmap);
2542                         vnnmap = NULL;
2543                 }
2544
2545                 /* get the recmaster */
2546                 ret = ctdb_ctrl_getrecmaster(ctdb, ctdb, TIMELIMIT(), CTDB_CURRENT_NODE, &recmaster);
2547                 if (ret != 0) {
2548                         DEBUG(DEBUG_ERR, ("Unable to get recmaster from node %u\n", options.pnn));
2549                         exit(10);
2550                 }
2551
2552                 /* get recovery mode */
2553                 ret = ctdb_ctrl_getrecmode(ctdb, ctdb, TIMELIMIT(), recmaster, &recmode);
2554                 if (ret != 0) {
2555                         DEBUG(DEBUG_ERR, ("Unable to get recmode from node %u\n", options.pnn));
2556                         exit(10);
2557                 }
2558
2559                 /* get the current generation number */
2560                 ret = ctdb_ctrl_getvnnmap(ctdb, TIMELIMIT(), recmaster, ctdb, &vnnmap);
2561                 if (ret != 0) {
2562                         DEBUG(DEBUG_ERR, ("Unable to get vnnmap from recmaster (%u)\n", recmaster));
2563                         exit(10);
2564                 }
2565
2566                 if ((recmode == CTDB_RECOVERY_NORMAL)
2567                 &&  (vnnmap->generation != 1)){
2568                         return vnnmap->generation;
2569                 }
2570                 sleep(1);
2571         }
2572 }
2573
2574 /*
2575   ban a node from the cluster
2576  */
2577 static int control_ban(struct ctdb_context *ctdb, int argc, const char **argv)
2578 {
2579         int ret;
2580         struct ctdb_node_map *nodemap=NULL;
2581         struct ctdb_ban_time bantime;
2582
2583         if (argc < 1) {
2584                 usage();
2585         }
2586         
2587         /* verify the node exists */
2588         ret = ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE, ctdb, &nodemap);
2589         if (ret != 0) {
2590                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from local node\n"));
2591                 return ret;
2592         }
2593
2594         if (nodemap->nodes[options.pnn].flags & NODE_FLAGS_BANNED) {
2595                 DEBUG(DEBUG_ERR,("Node %u is already banned.\n", options.pnn));
2596                 return -1;
2597         }
2598
2599         bantime.pnn  = options.pnn;
2600         bantime.time = strtoul(argv[0], NULL, 0);
2601
2602         ret = ctdb_ctrl_set_ban(ctdb, TIMELIMIT(), options.pnn, &bantime);
2603         if (ret != 0) {
2604                 DEBUG(DEBUG_ERR,("Banning node %d for %d seconds failed.\n", bantime.pnn, bantime.time));
2605                 return -1;
2606         }       
2607
2608         ret = control_ipreallocate(ctdb, argc, argv);
2609         if (ret != 0) {
2610                 DEBUG(DEBUG_ERR, ("IP Reallocate failed on node %u\n", options.pnn));
2611                 return ret;
2612         }
2613
2614         return 0;
2615 }
2616
2617
2618 /*
2619   unban a node from the cluster
2620  */
2621 static int control_unban(struct ctdb_context *ctdb, int argc, const char **argv)
2622 {
2623         int ret;
2624         struct ctdb_node_map *nodemap=NULL;
2625         struct ctdb_ban_time bantime;
2626
2627         /* verify the node exists */
2628         ret = ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE, ctdb, &nodemap);
2629         if (ret != 0) {
2630                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from local node\n"));
2631                 return ret;
2632         }
2633
2634         if (!(nodemap->nodes[options.pnn].flags & NODE_FLAGS_BANNED)) {
2635                 DEBUG(DEBUG_ERR,("Node %u is not banned.\n", options.pnn));
2636                 return -1;
2637         }
2638
2639         bantime.pnn  = options.pnn;
2640         bantime.time = 0;
2641
2642         ret = ctdb_ctrl_set_ban(ctdb, TIMELIMIT(), options.pnn, &bantime);
2643         if (ret != 0) {
2644                 DEBUG(DEBUG_ERR,("Unbanning node %d failed.\n", bantime.pnn));
2645                 return -1;
2646         }       
2647
2648         ret = control_ipreallocate(ctdb, argc, argv);
2649         if (ret != 0) {
2650                 DEBUG(DEBUG_ERR, ("IP Reallocate failed on node %u\n", options.pnn));
2651                 return ret;
2652         }
2653
2654         return 0;
2655 }
2656
2657
2658 /*
2659   show ban information for a node
2660  */
2661 static int control_showban(struct ctdb_context *ctdb, int argc, const char **argv)
2662 {
2663         int ret;
2664         struct ctdb_node_map *nodemap=NULL;
2665         struct ctdb_ban_time *bantime;
2666
2667         /* verify the node exists */
2668         ret = ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE, ctdb, &nodemap);
2669         if (ret != 0) {
2670                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from local node\n"));
2671                 return ret;
2672         }
2673
2674         ret = ctdb_ctrl_get_ban(ctdb, TIMELIMIT(), options.pnn, ctdb, &bantime);
2675         if (ret != 0) {
2676                 DEBUG(DEBUG_ERR,("Showing ban info for node %d failed.\n", options.pnn));
2677                 return -1;
2678         }       
2679
2680         if (bantime->time == 0) {
2681                 printf("Node %u is not banned\n", bantime->pnn);
2682         } else {
2683                 printf("Node %u is banned banned for %d seconds\n", bantime->pnn, bantime->time);
2684         }
2685
2686         return 0;
2687 }
2688
2689 /*
2690   shutdown a daemon
2691  */
2692 static int control_shutdown(struct ctdb_context *ctdb, int argc, const char **argv)
2693 {
2694         int ret;
2695
2696         ret = ctdb_ctrl_shutdown(ctdb, TIMELIMIT(), options.pnn);
2697         if (ret != 0) {
2698                 DEBUG(DEBUG_ERR, ("Unable to shutdown node %u\n", options.pnn));
2699                 return ret;
2700         }
2701
2702         return 0;
2703 }
2704
2705 /*
2706   trigger a recovery
2707  */
2708 static int control_recover(struct ctdb_context *ctdb, int argc, const char **argv)
2709 {
2710         int ret;
2711         uint32_t generation, next_generation;
2712
2713         /* record the current generation number */
2714         generation = get_generation(ctdb);
2715
2716         ret = ctdb_ctrl_freeze_priority(ctdb, TIMELIMIT(), options.pnn, 1);
2717         if (ret != 0) {
2718                 DEBUG(DEBUG_ERR, ("Unable to freeze node\n"));
2719                 return ret;
2720         }
2721
2722         ret = ctdb_ctrl_setrecmode(ctdb, TIMELIMIT(), options.pnn, CTDB_RECOVERY_ACTIVE);
2723         if (ret != 0) {
2724                 DEBUG(DEBUG_ERR, ("Unable to set recovery mode\n"));
2725                 return ret;
2726         }
2727
2728         /* wait until we are in a new generation */
2729         while (1) {
2730                 next_generation = get_generation(ctdb);
2731                 if (next_generation != generation) {
2732                         return 0;
2733                 }
2734                 sleep(1);
2735         }
2736
2737         return 0;
2738 }
2739
2740
2741 /*
2742   display monitoring mode of a remote node
2743  */
2744 static int control_getmonmode(struct ctdb_context *ctdb, int argc, const char **argv)
2745 {
2746         uint32_t monmode;
2747         int ret;
2748
2749         ret = ctdb_ctrl_getmonmode(ctdb, TIMELIMIT(), options.pnn, &monmode);
2750         if (ret != 0) {
2751                 DEBUG(DEBUG_ERR, ("Unable to get monmode from node %u\n", options.pnn));
2752                 return ret;
2753         }
2754         if (!options.machinereadable){
2755                 printf("Monitoring mode:%s (%d)\n",monmode==CTDB_MONITORING_ACTIVE?"ACTIVE":"DISABLED",monmode);
2756         } else {
2757                 printf(":mode:\n");
2758                 printf(":%d:\n",monmode);
2759         }
2760         return 0;
2761 }
2762
2763
2764 /*
2765   display capabilities of a remote node
2766  */
2767 static int control_getcapabilities(struct ctdb_context *ctdb, int argc, const char **argv)
2768 {
2769         uint32_t capabilities;
2770         int ret;
2771
2772         ret = ctdb_ctrl_getcapabilities(ctdb, TIMELIMIT(), options.pnn, &capabilities);
2773         if (ret != 0) {
2774                 DEBUG(DEBUG_ERR, ("Unable to get capabilities from node %u\n", options.pnn));
2775                 return ret;
2776         }
2777         
2778         if (!options.machinereadable){
2779                 printf("RECMASTER: %s\n", (capabilities&CTDB_CAP_RECMASTER)?"YES":"NO");
2780                 printf("LMASTER: %s\n", (capabilities&CTDB_CAP_LMASTER)?"YES":"NO");
2781                 printf("LVS: %s\n", (capabilities&CTDB_CAP_LVS)?"YES":"NO");
2782                 printf("NATGW: %s\n", (capabilities&CTDB_CAP_NATGW)?"YES":"NO");
2783         } else {
2784                 printf(":RECMASTER:LMASTER:LVS:NATGW:\n");
2785                 printf(":%d:%d:%d:%d:\n",
2786                         !!(capabilities&CTDB_CAP_RECMASTER),
2787                         !!(capabilities&CTDB_CAP_LMASTER),
2788                         !!(capabilities&CTDB_CAP_LVS),
2789                         !!(capabilities&CTDB_CAP_NATGW));
2790         }
2791         return 0;
2792 }
2793
2794 /*
2795   display lvs configuration
2796  */
2797 static int control_lvs(struct ctdb_context *ctdb, int argc, const char **argv)
2798 {
2799         uint32_t *capabilities;
2800         struct ctdb_node_map *nodemap=NULL;
2801         int i, ret;
2802         int healthy_count = 0;
2803
2804         ret = ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), options.pnn, ctdb, &nodemap);
2805         if (ret != 0) {
2806                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from node %u\n", options.pnn));
2807                 return ret;
2808         }
2809
2810         capabilities = talloc_array(ctdb, uint32_t, nodemap->num);
2811         CTDB_NO_MEMORY(ctdb, capabilities);
2812         
2813         /* collect capabilities for all connected nodes */
2814         for (i=0; i<nodemap->num; i++) {
2815                 if (nodemap->nodes[i].flags & NODE_FLAGS_INACTIVE) {
2816                         continue;
2817                 }
2818                 if (nodemap->nodes[i].flags & NODE_FLAGS_PERMANENTLY_DISABLED) {
2819                         continue;
2820                 }
2821         
2822                 ret = ctdb_ctrl_getcapabilities(ctdb, TIMELIMIT(), i, &capabilities[i]);
2823                 if (ret != 0) {
2824                         DEBUG(DEBUG_ERR, ("Unable to get capabilities from node %u\n", i));
2825                         return ret;
2826                 }
2827
2828                 if (!(capabilities[i] & CTDB_CAP_LVS)) {
2829                         continue;
2830                 }
2831
2832                 if (!(nodemap->nodes[i].flags & NODE_FLAGS_UNHEALTHY)) {
2833                         healthy_count++;
2834                 }
2835         }
2836
2837         /* Print all LVS nodes */
2838         for (i=0; i<nodemap->num; i++) {
2839                 if (nodemap->nodes[i].flags & NODE_FLAGS_INACTIVE) {
2840                         continue;
2841                 }
2842                 if (nodemap->nodes[i].flags & NODE_FLAGS_PERMANENTLY_DISABLED) {
2843                         continue;
2844                 }
2845                 if (!(capabilities[i] & CTDB_CAP_LVS)) {
2846                         continue;
2847                 }
2848
2849                 if (healthy_count != 0) {
2850                         if (nodemap->nodes[i].flags & NODE_FLAGS_UNHEALTHY) {
2851                                 continue;
2852                         }
2853                 }
2854
2855                 printf("%d:%s\n", i, 
2856                         ctdb_addr_to_str(&nodemap->nodes[i].addr));
2857         }
2858
2859         return 0;
2860 }
2861
2862 /*
2863   display who is the lvs master
2864  */
2865 static int control_lvsmaster(struct ctdb_context *ctdb, int argc, const char **argv)
2866 {
2867         uint32_t *capabilities;
2868         struct ctdb_node_map *nodemap=NULL;
2869         int i, ret;
2870         int healthy_count = 0;
2871
2872         ret = ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), options.pnn, ctdb, &nodemap);
2873         if (ret != 0) {
2874                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from node %u\n", options.pnn));
2875                 return ret;
2876         }
2877
2878         capabilities = talloc_array(ctdb, uint32_t, nodemap->num);
2879         CTDB_NO_MEMORY(ctdb, capabilities);
2880         
2881         /* collect capabilities for all connected nodes */
2882         for (i=0; i<nodemap->num; i++) {
2883                 if (nodemap->nodes[i].flags & NODE_FLAGS_INACTIVE) {
2884                         continue;
2885                 }
2886                 if (nodemap->nodes[i].flags & NODE_FLAGS_PERMANENTLY_DISABLED) {
2887                         continue;
2888                 }
2889         
2890                 ret = ctdb_ctrl_getcapabilities(ctdb, TIMELIMIT(), i, &capabilities[i]);
2891                 if (ret != 0) {
2892                         DEBUG(DEBUG_ERR, ("Unable to get capabilities from node %u\n", i));
2893                         return ret;
2894                 }
2895
2896                 if (!(capabilities[i] & CTDB_CAP_LVS)) {
2897                         continue;
2898                 }
2899
2900                 if (!(nodemap->nodes[i].flags & NODE_FLAGS_UNHEALTHY)) {
2901                         healthy_count++;
2902                 }
2903         }
2904
2905         /* find and show the lvsmaster */
2906         for (i=0; i<nodemap->num; i++) {
2907                 if (nodemap->nodes[i].flags & NODE_FLAGS_INACTIVE) {
2908                         continue;
2909                 }
2910                 if (nodemap->nodes[i].flags & NODE_FLAGS_PERMANENTLY_DISABLED) {
2911                         continue;
2912                 }
2913                 if (!(capabilities[i] & CTDB_CAP_LVS)) {
2914                         continue;
2915                 }
2916
2917                 if (healthy_count != 0) {
2918                         if (nodemap->nodes[i].flags & NODE_FLAGS_UNHEALTHY) {
2919                                 continue;
2920                         }
2921                 }
2922
2923                 if (options.machinereadable){
2924                         printf("%d\n", i);
2925                 } else {
2926                         printf("Node %d is LVS master\n", i);
2927                 }
2928                 return 0;
2929         }
2930
2931         printf("There is no LVS master\n");
2932         return -1;
2933 }
2934
2935 /*
2936   disable monitoring on a  node
2937  */
2938 static int control_disable_monmode(struct ctdb_context *ctdb, int argc, const char **argv)
2939 {
2940         
2941         int ret;
2942
2943         ret = ctdb_ctrl_disable_monmode(ctdb, TIMELIMIT(), options.pnn);
2944         if (ret != 0) {
2945                 DEBUG(DEBUG_ERR, ("Unable to disable monmode on node %u\n", options.pnn));
2946                 return ret;
2947         }
2948         printf("Monitoring mode:%s\n","DISABLED");
2949
2950         return 0;
2951 }
2952
2953 /*
2954   enable monitoring on a  node
2955  */
2956 static int control_enable_monmode(struct ctdb_context *ctdb, int argc, const char **argv)
2957 {
2958         
2959         int ret;
2960
2961         ret = ctdb_ctrl_enable_monmode(ctdb, TIMELIMIT(), options.pnn);
2962         if (ret != 0) {
2963                 DEBUG(DEBUG_ERR, ("Unable to enable monmode on node %u\n", options.pnn));
2964                 return ret;
2965         }
2966         printf("Monitoring mode:%s\n","ACTIVE");
2967
2968         return 0;
2969 }
2970
2971 /*
2972   display remote list of keys/data for a db
2973  */
2974 static int control_catdb(struct ctdb_context *ctdb, int argc, const char **argv)
2975 {
2976         const char *db_name;
2977         struct ctdb_db_context *ctdb_db;
2978         int ret;
2979         bool persistent;
2980
2981         if (argc < 1) {
2982                 usage();
2983         }
2984
2985         db_name = argv[0];
2986
2987
2988         if (db_exists(ctdb, db_name, &persistent)) {
2989                 DEBUG(DEBUG_ERR,("Database '%s' does not exist\n", db_name));
2990                 return -1;
2991         }
2992
2993         ctdb_db = ctdb_attach(ctdb, db_name, persistent, 0);
2994
2995         if (ctdb_db == NULL) {
2996                 DEBUG(DEBUG_ERR,("Unable to attach to database '%s'\n", db_name));
2997                 return -1;
2998         }
2999
3000         /* traverse and dump the cluster tdb */
3001         ret = ctdb_dump_db(ctdb_db, stdout);
3002         if (ret == -1) {
3003                 DEBUG(DEBUG_ERR, ("Unable to dump database\n"));
3004                 DEBUG(DEBUG_ERR, ("Maybe try 'ctdb getdbstatus %s'"
3005                                   " and 'ctdb getvar AllowUnhealthyDBRead'\n",
3006                                   db_name));
3007                 return -1;
3008         }
3009         talloc_free(ctdb_db);
3010
3011         printf("Dumped %d records\n", ret);
3012         return 0;
3013 }
3014
3015 /*
3016   display the content of a database key
3017  */
3018 static int control_readkey(struct ctdb_context *ctdb, int argc, const char **argv)
3019 {
3020         const char *db_name;
3021         struct ctdb_db_context *ctdb_db;
3022         struct ctdb_record_handle *h;
3023         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
3024         TDB_DATA key, data;
3025         bool persistent;
3026
3027         if (argc < 2) {
3028                 usage();
3029         }
3030
3031         db_name = argv[0];
3032
3033
3034         if (db_exists(ctdb, db_name, &persistent)) {
3035                 DEBUG(DEBUG_ERR,("Database '%s' does not exist\n", db_name));
3036                 return -1;
3037         }
3038
3039         ctdb_db = ctdb_attach(ctdb, db_name, persistent, 0);
3040
3041         if (ctdb_db == NULL) {
3042                 DEBUG(DEBUG_ERR,("Unable to attach to database '%s'\n", db_name));
3043                 return -1;
3044         }
3045
3046         key.dptr  = discard_const(argv[1]);
3047         key.dsize = strlen((char *)key.dptr);
3048  
3049         h = ctdb_fetch_lock(ctdb_db, tmp_ctx, key, &data);
3050         if (h == NULL) {
3051                 printf("Failed to fetch record '%s' on node %d\n", 
3052                         (const char *)key.dptr, ctdb_get_pnn(ctdb));
3053                 talloc_free(tmp_ctx);
3054                 exit(10);
3055         }
3056
3057         printf("Data: size:%d ptr:[%s]\n", (int)data.dsize, data.dptr);
3058
3059         talloc_free(ctdb_db);
3060         talloc_free(tmp_ctx);
3061         return 0;
3062 }
3063
3064 /*
3065   display the content of a database key
3066  */
3067 static int control_writekey(struct ctdb_context *ctdb, int argc, const char **argv)
3068 {
3069         const char *db_name;
3070         struct ctdb_db_context *ctdb_db;
3071         struct ctdb_record_handle *h;
3072         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
3073         TDB_DATA key, data;
3074         bool persistent;
3075
3076         if (argc < 3) {
3077                 usage();
3078         }
3079
3080         db_name = argv[0];
3081
3082
3083         if (db_exists(ctdb, db_name, &persistent)) {
3084                 DEBUG(DEBUG_ERR,("Database '%s' does not exist\n", db_name));
3085                 return -1;
3086         }
3087
3088         ctdb_db = ctdb_attach(ctdb, db_name, persistent, 0);
3089
3090         if (ctdb_db == NULL) {
3091                 DEBUG(DEBUG_ERR,("Unable to attach to database '%s'\n", db_name));
3092                 return -1;
3093         }
3094
3095         key.dptr  = discard_const(argv[1]);
3096         key.dsize = strlen((char *)key.dptr);
3097  
3098         h = ctdb_fetch_lock(ctdb_db, tmp_ctx, key, &data);
3099         if (h == NULL) {
3100                 printf("Failed to fetch record '%s' on node %d\n", 
3101                         (const char *)key.dptr, ctdb_get_pnn(ctdb));
3102                 talloc_free(tmp_ctx);
3103                 exit(10);
3104         }
3105
3106         data.dptr  = discard_const(argv[2]);
3107         data.dsize = strlen((char *)data.dptr);
3108  
3109         if (ctdb_record_store(h, data) != 0) {
3110                 printf("Failed to store record\n");
3111         }
3112
3113         talloc_free(h);
3114         talloc_free(ctdb_db);
3115         talloc_free(tmp_ctx);
3116         return 0;
3117 }
3118
3119 /*
3120   fetch a record from a persistent database
3121  */
3122 static int control_pfetch(struct ctdb_context *ctdb, int argc, const char **argv)
3123 {
3124         const char *db_name;
3125         struct ctdb_db_context *ctdb_db;
3126         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
3127         struct ctdb_transaction_handle *h;
3128         TDB_DATA key, data;
3129         int fd, ret;
3130         bool persistent;
3131
3132         if (argc < 2) {
3133                 talloc_free(tmp_ctx);
3134                 usage();
3135         }
3136
3137         db_name = argv[0];
3138
3139
3140         if (db_exists(ctdb, db_name, &persistent)) {
3141                 DEBUG(DEBUG_ERR,("Database '%s' does not exist\n", db_name));
3142                 talloc_free(tmp_ctx);
3143                 return -1;
3144         }
3145
3146         if (!persistent) {
3147                 DEBUG(DEBUG_ERR,("Database '%s' is not persistent\n", db_name));
3148                 talloc_free(tmp_ctx);
3149                 return -1;
3150         }
3151
3152         ctdb_db = ctdb_attach(ctdb, db_name, persistent, 0);
3153
3154         if (ctdb_db == NULL) {
3155                 DEBUG(DEBUG_ERR,("Unable to attach to database '%s'\n", db_name));
3156                 talloc_free(tmp_ctx);
3157                 return -1;
3158         }
3159
3160         h = ctdb_transaction_start(ctdb_db, tmp_ctx);
3161         if (h == NULL) {
3162                 DEBUG(DEBUG_ERR,("Failed to start transaction on database %s\n", db_name));
3163                 talloc_free(tmp_ctx);
3164                 return -1;
3165         }
3166
3167         key.dptr  = discard_const(argv[1]);
3168         key.dsize = strlen(argv[1]);
3169         ret = ctdb_transaction_fetch(h, tmp_ctx, key, &data);
3170         if (ret != 0) {
3171                 DEBUG(DEBUG_ERR,("Failed to fetch record\n"));
3172                 talloc_free(tmp_ctx);
3173                 return -1;
3174         }
3175
3176         if (data.dsize == 0 || data.dptr == NULL) {
3177                 DEBUG(DEBUG_ERR,("Record is empty\n"));
3178                 talloc_free(tmp_ctx);
3179                 return -1;
3180         }
3181
3182         if (argc == 3) {
3183           fd = open(argv[2], O_WRONLY|O_CREAT|O_TRUNC, 0600);
3184                 if (fd == -1) {
3185                         DEBUG(DEBUG_ERR,("Failed to open output file %s\n", argv[2]));
3186                         talloc_free(tmp_ctx);
3187                         return -1;
3188                 }
3189                 write(fd, data.dptr, data.dsize);
3190                 close(fd);
3191         } else {
3192                 write(1, data.dptr, data.dsize);
3193         }
3194
3195         /* abort the transaction */
3196         talloc_free(h);
3197
3198
3199         talloc_free(tmp_ctx);
3200         return 0;
3201 }
3202
3203 /*
3204   fetch a record from a tdb-file
3205  */
3206 static int control_tfetch(struct ctdb_context *ctdb, int argc, const char **argv)
3207 {
3208         const char *tdb_file;
3209         TDB_CONTEXT *tdb;
3210         TDB_DATA key, data;
3211         int fd;
3212
3213         if (argc < 2) {
3214                 usage();
3215         }
3216
3217         tdb_file = argv[0];
3218
3219         tdb = tdb_open(tdb_file, 0, 0, O_RDONLY, 0);
3220         if (tdb == NULL) {
3221                 DEBUG(DEBUG_ERR,("Failed to open TDB file %s\n", tdb_file));
3222                 return -1;
3223         }
3224
3225         key.dptr  = discard_const(argv[1]);
3226         key.dsize = strlen(argv[1]);
3227         data = tdb_fetch(tdb, key);
3228         if (data.dptr == NULL || data.dsize < sizeof(struct ctdb_ltdb_header)) {
3229                 DEBUG(DEBUG_ERR,("Failed to read record %s from tdb %s\n", argv[1], tdb_file));
3230                 tdb_close(tdb);
3231                 return -1;
3232         }
3233
3234         tdb_close(tdb);
3235
3236         if (argc == 3) {
3237           fd = open(argv[2], O_WRONLY|O_CREAT|O_TRUNC, 0600);
3238                 if (fd == -1) {
3239                         DEBUG(DEBUG_ERR,("Failed to open output file %s\n", argv[2]));
3240                         return -1;
3241                 }
3242                 write(fd, data.dptr+sizeof(struct ctdb_ltdb_header), data.dsize-sizeof(struct ctdb_ltdb_header));
3243                 close(fd);
3244         } else {
3245                 write(1, data.dptr+sizeof(struct ctdb_ltdb_header), data.dsize-sizeof(struct ctdb_ltdb_header));
3246         }
3247
3248         return 0;
3249 }
3250
3251 /*
3252   write a record to a persistent database
3253  */
3254 static int control_pstore(struct ctdb_context *ctdb, int argc, const char **argv)
3255 {
3256         const char *db_name;
3257         struct ctdb_db_context *ctdb_db;
3258         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
3259         struct ctdb_transaction_handle *h;
3260         struct stat st;
3261         TDB_DATA key, data;
3262         int fd, ret;
3263
3264         if (argc < 3) {
3265                 talloc_free(tmp_ctx);
3266                 usage();
3267         }
3268
3269         fd = open(argv[2], O_RDONLY);
3270         if (fd == -1) {
3271                 DEBUG(DEBUG_ERR,("Failed to open file containing record data : %s  %s\n", argv[2], strerror(errno)));
3272                 talloc_free(tmp_ctx);
3273                 return -1;
3274         }
3275         
3276         ret = fstat(fd, &st);
3277         if (ret == -1) {
3278                 DEBUG(DEBUG_ERR,("fstat of file %s failed: %s\n", argv[2], strerror(errno)));
3279                 close(fd);
3280                 talloc_free(tmp_ctx);
3281                 return -1;
3282         }
3283
3284         if (!S_ISREG(st.st_mode)) {
3285                 DEBUG(DEBUG_ERR,("Not a regular file %s\n", argv[2]));
3286                 close(fd);
3287                 talloc_free(tmp_ctx);
3288                 return -1;
3289         }
3290
3291         data.dsize = st.st_size;
3292         if (data.dsize == 0) {
3293                 data.dptr  = NULL;
3294         } else {
3295                 data.dptr = talloc_size(tmp_ctx, data.dsize);
3296                 if (data.dptr == NULL) {
3297                         DEBUG(DEBUG_ERR,("Failed to talloc %d of memory to store record data\n", (int)data.dsize));
3298                         close(fd);
3299                         talloc_free(tmp_ctx);
3300                         return -1;
3301                 }
3302                 ret = read(fd, data.dptr, data.dsize);
3303                 if (ret != data.dsize) {
3304                         DEBUG(DEBUG_ERR,("Failed to read %d bytes of record data\n", (int)data.dsize));
3305                         close(fd);
3306                         talloc_free(tmp_ctx);
3307                         return -1;
3308                 }
3309         }
3310         close(fd);
3311
3312
3313         db_name = argv[0];
3314
3315         ctdb_db = ctdb_attach(ctdb, db_name, true, 0);
3316
3317         if (ctdb_db == NULL) {
3318                 DEBUG(DEBUG_ERR,("Unable to attach to database '%s'\n", db_name));
3319                 talloc_free(tmp_ctx);
3320                 return -1;
3321         }
3322
3323         h = ctdb_transaction_start(ctdb_db, tmp_ctx);
3324         if (h == NULL) {
3325                 DEBUG(DEBUG_ERR,("Failed to start transaction on database %s\n", db_name));
3326                 talloc_free(tmp_ctx);
3327                 return -1;
3328         }
3329
3330         key.dptr  = discard_const(argv[1]);
3331         key.dsize = strlen(argv[1]);
3332         ret = ctdb_transaction_store(h, key, data);
3333         if (ret != 0) {
3334                 DEBUG(DEBUG_ERR,("Failed to store record\n"));
3335                 talloc_free(tmp_ctx);
3336                 return -1;
3337         }
3338
3339         ret = ctdb_transaction_commit(h);
3340         if (ret != 0) {
3341                 DEBUG(DEBUG_ERR,("Failed to commit transaction\n"));
3342                 talloc_free(tmp_ctx);
3343                 return -1;
3344         }
3345
3346
3347         talloc_free(tmp_ctx);
3348         return 0;
3349 }
3350
3351 /*
3352   check if a service is bound to a port or not
3353  */
3354 static int control_chktcpport(struct ctdb_context *ctdb, int argc, const char **argv)
3355 {
3356         int s, ret;
3357         unsigned v;
3358         int port;
3359         struct sockaddr_in sin;
3360
3361         if (argc != 1) {
3362                 printf("Use: ctdb chktcport <port>\n");
3363                 return EINVAL;
3364         }
3365
3366         port = atoi(argv[0]);
3367
3368         s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
3369         if (s == -1) {
3370                 printf("Failed to open local socket\n");
3371                 return errno;
3372         }
3373
3374         v = fcntl(s, F_GETFL, 0);
3375         fcntl(s, F_SETFL, v | O_NONBLOCK);
3376
3377         bzero(&sin, sizeof(sin));
3378         sin.sin_family = PF_INET;
3379         sin.sin_port   = htons(port);
3380         ret = bind(s, (struct sockaddr *)&sin, sizeof(sin));
3381         close(s);
3382         if (ret == -1) {
3383                 printf("Failed to bind to local socket: %d %s\n", errno, strerror(errno));
3384                 return errno;
3385         }
3386
3387         return 0;
3388 }
3389
3390
3391
3392 static void log_handler(struct ctdb_context *ctdb, uint64_t srvid, 
3393                              TDB_DATA data, void *private_data)
3394 {
3395         DEBUG(DEBUG_ERR,("Log data received\n"));
3396         if (data.dsize > 0) {
3397                 printf("%s", data.dptr);
3398         }
3399
3400         exit(0);
3401 }
3402
3403 /*
3404   display a list of log messages from the in memory ringbuffer
3405  */
3406 static int control_getlog(struct ctdb_context *ctdb, int argc, const char **argv)
3407 {
3408         int ret;
3409         int32_t res;
3410         struct ctdb_get_log_addr log_addr;
3411         TDB_DATA data;
3412         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
3413         char *errmsg;
3414         struct timeval tv;
3415
3416         if (argc != 1) {
3417                 DEBUG(DEBUG_ERR,("Invalid arguments\n"));
3418                 talloc_free(tmp_ctx);
3419                 return -1;
3420         }
3421
3422         log_addr.pnn = ctdb_ctrl_getpnn(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE);
3423         log_addr.srvid = getpid();
3424         if (isalpha(argv[0][0]) || argv[0][0] == '-') { 
3425                 log_addr.level = get_debug_by_desc(argv[0]);
3426         } else {
3427                 log_addr.level = strtol(argv[0], NULL, 0);
3428         }
3429
3430
3431         data.dptr = (unsigned char *)&log_addr;
3432         data.dsize = sizeof(log_addr);
3433
3434         DEBUG(DEBUG_ERR, ("Pulling logs from node %u\n", options.pnn));
3435
3436         ctdb_client_set_message_handler(ctdb, log_addr.srvid, log_handler, NULL);
3437         sleep(1);
3438
3439         DEBUG(DEBUG_ERR,("Listen for response on %d\n", (int)log_addr.srvid));
3440
3441         ret = ctdb_control(ctdb, options.pnn, 0, CTDB_CONTROL_GET_LOG,
3442                            0, data, tmp_ctx, NULL, &res, NULL, &errmsg);
3443         if (ret != 0 || res != 0) {
3444                 DEBUG(DEBUG_ERR,("Failed to get logs - %s\n", errmsg));
3445                 talloc_free(tmp_ctx);
3446                 return -1;
3447         }
3448
3449
3450         tv = timeval_current();
3451         /* this loop will terminate when we have received the reply */
3452         while (timeval_elapsed(&tv) < 3.0) {    
3453                 event_loop_once(ctdb->ev);
3454         }
3455
3456         DEBUG(DEBUG_INFO,("Timed out waiting for log data.\n"));
3457
3458         talloc_free(tmp_ctx);
3459         return 0;
3460 }
3461
3462 /*
3463   clear the in memory log area
3464  */
3465 static int control_clearlog(struct ctdb_context *ctdb, int argc, const char **argv)
3466 {
3467         int ret;
3468         int32_t res;
3469         char *errmsg;
3470         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
3471
3472         ret = ctdb_control(ctdb, options.pnn, 0, CTDB_CONTROL_CLEAR_LOG,
3473                            0, tdb_null, tmp_ctx, NULL, &res, NULL, &errmsg);
3474         if (ret != 0 || res != 0) {
3475                 DEBUG(DEBUG_ERR,("Failed to clear logs\n"));
3476                 talloc_free(tmp_ctx);
3477                 return -1;
3478         }
3479
3480         talloc_free(tmp_ctx);
3481         return 0;
3482 }
3483
3484
3485
3486 /*
3487   display a list of the databases on a remote ctdb
3488  */
3489 static int control_getdbmap(struct ctdb_context *ctdb, int argc, const char **argv)
3490 {
3491         int i, ret;
3492         struct ctdb_dbid_map *dbmap=NULL;
3493
3494         ret = ctdb_ctrl_getdbmap(ctdb, TIMELIMIT(), options.pnn, ctdb, &dbmap);
3495         if (ret != 0) {
3496                 DEBUG(DEBUG_ERR, ("Unable to get dbids from node %u\n", options.pnn));
3497                 return ret;
3498         }
3499
3500         if(options.machinereadable){
3501                 printf(":ID:Name:Path:Persistent:Unhealthy:\n");
3502                 for(i=0;i<dbmap->num;i++){
3503                         const char *path;
3504                         const char *name;
3505                         const char *health;
3506                         bool persistent;
3507
3508                         ctdb_ctrl_getdbpath(ctdb, TIMELIMIT(), options.pnn,
3509                                             dbmap->dbs[i].dbid, ctdb, &path);
3510                         ctdb_ctrl_getdbname(ctdb, TIMELIMIT(), options.pnn,
3511                                             dbmap->dbs[i].dbid, ctdb, &name);
3512                         ctdb_ctrl_getdbhealth(ctdb, TIMELIMIT(), options.pnn,
3513                                               dbmap->dbs[i].dbid, ctdb, &health);
3514                         persistent = dbmap->dbs[i].persistent;
3515                         printf(":0x%08X:%s:%s:%d:%d:\n",
3516                                dbmap->dbs[i].dbid, name, path,
3517                                !!(persistent), !!(health));
3518                 }
3519                 return 0;
3520         }
3521
3522         printf("Number of databases:%d\n", dbmap->num);
3523         for(i=0;i<dbmap->num;i++){
3524                 const char *path;
3525                 const char *name;
3526                 const char *health;
3527                 bool persistent;
3528
3529                 ctdb_ctrl_getdbpath(ctdb, TIMELIMIT(), options.pnn, dbmap->dbs[i].dbid, ctdb, &path);
3530                 ctdb_ctrl_getdbname(ctdb, TIMELIMIT(), options.pnn, dbmap->dbs[i].dbid, ctdb, &name);
3531                 ctdb_ctrl_getdbhealth(ctdb, TIMELIMIT(), options.pnn, dbmap->dbs[i].dbid, ctdb, &health);
3532                 persistent = dbmap->dbs[i].persistent;
3533                 printf("dbid:0x%08x name:%s path:%s%s%s\n",
3534                        dbmap->dbs[i].dbid, name, path,
3535                        persistent?" PERSISTENT":"",
3536                        health?" UNHEALTHY":"");
3537         }
3538
3539         return 0;
3540 }
3541
3542 /*
3543   display the status of a database on a remote ctdb
3544  */
3545 static int control_getdbstatus(struct ctdb_context *ctdb, int argc, const char **argv)
3546 {
3547         int i, ret;
3548         struct ctdb_dbid_map *dbmap=NULL;
3549         const char *db_name;
3550
3551         if (argc < 1) {
3552                 usage();
3553         }
3554
3555         db_name = argv[0];
3556
3557         ret = ctdb_ctrl_getdbmap(ctdb, TIMELIMIT(), options.pnn, ctdb, &dbmap);
3558         if (ret != 0) {
3559                 DEBUG(DEBUG_ERR, ("Unable to get dbids from node %u\n", options.pnn));
3560                 return ret;
3561         }
3562
3563         for(i=0;i<dbmap->num;i++){
3564                 const char *path;
3565                 const char *name;
3566                 const char *health;
3567                 bool persistent;
3568
3569                 ctdb_ctrl_getdbname(ctdb, TIMELIMIT(), options.pnn, dbmap->dbs[i].dbid, ctdb, &name);
3570                 if (strcmp(name, db_name) != 0) {
3571                         continue;
3572                 }
3573
3574                 ctdb_ctrl_getdbpath(ctdb, TIMELIMIT(), options.pnn, dbmap->dbs[i].dbid, ctdb, &path);
3575                 ctdb_ctrl_getdbhealth(ctdb, TIMELIMIT(), options.pnn, dbmap->dbs[i].dbid, ctdb, &health);
3576                 persistent = dbmap->dbs[i].persistent;
3577                 printf("dbid: 0x%08x\nname: %s\npath: %s\nPERSISTENT: %s\nHEALTH: %s\n",
3578                        dbmap->dbs[i].dbid, name, path,
3579                        persistent?"yes":"no",
3580                        health?health:"OK");
3581                 return 0;
3582         }
3583
3584         DEBUG(DEBUG_ERR, ("db %s doesn't exist on node %u\n", db_name, options.pnn));
3585         return 0;
3586 }
3587
3588 /*
3589   check if the local node is recmaster or not
3590   it will return 1 if this node is the recmaster and 0 if it is not
3591   or if the local ctdb daemon could not be contacted
3592  */
3593 static int control_isnotrecmaster(struct ctdb_context *ctdb, int argc, const char **argv)
3594 {
3595         uint32_t mypnn, recmaster;
3596         int ret;
3597
3598         mypnn = ctdb_ctrl_getpnn(ctdb, TIMELIMIT(), options.pnn);
3599         if (mypnn == -1) {
3600                 printf("Failed to get pnn of node\n");
3601                 return 1;
3602         }
3603
3604         ret = ctdb_ctrl_getrecmaster(ctdb, ctdb, TIMELIMIT(), options.pnn, &recmaster);
3605         if (ret != 0) {
3606                 printf("Failed to get the recmaster\n");
3607                 return 1;
3608         }
3609
3610         if (recmaster != mypnn) {
3611                 printf("this node is not the recmaster\n");
3612                 return 1;
3613         }
3614
3615         printf("this node is the recmaster\n");
3616         return 0;
3617 }
3618
3619 /*
3620   ping a node
3621  */
3622 static int control_ping(struct ctdb_context *ctdb, int argc, const char **argv)
3623 {
3624         int ret;
3625         struct timeval tv = timeval_current();
3626         ret = ctdb_ctrl_ping(ctdb, options.pnn);
3627         if (ret == -1) {
3628                 printf("Unable to get ping response from node %u\n", options.pnn);
3629                 return -1;
3630         } else {
3631                 printf("response from %u time=%.6f sec  (%d clients)\n", 
3632                        options.pnn, timeval_elapsed(&tv), ret);
3633         }
3634         return 0;
3635 }
3636
3637
3638 /*
3639   get a tunable
3640  */
3641 static int control_getvar(struct ctdb_context *ctdb, int argc, const char **argv)
3642 {
3643         const char *name;
3644         uint32_t value;
3645         int ret;
3646
3647         if (argc < 1) {
3648                 usage();
3649         }
3650
3651         name = argv[0];
3652         ret = ctdb_ctrl_get_tunable(ctdb, TIMELIMIT(), options.pnn, name, &value);
3653         if (ret == -1) {
3654                 DEBUG(DEBUG_ERR, ("Unable to get tunable variable '%s'\n", name));
3655                 return -1;
3656         }
3657
3658         printf("%-19s = %u\n", name, value);
3659         return 0;
3660 }
3661
3662 /*
3663   set a tunable
3664  */
3665 static int control_setvar(struct ctdb_context *ctdb, int argc, const char **argv)
3666 {
3667         const char *name;
3668         uint32_t value;
3669         int ret;
3670
3671         if (argc < 2) {
3672                 usage();
3673         }
3674
3675         name = argv[0];
3676         value = strtoul(argv[1], NULL, 0);
3677
3678         ret = ctdb_ctrl_set_tunable(ctdb, TIMELIMIT(), options.pnn, name, value);
3679         if (ret == -1) {
3680                 DEBUG(DEBUG_ERR, ("Unable to set tunable variable '%s'\n", name));
3681                 return -1;
3682         }
3683         return 0;
3684 }
3685
3686 /*
3687   list all tunables
3688  */
3689 static int control_listvars(struct ctdb_context *ctdb, int argc, const char **argv)
3690 {
3691         uint32_t count;
3692         const char **list;
3693         int ret, i;
3694
3695         ret = ctdb_ctrl_list_tunables(ctdb, TIMELIMIT(), options.pnn, ctdb, &list, &count);
3696         if (ret == -1) {
3697                 DEBUG(DEBUG_ERR, ("Unable to list tunable variables\n"));
3698                 return -1;
3699         }
3700
3701         for (i=0;i<count;i++) {
3702                 control_getvar(ctdb, 1, &list[i]);
3703         }
3704
3705         talloc_free(list);
3706         
3707         return 0;
3708 }
3709
3710 /*
3711   display debug level on a node
3712  */
3713 static int control_getdebug(struct ctdb_context *ctdb, int argc, const char **argv)
3714 {
3715         int ret;
3716         int32_t level;
3717
3718         ret = ctdb_ctrl_get_debuglevel(ctdb, options.pnn, &level);
3719         if (ret != 0) {
3720                 DEBUG(DEBUG_ERR, ("Unable to get debuglevel response from node %u\n", options.pnn));
3721                 return ret;
3722         } else {
3723                 if (options.machinereadable){
3724                         printf(":Name:Level:\n");
3725                         printf(":%s:%d:\n",get_debug_by_level(level),level);
3726                 } else {
3727                         printf("Node %u is at debug level %s (%d)\n", options.pnn, get_debug_by_level(level), level);
3728                 }
3729         }
3730         return 0;
3731 }
3732
3733 /*
3734   display reclock file of a node
3735  */
3736 static int control_getreclock(struct ctdb_context *ctdb, int argc, const char **argv)
3737 {
3738         int ret;
3739         const char *reclock;
3740
3741         ret = ctdb_ctrl_getreclock(ctdb, TIMELIMIT(), options.pnn, ctdb, &reclock);
3742         if (ret != 0) {
3743                 DEBUG(DEBUG_ERR, ("Unable to get reclock file from node %u\n", options.pnn));
3744                 return ret;
3745         } else {
3746                 if (options.machinereadable){
3747                         if (reclock != NULL) {
3748                                 printf("%s", reclock);
3749                         }
3750                 } else {
3751                         if (reclock == NULL) {
3752                                 printf("No reclock file used.\n");
3753                         } else {
3754                                 printf("Reclock file:%s\n", reclock);
3755                         }
3756                 }
3757         }
3758         return 0;
3759 }
3760
3761 /*
3762   set the reclock file of a node
3763  */
3764 static int control_setreclock(struct ctdb_context *ctdb, int argc, const char **argv)
3765 {
3766         int ret;
3767         const char *reclock;
3768
3769         if (argc == 0) {
3770                 reclock = NULL;
3771         } else if (argc == 1) {
3772                 reclock = argv[0];
3773         } else {
3774                 usage();
3775         }
3776
3777         ret = ctdb_ctrl_setreclock(ctdb, TIMELIMIT(), options.pnn, reclock);
3778         if (ret != 0) {
3779                 DEBUG(DEBUG_ERR, ("Unable to get reclock file from node %u\n", options.pnn));
3780                 return ret;
3781         }
3782         return 0;
3783 }
3784
3785 /*
3786   set the natgw state on/off
3787  */
3788 static int control_setnatgwstate(struct ctdb_context *ctdb, int argc, const char **argv)
3789 {
3790         int ret;
3791         uint32_t natgwstate;
3792
3793         if (argc == 0) {
3794                 usage();
3795         }
3796
3797         if (!strcmp(argv[0], "on")) {
3798                 natgwstate = 1;
3799         } else if (!strcmp(argv[0], "off")) {
3800                 natgwstate = 0;
3801         } else {
3802                 usage();
3803         }
3804
3805         ret = ctdb_ctrl_setnatgwstate(ctdb, TIMELIMIT(), options.pnn, natgwstate);
3806         if (ret != 0) {
3807                 DEBUG(DEBUG_ERR, ("Unable to set the natgw state for node %u\n", options.pnn));
3808                 return ret;
3809         }
3810
3811         return 0;
3812 }
3813
3814 /*
3815   set the lmaster role on/off
3816  */
3817 static int control_setlmasterrole(struct ctdb_context *ctdb, int argc, const char **argv)
3818 {
3819         int ret;
3820         uint32_t lmasterrole;
3821
3822         if (argc == 0) {
3823                 usage();
3824         }
3825
3826         if (!strcmp(argv[0], "on")) {
3827                 lmasterrole = 1;
3828         } else if (!strcmp(argv[0], "off")) {
3829                 lmasterrole = 0;
3830         } else {
3831                 usage();
3832         }
3833
3834         ret = ctdb_ctrl_setlmasterrole(ctdb, TIMELIMIT(), options.pnn, lmasterrole);
3835         if (ret != 0) {
3836                 DEBUG(DEBUG_ERR, ("Unable to set the lmaster role for node %u\n", options.pnn));
3837                 return ret;
3838         }
3839
3840         return 0;
3841 }
3842
3843 /*
3844   set the recmaster role on/off
3845  */
3846 static int control_setrecmasterrole(struct ctdb_context *ctdb, int argc, const char **argv)
3847 {
3848         int ret;
3849         uint32_t recmasterrole;
3850
3851         if (argc == 0) {
3852                 usage();
3853         }
3854
3855         if (!strcmp(argv[0], "on")) {
3856                 recmasterrole = 1;
3857         } else if (!strcmp(argv[0], "off")) {
3858                 recmasterrole = 0;
3859         } else {
3860                 usage();
3861         }
3862
3863         ret = ctdb_ctrl_setrecmasterrole(ctdb, TIMELIMIT(), options.pnn, recmasterrole);
3864         if (ret != 0) {
3865                 DEBUG(DEBUG_ERR, ("Unable to set the recmaster role for node %u\n", options.pnn));
3866                 return ret;
3867         }
3868
3869         return 0;
3870 }
3871
3872 /*
3873   set debug level on a node or all nodes
3874  */
3875 static int control_setdebug(struct ctdb_context *ctdb, int argc, const char **argv)
3876 {
3877         int i, ret;
3878         int32_t level;
3879
3880         if (argc == 0) {
3881                 printf("You must specify the debug level. Valid levels are:\n");
3882                 for (i=0; debug_levels[i].description != NULL; i++) {
3883                         printf("%s (%d)\n", debug_levels[i].description, debug_levels[i].level);
3884                 }
3885
3886                 return 0;
3887         }
3888
3889         if (isalpha(argv[0][0]) || argv[0][0] == '-') { 
3890                 level = get_debug_by_desc(argv[0]);
3891         } else {
3892                 level = strtol(argv[0], NULL, 0);
3893         }
3894
3895         for (i=0; debug_levels[i].description != NULL; i++) {
3896                 if (level == debug_levels[i].level) {
3897                         break;
3898                 }
3899         }
3900         if (debug_levels[i].description == NULL) {
3901                 printf("Invalid debug level, must be one of\n");
3902                 for (i=0; debug_levels[i].description != NULL; i++) {
3903                         printf("%s (%d)\n", debug_levels[i].description, debug_levels[i].level);
3904                 }
3905                 return -1;
3906         }
3907
3908         ret = ctdb_ctrl_set_debuglevel(ctdb, options.pnn, level);
3909         if (ret != 0) {
3910                 DEBUG(DEBUG_ERR, ("Unable to set debug level on node %u\n", options.pnn));
3911         }
3912         return 0;
3913 }
3914
3915
3916 /*
3917   thaw a node
3918  */
3919 static int control_thaw(struct ctdb_context *ctdb, int argc, const char **argv)
3920 {
3921         int ret;
3922         uint32_t priority;
3923         
3924         if (argc == 1) {
3925                 priority = strtol(argv[0], NULL, 0);
3926         } else {
3927                 priority = 0;
3928         }
3929         DEBUG(DEBUG_ERR,("Thaw by priority %u\n", priority));
3930
3931         ret = ctdb_ctrl_thaw_priority(ctdb, TIMELIMIT(), options.pnn, priority);
3932         if (ret != 0) {
3933                 DEBUG(DEBUG_ERR, ("Unable to thaw node %u\n", options.pnn));
3934         }               
3935         return 0;
3936 }
3937
3938
3939 /*
3940   attach to a database
3941  */
3942 static int control_attach(struct ctdb_context *ctdb, int argc, const char **argv)
3943 {
3944         const char *db_name;
3945         struct ctdb_db_context *ctdb_db;
3946         bool persistent = false;
3947
3948         if (argc < 1) {
3949                 usage();
3950         }
3951         db_name = argv[0];
3952         if (argc > 2) {
3953                 usage();
3954         }
3955         if (argc == 2) {
3956                 if (strcmp(argv[1], "persistent") != 0) {
3957                         usage();
3958                 }
3959                 persistent = true;
3960         }
3961
3962         ctdb_db = ctdb_attach(ctdb, db_name, persistent, 0);
3963         if (ctdb_db == NULL) {
3964                 DEBUG(DEBUG_ERR,("Unable to attach to database '%s'\n", db_name));
3965                 return -1;
3966         }
3967
3968         return 0;
3969 }
3970
3971 /*
3972   set db priority
3973  */
3974 static int control_setdbprio(struct ctdb_context *ctdb, int argc, const char **argv)
3975 {
3976         struct ctdb_db_priority db_prio;
3977         int ret;
3978
3979         if (argc < 2) {
3980                 usage();
3981         }
3982
3983         db_prio.db_id    = strtoul(argv[0], NULL, 0);
3984         db_prio.priority = strtoul(argv[1], NULL, 0);
3985
3986         ret = ctdb_ctrl_set_db_priority(ctdb, TIMELIMIT(), options.pnn, &db_prio);
3987         if (ret != 0) {
3988                 DEBUG(DEBUG_ERR,("Unable to set db prio\n"));
3989                 return -1;
3990         }
3991
3992         return 0;
3993 }
3994
3995 /*
3996   get db priority
3997  */
3998 static int control_getdbprio(struct ctdb_context *ctdb, int argc, const char **argv)
3999 {
4000         uint32_t db_id, priority;
4001         int ret;
4002
4003         if (argc < 1) {
4004                 usage();
4005         }
4006
4007         db_id = strtoul(argv[0], NULL, 0);
4008
4009         ret = ctdb_ctrl_get_db_priority(ctdb, TIMELIMIT(), options.pnn, db_id, &priority);
4010         if (ret != 0) {
4011                 DEBUG(DEBUG_ERR,("Unable to get db prio\n"));
4012                 return -1;
4013         }
4014
4015         DEBUG(DEBUG_ERR,("Priority:%u\n", priority));
4016
4017         return 0;
4018 }
4019
4020 /*
4021   run an eventscript on a node
4022  */
4023 static int control_eventscript(struct ctdb_context *ctdb, int argc, const char **argv)
4024 {
4025         TDB_DATA data;
4026         int ret;
4027         int32_t res;
4028         char *errmsg;
4029         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
4030
4031         if (argc != 1) {
4032                 DEBUG(DEBUG_ERR,("Invalid arguments\n"));
4033                 return -1;
4034         }
4035
4036         data.dptr = (unsigned char *)discard_const(argv[0]);
4037         data.dsize = strlen((char *)data.dptr) + 1;
4038
4039         DEBUG(DEBUG_ERR, ("Running eventscripts with arguments \"%s\" on node %u\n", data.dptr, options.pnn));
4040
4041         ret = ctdb_control(ctdb, options.pnn, 0, CTDB_CONTROL_RUN_EVENTSCRIPTS,
4042                            0, data, tmp_ctx, NULL, &res, NULL, &errmsg);
4043         if (ret != 0 || res != 0) {
4044                 DEBUG(DEBUG_ERR,("Failed to run eventscripts - %s\n", errmsg));
4045                 talloc_free(tmp_ctx);
4046                 return -1;
4047         }
4048         talloc_free(tmp_ctx);
4049         return 0;
4050 }
4051
4052 #define DB_VERSION 1
4053 #define MAX_DB_NAME 64
4054 struct db_file_header {
4055         unsigned long version;
4056         time_t timestamp;
4057         unsigned long persistent;
4058         unsigned long size;
4059         const char name[MAX_DB_NAME];
4060 };
4061
4062 struct backup_data {
4063         struct ctdb_marshall_buffer *records;
4064         uint32_t len;
4065         uint32_t total;
4066         bool traverse_error;
4067 };
4068
4069 static int backup_traverse(struct tdb_context *tdb, TDB_DATA key, TDB_DATA data, void *private)
4070 {
4071         struct backup_data *bd = talloc_get_type(private, struct backup_data);
4072         struct ctdb_rec_data *rec;
4073
4074         /* add the record */
4075         rec = ctdb_marshall_record(bd->records, 0, key, NULL, data);
4076         if (rec == NULL) {
4077                 bd->traverse_error = true;
4078                 DEBUG(DEBUG_ERR,("Failed to marshall record\n"));
4079                 return -1;
4080         }
4081         bd->records = talloc_realloc_size(NULL, bd->records, rec->length + bd->len);
4082         if (bd->records == NULL) {
4083                 DEBUG(DEBUG_ERR,("Failed to expand marshalling buffer\n"));
4084                 bd->traverse_error = true;
4085                 return -1;
4086         }
4087         bd->records->count++;
4088         memcpy(bd->len+(uint8_t *)bd->records, rec, rec->length);
4089         bd->len += rec->length;
4090         talloc_free(rec);
4091
4092         bd->total++;
4093         return 0;
4094 }
4095
4096 /*
4097  * backup a database to a file 
4098  */
4099 static int control_backupdb(struct ctdb_context *ctdb, int argc, const char **argv)
4100 {
4101         int i, ret;
4102         struct ctdb_dbid_map *dbmap=NULL;
4103         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
4104         struct db_file_header dbhdr;
4105         struct ctdb_db_context *ctdb_db;
4106         struct backup_data *bd;
4107         int fh = -1;
4108         int status = -1;
4109         const char *reason = NULL;
4110
4111         if (argc != 2) {
4112                 DEBUG(DEBUG_ERR,("Invalid arguments\n"));
4113                 return -1;
4114         }
4115
4116         ret = ctdb_ctrl_getdbmap(ctdb, TIMELIMIT(), options.pnn, tmp_ctx, &dbmap);
4117         if (ret != 0) {
4118                 DEBUG(DEBUG_ERR, ("Unable to get dbids from node %u\n", options.pnn));
4119                 return ret;
4120         }
4121
4122         for(i=0;i<dbmap->num;i++){
4123                 const char *name;
4124
4125                 ctdb_ctrl_getdbname(ctdb, TIMELIMIT(), options.pnn, dbmap->dbs[i].dbid, tmp_ctx, &name);
4126                 if(!strcmp(argv[0], name)){
4127                         talloc_free(discard_const(name));
4128                         break;
4129                 }
4130                 talloc_free(discard_const(name));
4131         }
4132         if (i == dbmap->num) {
4133                 DEBUG(DEBUG_ERR,("No database with name '%s' found\n", argv[0]));
4134                 talloc_free(tmp_ctx);
4135                 return -1;
4136         }
4137
4138         ret = ctdb_ctrl_getdbhealth(ctdb, TIMELIMIT(), options.pnn,
4139                                     dbmap->dbs[i].dbid, tmp_ctx, &reason);
4140         if (ret != 0) {
4141                 DEBUG(DEBUG_ERR,("Unable to get dbhealth for database '%s'\n",
4142                                  argv[0]));
4143                 talloc_free(tmp_ctx);
4144                 return -1;
4145         }
4146         if (reason) {
4147                 uint32_t allow_unhealthy = 0;
4148
4149                 ctdb_ctrl_get_tunable(ctdb, TIMELIMIT(), options.pnn,
4150                                       "AllowUnhealthyDBRead",
4151                                       &allow_unhealthy);
4152
4153                 if (allow_unhealthy != 1) {
4154                         DEBUG(DEBUG_ERR,("database '%s' is unhealthy: %s\n",
4155                                          argv[0], reason));
4156
4157                         DEBUG(DEBUG_ERR,("disallow backup : tunnable AllowUnhealthyDBRead = %u\n",
4158                                          allow_unhealthy));
4159                         talloc_free(tmp_ctx);
4160                         return -1;
4161                 }
4162
4163                 DEBUG(DEBUG_WARNING,("WARNING database '%s' is unhealthy - see 'ctdb getdbstatus %s'\n",
4164                                      argv[0], argv[0]));
4165                 DEBUG(DEBUG_WARNING,("WARNING! allow backup of unhealthy database: "
4166                                      "tunnable AllowUnhealthyDBRead = %u\n",
4167                                      allow_unhealthy));
4168         }
4169
4170         ctdb_db = ctdb_attach(ctdb, argv[0], dbmap->dbs[i].persistent, 0);
4171         if (ctdb_db == NULL) {
4172                 DEBUG(DEBUG_ERR,("Unable to attach to database '%s'\n", argv[0]));
4173                 talloc_free(tmp_ctx);
4174                 return -1;
4175         }
4176
4177
4178         ret = tdb_transaction_start(ctdb_db->ltdb->tdb);
4179         if (ret == -1) {
4180                 DEBUG(DEBUG_ERR,("Failed to start transaction\n"));
4181                 talloc_free(tmp_ctx);
4182                 return -1;
4183         }
4184
4185
4186         bd = talloc_zero(tmp_ctx, struct backup_data);
4187         if (bd == NULL) {
4188                 DEBUG(DEBUG_ERR,("Failed to allocate backup_data\n"));
4189                 talloc_free(tmp_ctx);
4190                 return -1;
4191         }
4192
4193         bd->records = talloc_zero(bd, struct ctdb_marshall_buffer);
4194         if (bd->records == NULL) {
4195                 DEBUG(DEBUG_ERR,("Failed to allocate ctdb_marshall_buffer\n"));
4196                 talloc_free(tmp_ctx);
4197                 return -1;
4198         }
4199
4200         bd->len = offsetof(struct ctdb_marshall_buffer, data);
4201         bd->records->db_id = ctdb_db->db_id;
4202         /* traverse the database collecting all records */
4203         if (tdb_traverse_read(ctdb_db->ltdb->tdb, backup_traverse, bd) == -1 ||
4204             bd->traverse_error) {
4205                 DEBUG(DEBUG_ERR,("Traverse error\n"));
4206                 talloc_free(tmp_ctx);
4207                 return -1;              
4208         }
4209
4210         tdb_transaction_cancel(ctdb_db->ltdb->tdb);
4211
4212
4213         fh = open(argv[1], O_RDWR|O_CREAT, 0600);
4214         if (fh == -1) {
4215                 DEBUG(DEBUG_ERR,("Failed to open file '%s'\n", argv[1]));
4216                 talloc_free(tmp_ctx);
4217                 return -1;
4218         }
4219
4220         dbhdr.version = DB_VERSION;
4221         dbhdr.timestamp = time(NULL);
4222         dbhdr.persistent = dbmap->dbs[i].persistent;
4223         dbhdr.size = bd->len;
4224         if (strlen(argv[0]) >= MAX_DB_NAME) {
4225                 DEBUG(DEBUG_ERR,("Too long dbname\n"));
4226                 goto done;
4227         }
4228         strncpy(discard_const(dbhdr.name), argv[0], MAX_DB_NAME);
4229         ret = write(fh, &dbhdr, sizeof(dbhdr));
4230         if (ret == -1) {
4231                 DEBUG(DEBUG_ERR,("write failed: %s\n", strerror(errno)));
4232                 goto done;
4233         }
4234         ret = write(fh, bd->records, bd->len);
4235         if (ret == -1) {
4236                 DEBUG(DEBUG_ERR,("write failed: %s\n", strerror(errno)));
4237                 goto done;
4238         }
4239
4240         status = 0;
4241 done:
4242         if (fh != -1) {
4243                 ret = close(fh);
4244                 if (ret == -1) {
4245                         DEBUG(DEBUG_ERR,("close failed: %s\n", strerror(errno)));
4246                 }
4247         }
4248
4249         DEBUG(DEBUG_ERR,("Database acked up to %s\n", argv[1]));
4250
4251         talloc_free(tmp_ctx);
4252         return status;
4253 }
4254
4255 /*
4256  * restore a database from a file 
4257  */
4258 static int control_restoredb(struct ctdb_context *ctdb, int argc, const char **argv)
4259 {
4260         int ret;
4261         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
4262         TDB_DATA outdata;
4263         TDB_DATA data;
4264         struct db_file_header dbhdr;
4265         struct ctdb_db_context *ctdb_db;
4266         struct ctdb_node_map *nodemap=NULL;
4267         struct ctdb_vnn_map *vnnmap=NULL;
4268         int i, fh;
4269         struct ctdb_control_wipe_database w;
4270         uint32_t *nodes;
4271         uint32_t generation;
4272         struct tm *tm;
4273         char tbuf[100];
4274         char *dbname;
4275
4276         if (argc < 1 || argc > 2) {
4277                 DEBUG(DEBUG_ERR,("Invalid arguments\n"));
4278                 return -1;
4279         }
4280
4281         fh = open(argv[0], O_RDONLY);
4282         if (fh == -1) {
4283                 DEBUG(DEBUG_ERR,("Failed to open file '%s'\n", argv[0]));
4284                 talloc_free(tmp_ctx);
4285                 return -1;
4286         }
4287
4288         read(fh, &dbhdr, sizeof(dbhdr));
4289         if (dbhdr.version != DB_VERSION) {
4290                 DEBUG(DEBUG_ERR,("Invalid version of database dump. File is version %lu but expected version was %u\n", dbhdr.version, DB_VERSION));
4291                 talloc_free(tmp_ctx);
4292                 return -1;
4293         }
4294
4295         dbname = discard_const(dbhdr.name);
4296         if (argc == 2) {
4297                 dbname = discard_const(argv[1]);
4298         }
4299
4300         outdata.dsize = dbhdr.size;
4301         outdata.dptr = talloc_size(tmp_ctx, outdata.dsize);
4302         if (outdata.dptr == NULL) {
4303                 DEBUG(DEBUG_ERR,("Failed to allocate data of size '%lu'\n", dbhdr.size));
4304                 close(fh);
4305                 talloc_free(tmp_ctx);
4306                 return -1;
4307         }               
4308         read(fh, outdata.dptr, outdata.dsize);
4309         close(fh);
4310
4311         tm = localtime(&dbhdr.timestamp);
4312         strftime(tbuf,sizeof(tbuf)-1,"%Y/%m/%d %H:%M:%S", tm);
4313         printf("Restoring database '%s' from backup @ %s\n",
4314                 dbname, tbuf);
4315
4316
4317         ctdb_db = ctdb_attach(ctdb, dbname, dbhdr.persistent, 0);
4318         if (ctdb_db == NULL) {
4319                 DEBUG(DEBUG_ERR,("Unable to attach to database '%s'\n", dbname));
4320                 talloc_free(tmp_ctx);
4321                 return -1;
4322         }
4323
4324         ret = ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), options.pnn, ctdb, &nodemap);
4325         if (ret != 0) {
4326                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from node %u\n", options.pnn));
4327                 talloc_free(tmp_ctx);
4328                 return ret;
4329         }
4330
4331
4332         ret = ctdb_ctrl_getvnnmap(ctdb, TIMELIMIT(), options.pnn, tmp_ctx, &vnnmap);
4333         if (ret != 0) {
4334                 DEBUG(DEBUG_ERR, ("Unable to get vnnmap from node %u\n", options.pnn));
4335                 talloc_free(tmp_ctx);
4336                 return ret;
4337         }
4338
4339         /* freeze all nodes */
4340         nodes = list_of_active_nodes(ctdb, nodemap, tmp_ctx, true);
4341         for (i=1; i<=NUM_DB_PRIORITIES; i++) {
4342                 if (ctdb_client_async_control(ctdb, CTDB_CONTROL_FREEZE,
4343                                         nodes, i,
4344                                         TIMELIMIT(),
4345                                         false, tdb_null,
4346                                         NULL, NULL,
4347                                         NULL) != 0) {
4348                         DEBUG(DEBUG_ERR, ("Unable to freeze nodes.\n"));
4349                         ctdb_ctrl_setrecmode(ctdb, TIMELIMIT(), options.pnn, CTDB_RECOVERY_ACTIVE);
4350                         talloc_free(tmp_ctx);
4351                         return -1;
4352                 }
4353         }
4354
4355         generation = vnnmap->generation;
4356         data.dptr = (void *)&generation;
4357         data.dsize = sizeof(generation);
4358
4359         /* start a cluster wide transaction */
4360         nodes = list_of_active_nodes(ctdb, nodemap, tmp_ctx, true);
4361         if (ctdb_client_async_control(ctdb, CTDB_CONTROL_TRANSACTION_START,
4362                                         nodes, 0,
4363                                         TIMELIMIT(), false, data,
4364                                         NULL, NULL,
4365                                         NULL) != 0) {
4366                 DEBUG(DEBUG_ERR, ("Unable to start cluster wide transactions.\n"));
4367                 return -1;
4368         }
4369
4370
4371         w.db_id = ctdb_db->db_id;
4372         w.transaction_id = generation;
4373
4374         data.dptr = (void *)&w;
4375         data.dsize = sizeof(w);
4376
4377         /* wipe all the remote databases. */
4378         nodes = list_of_active_nodes(ctdb, nodemap, tmp_ctx, true);
4379         if (ctdb_client_async_control(ctdb, CTDB_CONTROL_WIPE_DATABASE,
4380                                         nodes, 0,
4381                                         TIMELIMIT(), false, data,
4382                                         NULL, NULL,
4383                                         NULL) != 0) {
4384                 DEBUG(DEBUG_ERR, ("Unable to wipe database.\n"));
4385                 ctdb_ctrl_setrecmode(ctdb, TIMELIMIT(), options.pnn, CTDB_RECOVERY_ACTIVE);
4386                 talloc_free(tmp_ctx);
4387                 return -1;
4388         }
4389         
4390         /* push the database */
4391         nodes = list_of_active_nodes(ctdb, nodemap, tmp_ctx, true);
4392         if (ctdb_client_async_control(ctdb, CTDB_CONTROL_PUSH_DB,
4393                                         nodes, 0,
4394                                         TIMELIMIT(), false, outdata,
4395                                         NULL, NULL,
4396                                         NULL) != 0) {
4397                 DEBUG(DEBUG_ERR, ("Failed to push database.\n"));
4398                 ctdb_ctrl_setrecmode(ctdb, TIMELIMIT(), options.pnn, CTDB_RECOVERY_ACTIVE);
4399                 talloc_free(tmp_ctx);
4400                 return -1;
4401         }
4402
4403         data.dptr = (void *)&ctdb_db->db_id;
4404         data.dsize = sizeof(ctdb_db->db_id);
4405
4406         /* mark the database as healthy */
4407         nodes = list_of_active_nodes(ctdb, nodemap, tmp_ctx, true);
4408         if (ctdb_client_async_control(ctdb, CTDB_CONTROL_DB_SET_HEALTHY,
4409                                         nodes, 0,
4410                                         TIMELIMIT(), false, data,
4411                                         NULL, NULL,
4412                                         NULL) != 0) {
4413                 DEBUG(DEBUG_ERR, ("Failed to mark database as healthy.\n"));
4414                 ctdb_ctrl_setrecmode(ctdb, TIMELIMIT(), options.pnn, CTDB_RECOVERY_ACTIVE);
4415                 talloc_free(tmp_ctx);
4416                 return -1;
4417         }
4418
4419         data.dptr = (void *)&generation;
4420         data.dsize = sizeof(generation);
4421
4422         /* commit all the changes */
4423         if (ctdb_client_async_control(ctdb, CTDB_CONTROL_TRANSACTION_COMMIT,
4424                                         nodes, 0,
4425                                         TIMELIMIT(), false, data,
4426                                         NULL, NULL,
4427                                         NULL) != 0) {
4428                 DEBUG(DEBUG_ERR, ("Unable to commit databases.\n"));
4429                 ctdb_ctrl_setrecmode(ctdb, TIMELIMIT(), options.pnn, CTDB_RECOVERY_ACTIVE);
4430                 talloc_free(tmp_ctx);
4431                 return -1;
4432         }
4433
4434
4435         /* thaw all nodes */
4436         nodes = list_of_active_nodes(ctdb, nodemap, tmp_ctx, true);
4437         if (ctdb_client_async_control(ctdb, CTDB_CONTROL_THAW,
4438                                         nodes, 0,
4439                                         TIMELIMIT(),
4440                                         false, tdb_null,
4441                                         NULL, NULL,
4442                                         NULL) != 0) {
4443                 DEBUG(DEBUG_ERR, ("Unable to thaw nodes.\n"));
4444                 ctdb_ctrl_setrecmode(ctdb, TIMELIMIT(), options.pnn, CTDB_RECOVERY_ACTIVE);
4445                 talloc_free(tmp_ctx);
4446                 return -1;
4447         }
4448
4449
4450         talloc_free(tmp_ctx);
4451         return 0;
4452 }
4453
4454 /*
4455  * dump a database backup from a file
4456  */
4457 static int control_dumpdbbackup(struct ctdb_context *ctdb, int argc, const char **argv)
4458 {
4459         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
4460         TDB_DATA outdata;
4461         struct db_file_header dbhdr;
4462         int i, fh;
4463         struct tm *tm;
4464         char tbuf[100];
4465         struct ctdb_rec_data *rec = NULL;
4466         struct ctdb_marshall_buffer *m;
4467
4468         if (argc != 1) {
4469                 DEBUG(DEBUG_ERR,("Invalid arguments\n"));
4470                 return -1;
4471         }
4472
4473         fh = open(argv[0], O_RDONLY);
4474         if (fh == -1) {
4475                 DEBUG(DEBUG_ERR,("Failed to open file '%s'\n", argv[0]));
4476                 talloc_free(tmp_ctx);
4477                 return -1;
4478         }
4479
4480         read(fh, &dbhdr, sizeof(dbhdr));
4481         if (dbhdr.version != DB_VERSION) {
4482                 DEBUG(DEBUG_ERR,("Invalid version of database dump. File is version %lu but expected version was %u\n", dbhdr.version, DB_VERSION));
4483                 talloc_free(tmp_ctx);
4484                 return -1;
4485         }
4486
4487         outdata.dsize = dbhdr.size;
4488         outdata.dptr = talloc_size(tmp_ctx, outdata.dsize);
4489         if (outdata.dptr == NULL) {
4490                 DEBUG(DEBUG_ERR,("Failed to allocate data of size '%lu'\n", dbhdr.size));
4491                 close(fh);
4492                 talloc_free(tmp_ctx);
4493                 return -1;
4494         }
4495         read(fh, outdata.dptr, outdata.dsize);
4496         close(fh);
4497         m = (struct ctdb_marshall_buffer *)outdata.dptr;
4498
4499         tm = localtime(&dbhdr.timestamp);
4500         strftime(tbuf,sizeof(tbuf)-1,"%Y/%m/%d %H:%M:%S", tm);
4501         printf("Backup of database name:'%s' dbid:0x%x08x from @ %s\n",
4502                 dbhdr.name, m->db_id, tbuf);
4503
4504         for (i=0; i < m->count; i++) {
4505                 uint32_t reqid = 0;
4506                 TDB_DATA key, data;
4507
4508                 /* we do not want the header splitted, so we pass NULL*/
4509                 rec = ctdb_marshall_loop_next(m, rec, &reqid,
4510                                               NULL, &key, &data);
4511
4512                 ctdb_dumpdb_record(ctdb, key, data, stdout);
4513         }
4514
4515         printf("Dumped %d records\n", i);
4516         talloc_free(tmp_ctx);
4517         return 0;
4518 }
4519
4520 /*
4521  * wipe a database from a file
4522  */
4523 static int control_wipedb(struct ctdb_context *ctdb, int argc,
4524                           const char **argv)
4525 {
4526         int ret;
4527         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
4528         TDB_DATA data;
4529         struct ctdb_db_context *ctdb_db;
4530         struct ctdb_node_map *nodemap = NULL;
4531         struct ctdb_vnn_map *vnnmap = NULL;
4532         int i;
4533         struct ctdb_control_wipe_database w;
4534         uint32_t *nodes;
4535         uint32_t generation;
4536         struct ctdb_dbid_map *dbmap = NULL;
4537
4538         if (argc != 1) {
4539                 DEBUG(DEBUG_ERR,("Invalid arguments\n"));
4540                 return -1;
4541         }
4542
4543         ret = ctdb_ctrl_getdbmap(ctdb, TIMELIMIT(), options.pnn, tmp_ctx,
4544                                  &dbmap);
4545         if (ret != 0) {
4546                 DEBUG(DEBUG_ERR, ("Unable to get dbids from node %u\n",
4547                                   options.pnn));
4548                 return ret;
4549         }
4550
4551         for(i=0;i<dbmap->num;i++){
4552                 const char *name;
4553
4554                 ctdb_ctrl_getdbname(ctdb, TIMELIMIT(), options.pnn,
4555                                     dbmap->dbs[i].dbid, tmp_ctx, &name);
4556                 if(!strcmp(argv[0], name)){
4557                         talloc_free(discard_const(name));
4558                         break;
4559                 }
4560                 talloc_free(discard_const(name));
4561         }
4562         if (i == dbmap->num) {
4563                 DEBUG(DEBUG_ERR, ("No database with name '%s' found\n",
4564                                   argv[0]));
4565                 talloc_free(tmp_ctx);
4566                 return -1;
4567         }
4568
4569         ctdb_db = ctdb_attach(ctdb, argv[0], dbmap->dbs[i].persistent, 0);
4570         if (ctdb_db == NULL) {
4571                 DEBUG(DEBUG_ERR, ("Unable to attach to database '%s'\n",
4572                                   argv[0]));
4573                 talloc_free(tmp_ctx);
4574                 return -1;
4575         }
4576
4577         ret = ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), options.pnn, ctdb,
4578                                    &nodemap);
4579         if (ret != 0) {
4580                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from node %u\n",
4581                                   options.pnn));
4582                 talloc_free(tmp_ctx);
4583                 return ret;
4584         }
4585
4586         ret = ctdb_ctrl_getvnnmap(ctdb, TIMELIMIT(), options.pnn, tmp_ctx,
4587                                   &vnnmap);
4588         if (ret != 0) {
4589                 DEBUG(DEBUG_ERR, ("Unable to get vnnmap from node %u\n",
4590                                   options.pnn));
4591                 talloc_free(tmp_ctx);
4592                 return ret;
4593         }
4594
4595         /* freeze all nodes */
4596         nodes = list_of_active_nodes(ctdb, nodemap, tmp_ctx, true);
4597         for (i=1; i<=NUM_DB_PRIORITIES; i++) {
4598                 ret = ctdb_client_async_control(ctdb, CTDB_CONTROL_FREEZE,
4599                                                 nodes, i,
4600                                                 TIMELIMIT(),
4601                                                 false, tdb_null,
4602                                                 NULL, NULL,
4603                                                 NULL);
4604                 if (ret != 0) {
4605                         DEBUG(DEBUG_ERR, ("Unable to freeze nodes.\n"));
4606                         ctdb_ctrl_setrecmode(ctdb, TIMELIMIT(), options.pnn,
4607                                              CTDB_RECOVERY_ACTIVE);
4608                         talloc_free(tmp_ctx);
4609                         return -1;
4610                 }
4611         }
4612
4613         generation = vnnmap->generation;
4614         data.dptr = (void *)&generation;
4615         data.dsize = sizeof(generation);
4616
4617         /* start a cluster wide transaction */
4618         nodes = list_of_active_nodes(ctdb, nodemap, tmp_ctx, true);
4619         ret = ctdb_client_async_control(ctdb, CTDB_CONTROL_TRANSACTION_START,
4620                                         nodes, 0,
4621                                         TIMELIMIT(), false, data,
4622                                         NULL, NULL,
4623                                         NULL);
4624         if (ret!= 0) {
4625                 DEBUG(DEBUG_ERR, ("Unable to start cluster wide "
4626                                   "transactions.\n"));
4627                 return -1;
4628         }
4629
4630         w.db_id = ctdb_db->db_id;
4631         w.transaction_id = generation;
4632
4633         data.dptr = (void *)&w;
4634         data.dsize = sizeof(w);
4635
4636         /* wipe all the remote databases. */
4637         nodes = list_of_active_nodes(ctdb, nodemap, tmp_ctx, true);
4638         if (ctdb_client_async_control(ctdb, CTDB_CONTROL_WIPE_DATABASE,
4639                                         nodes, 0,
4640                                         TIMELIMIT(), false, data,
4641                                         NULL, NULL,
4642                                         NULL) != 0) {
4643                 DEBUG(DEBUG_ERR, ("Unable to wipe database.\n"));
4644                 ctdb_ctrl_setrecmode(ctdb, TIMELIMIT(), options.pnn, CTDB_RECOVERY_ACTIVE);
4645                 talloc_free(tmp_ctx);
4646                 return -1;
4647         }
4648
4649         data.dptr = (void *)&ctdb_db->db_id;
4650         data.dsize = sizeof(ctdb_db->db_id);
4651
4652         /* mark the database as healthy */
4653         nodes = list_of_active_nodes(ctdb, nodemap, tmp_ctx, true);
4654         if (ctdb_client_async_control(ctdb, CTDB_CONTROL_DB_SET_HEALTHY,
4655                                         nodes, 0,
4656                                         TIMELIMIT(), false, data,
4657                                         NULL, NULL,
4658                                         NULL) != 0) {
4659                 DEBUG(DEBUG_ERR, ("Failed to mark database as healthy.\n"));
4660                 ctdb_ctrl_setrecmode(ctdb, TIMELIMIT(), options.pnn, CTDB_RECOVERY_ACTIVE);
4661                 talloc_free(tmp_ctx);
4662                 return -1;
4663         }
4664
4665         data.dptr = (void *)&generation;
4666         data.dsize = sizeof(generation);
4667
4668         /* commit all the changes */
4669         if (ctdb_client_async_control(ctdb, CTDB_CONTROL_TRANSACTION_COMMIT,
4670                                         nodes, 0,
4671                                         TIMELIMIT(), false, data,
4672                                         NULL, NULL,
4673                                         NULL) != 0) {
4674                 DEBUG(DEBUG_ERR, ("Unable to commit databases.\n"));
4675                 ctdb_ctrl_setrecmode(ctdb, TIMELIMIT(), options.pnn, CTDB_RECOVERY_ACTIVE);
4676                 talloc_free(tmp_ctx);
4677                 return -1;
4678         }
4679
4680         /* thaw all nodes */
4681         nodes = list_of_active_nodes(ctdb, nodemap, tmp_ctx, true);
4682         if (ctdb_client_async_control(ctdb, CTDB_CONTROL_THAW,
4683                                         nodes, 0,
4684                                         TIMELIMIT(),
4685                                         false, tdb_null,
4686                                         NULL, NULL,
4687                                         NULL) != 0) {
4688                 DEBUG(DEBUG_ERR, ("Unable to thaw nodes.\n"));
4689                 ctdb_ctrl_setrecmode(ctdb, TIMELIMIT(), options.pnn, CTDB_RECOVERY_ACTIVE);
4690                 talloc_free(tmp_ctx);
4691                 return -1;
4692         }
4693
4694         DEBUG(DEBUG_ERR, ("Database wiped.\n"));
4695
4696         talloc_free(tmp_ctx);
4697         return 0;
4698 }
4699
4700 /*
4701   dump memory usage
4702  */
4703 static int control_dumpmemory(struct ctdb_context *ctdb, int argc, const char **argv)
4704 {
4705         TDB_DATA data;
4706         int ret;
4707         int32_t res;
4708         char *errmsg;
4709         TALLOC_CTX *tmp_ctx = talloc_new(ctdb);
4710         ret = ctdb_control(ctdb, options.pnn, 0, CTDB_CONTROL_DUMP_MEMORY,
4711                            0, tdb_null, tmp_ctx, &data, &res, NULL, &errmsg);
4712         if (ret != 0 || res != 0) {
4713                 DEBUG(DEBUG_ERR,("Failed to dump memory - %s\n", errmsg));
4714                 talloc_free(tmp_ctx);
4715                 return -1;
4716         }
4717         write(1, data.dptr, data.dsize);
4718         talloc_free(tmp_ctx);
4719         return 0;
4720 }
4721
4722 /*
4723   handler for memory dumps
4724 */
4725 static void mem_dump_handler(struct ctdb_context *ctdb, uint64_t srvid, 
4726                              TDB_DATA data, void *private_data)
4727 {
4728         write(1, data.dptr, data.dsize);
4729         exit(0);
4730 }
4731
4732 /*
4733   dump memory usage on the recovery daemon
4734  */
4735 static int control_rddumpmemory(struct ctdb_context *ctdb, int argc, const char **argv)
4736 {
4737         int ret;
4738         TDB_DATA data;
4739         struct rd_memdump_reply rd;
4740
4741         rd.pnn = ctdb_ctrl_getpnn(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE);
4742         if (rd.pnn == -1) {
4743                 DEBUG(DEBUG_ERR, ("Failed to get pnn of local node\n"));
4744                 return -1;
4745         }
4746         rd.srvid = getpid();
4747
4748         /* register a message port for receiveing the reply so that we
4749            can receive the reply
4750         */
4751         ctdb_client_set_message_handler(ctdb, rd.srvid, mem_dump_handler, NULL);
4752
4753
4754         data.dptr = (uint8_t *)&rd;
4755         data.dsize = sizeof(rd);
4756
4757         ret = ctdb_client_send_message(ctdb, options.pnn, CTDB_SRVID_MEM_DUMP, data);
4758         if (ret != 0) {
4759                 DEBUG(DEBUG_ERR,("Failed to send memdump request message to %u\n", options.pnn));
4760                 return -1;
4761         }
4762
4763         /* this loop will terminate when we have received the reply */
4764         while (1) {     
4765                 event_loop_once(ctdb->ev);
4766         }
4767
4768         return 0;
4769 }
4770
4771 /*
4772   send a message to a srvid
4773  */
4774 static int control_msgsend(struct ctdb_context *ctdb, int argc, const char **argv)
4775 {
4776         unsigned long srvid;
4777         int ret;
4778         TDB_DATA data;
4779
4780         if (argc < 2) {
4781                 usage();
4782         }
4783
4784         srvid      = strtoul(argv[0], NULL, 0);
4785
4786         data.dptr = (uint8_t *)discard_const(argv[1]);
4787         data.dsize= strlen(argv[1]);
4788
4789         ret = ctdb_client_send_message(ctdb, CTDB_BROADCAST_CONNECTED, srvid, data);
4790         if (ret != 0) {
4791                 DEBUG(DEBUG_ERR,("Failed to send memdump request message to %u\n", options.pnn));
4792                 return -1;
4793         }
4794
4795         return 0;
4796 }
4797
4798 /*
4799   handler for msglisten
4800 */
4801 static void msglisten_handler(struct ctdb_context *ctdb, uint64_t srvid, 
4802                              TDB_DATA data, void *private_data)
4803 {
4804         int i;
4805
4806         printf("Message received: ");
4807         for (i=0;i<data.dsize;i++) {
4808                 printf("%c", data.dptr[i]);
4809         }
4810         printf("\n");
4811 }
4812
4813 /*
4814   listen for messages on a messageport
4815  */
4816 static int control_msglisten(struct ctdb_context *ctdb, int argc, const char **argv)
4817 {
4818         uint64_t srvid;
4819
4820         srvid = getpid();
4821
4822         /* register a message port and listen for messages
4823         */
4824         ctdb_client_set_message_handler(ctdb, srvid, msglisten_handler, NULL);
4825         printf("Listening for messages on srvid:%d\n", (int)srvid);
4826
4827         while (1) {     
4828                 event_loop_once(ctdb->ev);
4829         }
4830
4831         return 0;
4832 }
4833
4834 /*
4835   list all nodes in the cluster
4836   we parse the nodes file directly
4837  */
4838 static int control_listnodes(struct ctdb_context *ctdb, int argc, const char **argv)
4839 {
4840         TALLOC_CTX *mem_ctx = talloc_new(NULL);
4841         struct pnn_node *pnn_nodes;
4842         struct pnn_node *pnn_node;
4843
4844         pnn_nodes = read_nodes_file(mem_ctx);
4845         if (pnn_nodes == NULL) {
4846                 DEBUG(DEBUG_ERR,("Failed to read nodes file\n"));
4847                 talloc_free(mem_ctx);
4848                 return -1;
4849         }
4850
4851         for(pnn_node=pnn_nodes;pnn_node;pnn_node=pnn_node->next) {
4852                 ctdb_sock_addr addr;
4853                 if (parse_ip(pnn_node->addr, NULL, 63999, &addr) == 0) {
4854                         DEBUG(DEBUG_ERR,("Wrongly formed ip address '%s' in nodes file\n", pnn_node->addr));
4855                         talloc_free(mem_ctx);
4856                         return -1;
4857                 }
4858                 if (options.machinereadable){
4859                         printf(":%d:%s:\n", pnn_node->pnn, pnn_node->addr);
4860                 } else {
4861                         printf("%s\n", pnn_node->addr);
4862                 }
4863         }
4864         talloc_free(mem_ctx);
4865
4866         return 0;
4867 }
4868
4869 /*
4870   reload the nodes file on the local node
4871  */
4872 static int control_reload_nodes_file(struct ctdb_context *ctdb, int argc, const char **argv)
4873 {
4874         int i, ret;
4875         int mypnn;
4876         struct ctdb_node_map *nodemap=NULL;
4877
4878         mypnn = ctdb_ctrl_getpnn(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE);
4879         if (mypnn == -1) {
4880                 DEBUG(DEBUG_ERR, ("Failed to read pnn of local node\n"));
4881                 return -1;
4882         }
4883
4884         ret = ctdb_ctrl_getnodemap(ctdb, TIMELIMIT(), CTDB_CURRENT_NODE, ctdb, &nodemap);
4885         if (ret != 0) {
4886                 DEBUG(DEBUG_ERR, ("Unable to get nodemap from local node\n"));
4887                 return ret;
4888         }
4889
4890         /* reload the nodes file on all remote nodes */
4891         for (i=0;i<nodemap->num;i++) {
4892                 if (nodemap->nodes[i].pnn == mypnn) {
4893                         continue;
4894                 }
4895                 DEBUG(DEBUG_NOTICE, ("Reloading nodes file on node %u\n", nodemap->nodes[i].pnn));
4896                 ret = ctdb_ctrl_reload_nodes_file(ctdb, TIMELIMIT(),
4897                         nodemap->nodes[i].pnn);
4898                 if (ret != 0) {
4899                         DEBUG(DEBUG_ERR, ("ERROR: Failed to reload nodes file on node %u. You MUST fix that node manually!\n", nodemap->nodes[i].pnn));
4900                 }
4901         }
4902
4903         /* reload the nodes file on the local node */
4904         DEBUG(DEBUG_NOTICE, ("Reloading nodes file on node %u\n", mypnn));
4905         ret = ctdb_ctrl_reload_nodes_file(ctdb, TIMELIMIT(), mypnn);
4906         if (ret != 0) {
4907                 DEBUG(DEBUG_ERR, ("ERROR: Failed to reload nodes file on node %u. You MUST fix that node manually!\n", mypnn));
4908         }
4909
4910         /* initiate a recovery */
4911         control_recover(ctdb, argc, argv);
4912
4913         return 0;
4914 }
4915
4916
4917 static const struct {
4918         const char *name;
4919         int (*fn)(struct ctdb_context *, int, const char **);
4920         bool auto_all;
4921         bool without_daemon; /* can be run without daemon running ? */
4922         const char *msg;
4923         const char *args;
4924 } ctdb_commands[] = {
4925 #ifdef CTDB_VERS
4926         { "version",         control_version,           true,   false,  "show version of ctdb" },
4927 #endif
4928         { "status",          control_status,            true,   false,  "show node status" },
4929         { "uptime",          control_uptime,            true,   false,  "show node uptime" },
4930         { "ping",            control_ping,              true,   false,  "ping all nodes" },
4931         { "getvar",          control_getvar,            true,   false,  "get a tunable variable",               "<name>"},
4932         { "setvar",          control_setvar,            true,   false,  "set a tunable variable",               "<name> <value>"},
4933         { "listvars",        control_listvars,          true,   false,  "list tunable variables"},
4934         { "statistics",      control_statistics,        false,  false, "show statistics" },
4935         { "statisticsreset", control_statistics_reset,  true,   false,  "reset statistics"},
4936         { "stats",           control_stats,             false,  false,  "show rolling statistics", "[number of history records]" },
4937         { "ip",              control_ip,                false,  false,  "show which public ip's that ctdb manages" },
4938         { "ipinfo",          control_ipinfo,            true,   false,  "show details about a public ip that ctdb manages", "<ip>" },
4939         { "ifaces",          control_ifaces,            true,   false,  "show which interfaces that ctdb manages" },
4940         { "setifacelink",    control_setifacelink,      true,   false,  "set interface link status", "<iface> <status>" },
4941         { "process-exists",  control_process_exists,    true,   false,  "check if a process exists on a node",  "<pid>"},
4942         { "getdbmap",        control_getdbmap,          true,   false,  "show the database map" },
4943         { "getdbstatus",     control_getdbstatus,       true,   false,  "show the status of a database", "<dbname>" },
4944         { "catdb",           control_catdb,             true,   false,  "dump a database" ,                     "<dbname>"},
4945         { "getmonmode",      control_getmonmode,        true,   false,  "show monitoring mode" },
4946         { "getcapabilities", control_getcapabilities,   true,   false,  "show node capabilities" },
4947         { "pnn",             control_pnn,               true,   false,  "show the pnn of the currnet node" },
4948         { "lvs",             control_lvs,               true,   false,  "show lvs configuration" },
4949         { "lvsmaster",       control_lvsmaster,         true,   false,  "show which node is the lvs master" },
4950         { "disablemonitor",      control_disable_monmode,true,  false,  "set monitoring mode to DISABLE" },
4951         { "enablemonitor",      control_enable_monmode, true,   false,  "set monitoring mode to ACTIVE" },
4952         { "setdebug",        control_setdebug,          true,   false,  "set debug level",                      "<EMERG|ALERT|CRIT|ERR|WARNING|NOTICE|INFO|DEBUG>" },
4953         { "getdebug",        control_getdebug,          true,   false,  "get debug level" },
4954         { "getlog",          control_getlog,            true,   false,  "get the log data from the in memory ringbuffer", "<level>" },
4955         { "clearlog",          control_clearlog,        true,   false,  "clear the log data from the in memory ringbuffer" },
4956         { "attach",          control_attach,            true,   false,  "attach to a database",                 "<dbname> [persistent]" },
4957         { "dumpmemory",      control_dumpmemory,        true,   false,  "dump memory map to stdout" },
4958         { "rddumpmemory",    control_rddumpmemory,      true,   false,  "dump memory map from the recovery daemon to stdout" },
4959         { "getpid",          control_getpid,            true,   false,  "get ctdbd process ID" },
4960         { "disable",         control_disable,           true,   false,  "disable a nodes public IP" },
4961         { "enable",          control_enable,            true,   false,  "enable a nodes public IP" },
4962         { "stop",            control_stop,              true,   false,  "stop a node" },
4963         { "continue",        control_continue,          true,   false,  "re-start a stopped node" },
4964         { "ban",             control_ban,               true,   false,  "ban a node from the cluster",          "<bantime|0>"},
4965         { "unban",           control_unban,             true,   false,  "unban a node" },
4966         { "showban",         control_showban,           true,   false,  "show ban information"},
4967         { "shutdown",        control_shutdown,          true,   false,  "shutdown ctdbd" },
4968         { "recover",         control_recover,           true,   false,  "force recovery" },
4969         { "sync",            control_ipreallocate,      true,   false,  "wait until ctdbd has synced all state changes" },
4970         { "ipreallocate",    control_ipreallocate,      true,   false,  "force the recovery daemon to perform a ip reallocation procedure" },
4971         { "thaw",            control_thaw,              true,   false,  "thaw databases", "[priority:1-3]" },
4972         { "isnotrecmaster",  control_isnotrecmaster,    false,  false,  "check if the local node is recmaster or not" },
4973         { "killtcp",         kill_tcp,                  false,  false, "kill a tcp connection.", "<srcip:port> <dstip:port>" },
4974         { "gratiousarp",     control_gratious_arp,      false,  false, "send a gratious arp", "<ip> <interface>" },
4975         { "tickle",          tickle_tcp,                false,  false, "send a tcp tickle ack", "<srcip:port> <dstip:port>" },
4976         { "gettickles",      control_get_tickles,       false,  false, "get the list of tickles registered for this ip", "<ip> [<port>]" },
4977         { "addtickle",       control_add_tickle,        false,  false, "add a tickle for this ip", "<ip>:<port> <ip>:<port>" },
4978
4979         { "deltickle",       control_del_tickle,        false,  false, "delete a tickle from this ip", "<ip>:<port> <ip>:<port>" },
4980
4981         { "regsrvid",        regsrvid,                  false,  false, "register a server id", "<pnn> <type> <id>" },
4982         { "unregsrvid",      unregsrvid,                false,  false, "unregister a server id", "<pnn> <type> <id>" },
4983         { "chksrvid",        chksrvid,                  false,  false, "check if a server id exists", "<pnn> <type> <id>" },
4984         { "getsrvids",       getsrvids,                 false,  false, "get a list of all server ids"},
4985         { "vacuum",          ctdb_vacuum,               false,  false, "vacuum the databases of empty records", "[max_records]"},
4986         { "repack",          ctdb_repack,               false,  false, "repack all databases", "[max_freelist]"},
4987         { "listnodes",       control_listnodes,         false,  true, "list all nodes in the cluster"},
4988         { "reloadnodes",     control_reload_nodes_file, false,  false, "reload the nodes file and restart the transport on all nodes"},
4989         { "moveip",          control_moveip,            false,  false, "move/failover an ip address to another node", "<ip> <node>"},
4990         { "addip",           control_addip,             true,   false, "add a ip address to a node", "<ip/mask> <iface>"},
4991         { "delip",           control_delip,             false,  false, "delete an ip address from a node", "<ip>"},
4992         { "eventscript",     control_eventscript,       true,   false, "run the eventscript with the given parameters on a node", "<arguments>"},
4993         { "backupdb",        control_backupdb,          false,  false, "backup the database into a file.", "<database> <file>"},
4994         { "restoredb",        control_restoredb,        false,  false, "restore the database from a file.", "<file> [dbname]"},
4995         { "dumpdbbackup",    control_dumpdbbackup,      false,  true,  "dump database backup from a file.", "<file>"},
4996         { "wipedb",           control_wipedb,        false,     false, "wipe the contents of a database.", "<dbname>"},
4997         { "recmaster",        control_recmaster,        false,  false, "show the pnn for the recovery master."},
4998         { "scriptstatus",    control_scriptstatus,  false,      false, "show the status of the monitoring scripts (or all scripts)", "[all]"},
4999         { "enablescript",     control_enablescript,  false,     false, "enable an eventscript", "<script>"},
5000         { "disablescript",    control_disablescript,  false,    false, "disable an eventscript", "<script>"},
5001         { "natgwlist",        control_natgwlist,        false,  false, "show the nodes belonging to this natgw configuration"},
5002         { "xpnn",             control_xpnn,             true,   true,  "find the pnn of the local node without talking to the daemon (unreliable)" },
5003         { "getreclock",       control_getreclock,       false,  false, "Show the reclock file of a node"},
5004         { "setreclock",       control_setreclock,       false,  false, "Set/clear the reclock file of a node", "[filename]"},
5005         { "setnatgwstate",    control_setnatgwstate,    false,  false, "Set NATGW state to on/off", "{on|off}"},
5006         { "setlmasterrole",   control_setlmasterrole,   false,  false, "Set LMASTER role to on/off", "{on|off}"},
5007         { "setrecmasterrole", control_setrecmasterrole, false,  false, "Set RECMASTER role to on/off", "{on|off}"},
5008         { "setdbprio",        control_setdbprio,        false,  false, "Set DB priority", "<dbid> <prio:1-3>"},
5009         { "getdbprio",        control_getdbprio,        false,  false, "Get DB priority", "<dbid>"},
5010         { "msglisten",        control_msglisten,        false,  false, "Listen on a srvid port for messages", "<msg srvid>"},
5011         { "msgsend",          control_msgsend,  false,  false, "Send a message to srvid", "<srvid> <message>"},
5012         { "sync",            control_ipreallocate,      false,  false,  "wait until ctdbd has synced all state changes" },
5013         { "pfetch",          control_pfetch,            false,  false,  "fetch a record from a persistent database", "<db> <key> [<file>]" },
5014         { "pstore",          control_pstore,            false,  false,  "write a record to a persistent database", "<db> <key> <file containing record>" },
5015         { "tfetch",          control_tfetch,            false,  true,  "fetch a record from a [c]tdb-file", "<tdb-file> <key> [<file>]" },
5016         { "readkey",         control_readkey,           true,   false,  "read the content off a database key", "<tdb-file> <key>" },
5017         { "writekey",        control_writekey,          true,   false,  "write to a database key", "<tdb-file> <key> <value>" },
5018         { "checktcpport",    control_chktcpport,        false,  true,  "check if a service is bound to a specific tcp port or not", "<port>" },
5019 };
5020
5021 /*
5022   show usage message
5023  */
5024 static void usage(void)
5025 {
5026         int i;
5027         printf(
5028 "Usage: ctdb [options] <control>\n" \
5029 "Options:\n" \
5030 "   -n <node>          choose node number, or 'all' (defaults to local node)\n"
5031 "   -Y                 generate machinereadable output\n"
5032 "   -v                 generate verbose output\n"
5033 "   -t <timelimit>     set timelimit for control in seconds (default %u)\n", options.timelimit);
5034         printf("Controls:\n");
5035         for (i=0;i<ARRAY_SIZE(ctdb_commands);i++) {
5036                 printf("  %-15s %-27s  %s\n", 
5037                        ctdb_commands[i].name, 
5038                        ctdb_commands[i].args?ctdb_commands[i].args:"",
5039                        ctdb_commands[i].msg);
5040         }
5041         exit(1);
5042 }
5043
5044
5045 static void ctdb_alarm(int sig)
5046 {
5047         printf("Maximum runtime exceeded - exiting\n");
5048         _exit(ERR_TIMEOUT);
5049 }
5050
5051 /*
5052   main program
5053 */
5054 int main(int argc, const char *argv[])
5055 {
5056         struct ctdb_context *ctdb;
5057         char *nodestring = NULL;
5058         struct poptOption popt_options[] = {
5059                 POPT_AUTOHELP
5060                 POPT_CTDB_CMDLINE
5061                 { "timelimit", 't', POPT_ARG_INT, &options.timelimit, 0, "timelimit", "integer" },
5062                 { "node",      'n', POPT_ARG_STRING, &nodestring, 0, "node", "integer|all" },
5063                 { "machinereadable", 'Y', POPT_ARG_NONE, &options.machinereadable, 0, "enable machinereadable output", NULL },
5064                 { "verbose",    'v', POPT_ARG_NONE, &options.verbose, 0, "enable verbose output", NULL },
5065                 { "maxruntime", 'T', POPT_ARG_INT, &options.maxruntime, 0, "die if runtime exceeds this limit (in seconds)", "integer" },
5066                 POPT_TABLEEND
5067         };
5068         int opt;
5069         const char **extra_argv;
5070         int extra_argc = 0;
5071         int ret=-1, i;
5072         poptContext pc;
5073         struct event_context *ev;
5074         const char *control;
5075
5076         setlinebuf(stdout);
5077         
5078         /* set some defaults */
5079         options.maxruntime = 0;
5080         options.timelimit = 3;
5081         options.pnn = CTDB_CURRENT_NODE;
5082
5083         pc = poptGetContext(argv[0], argc, argv, popt_options, POPT_CONTEXT_KEEP_FIRST);
5084
5085         while ((opt = poptGetNextOpt(pc)) != -1) {
5086                 switch (opt) {
5087                 default:
5088                         DEBUG(DEBUG_ERR, ("Invalid option %s: %s\n", 
5089                                 poptBadOption(pc, 0), poptStrerror(opt)));
5090                         exit(1);
5091                 }
5092         }
5093
5094         /* setup the remaining options for the main program to use */
5095         extra_argv = poptGetArgs(pc);
5096         if (extra_argv) {
5097                 extra_argv++;
5098                 while (extra_argv[extra_argc]) extra_argc++;
5099         }
5100
5101         if (extra_argc < 1) {
5102                 usage();
5103         }
5104
5105         if (options.maxruntime == 0) {
5106                 const char *ctdb_timeout;
5107                 ctdb_timeout = getenv("CTDB_TIMEOUT");
5108                 if (ctdb_timeout != NULL) {
5109                         options.maxruntime = strtoul(ctdb_timeout, NULL, 0);
5110                 } else {
5111                         /* default timeout is 120 seconds */
5112                         options.maxruntime = 120;
5113                 }
5114         }
5115
5116         signal(SIGALRM, ctdb_alarm);
5117         alarm(options.maxruntime);
5118
5119         /* setup the node number to contact */
5120         if (nodestring != NULL) {
5121                 if (strcmp(nodestring, "all") == 0) {
5122                         options.pnn = CTDB_BROADCAST_ALL;
5123                 } else {
5124                         options.pnn = strtoul(nodestring, NULL, 0);
5125                 }
5126         }
5127
5128         control = extra_argv[0];
5129
5130         ev = event_context_init(NULL);
5131         if (!ev) {
5132                 DEBUG(DEBUG_ERR, ("Failed to initialize event system\n"));
5133                 exit(1);
5134         }
5135         tevent_loop_allow_nesting(ev);
5136
5137         for (i=0;i<ARRAY_SIZE(ctdb_commands);i++) {
5138                 if (strcmp(control, ctdb_commands[i].name) == 0) {
5139                         int j;
5140
5141                         if (ctdb_commands[i].without_daemon == true) {
5142                                 close(2);
5143                         }
5144
5145                         /* initialise ctdb */
5146                         ctdb = ctdb_cmdline_client(ev);
5147
5148                         if (ctdb_commands[i].without_daemon == false) {
5149                                 const char *socket_name;
5150
5151                                 if (ctdb == NULL) {
5152                                         DEBUG(DEBUG_ERR, ("Failed to init ctdb\n"));
5153                                         exit(1);
5154                                 }
5155
5156                                 /* initialize a libctdb connection as well */
5157                                 socket_name = ctdb_get_socketname(ctdb);
5158                                 ctdb_connection = ctdb_connect(socket_name,
5159                                                        ctdb_log_file, stderr);
5160                                 if (ctdb_connection == NULL) {
5161                                         fprintf(stderr, "Failed to connect to daemon from libctdb\n");
5162                                         exit(1);
5163                                 }                               
5164                         
5165                                 /* verify the node exists */
5166                                 verify_node(ctdb);
5167
5168                                 if (options.pnn == CTDB_CURRENT_NODE) {
5169                                         int pnn;
5170                                         pnn = ctdb_ctrl_getpnn(ctdb, TIMELIMIT(), options.pnn);         
5171                                         if (pnn == -1) {
5172                                                 return -1;
5173                                         }
5174                                         options.pnn = pnn;
5175                                 }
5176                         }
5177
5178                         if (ctdb_commands[i].auto_all && 
5179                             options.pnn == CTDB_BROADCAST_ALL) {
5180                                 uint32_t *nodes;
5181                                 uint32_t num_nodes;
5182                                 ret = 0;
5183
5184                                 nodes = ctdb_get_connected_nodes(ctdb, TIMELIMIT(), ctdb, &num_nodes);
5185                                 CTDB_NO_MEMORY(ctdb, nodes);
5186         
5187                                 for (j=0;j<num_nodes;j++) {
5188                                         options.pnn = nodes[j];
5189                                         ret |= ctdb_commands[i].fn(ctdb, extra_argc-1, extra_argv+1);
5190                                 }
5191                                 talloc_free(nodes);
5192                         } else {
5193                                 ret = ctdb_commands[i].fn(ctdb, extra_argc-1, extra_argv+1);
5194                         }
5195                         break;
5196                 }
5197         }
5198
5199         if (i == ARRAY_SIZE(ctdb_commands)) {
5200                 DEBUG(DEBUG_ERR, ("Unknown control '%s'\n", control));
5201                 exit(1);
5202         }
5203
5204         return ret;
5205 }