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