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