move repository from m6w6 to awesomized
[m6w6/libmemcached] / src / bin / memdump.cc
1 /*
2 +--------------------------------------------------------------------+
3 | libmemcached - C/C++ Client Library for memcached |
4 +--------------------------------------------------------------------+
5 | Redistribution and use in source and binary forms, with or without |
6 | modification, are permitted under the terms of the BSD license. |
7 | You should have received a copy of the license in a bundled file |
8 | named LICENSE; in case you did not receive a copy you can review |
9 | the terms online at: https://opensource.org/licenses/BSD-3-Clause |
10 +--------------------------------------------------------------------+
11 | Copyright (c) 2006-2014 Brian Aker https://datadifferential.com/ |
12 | Copyright (c) 2020-2021 Michael Wallner https://awesome.co/ |
13 +--------------------------------------------------------------------+
14 */
15
16 #include <fstream>
17 #include "mem_config.h"
18
19 #define PROGRAM_NAME "memdump"
20 #define PROGRAM_DESCRIPTION "Dump all values from one or many servers."
21 #define PROGRAM_VERSION "1.1"
22
23 #include "common/options.hpp"
24 #include "common/checks.hpp"
25
26 static memcached_return_t print(const memcached_st *, const char *k, size_t l, void *ctx) {
27 auto out = static_cast<std::ostream *>(ctx);
28 out->write(k, l);
29 out->put('\n');
30 return MEMCACHED_SUCCESS;
31 }
32
33 int main(int argc, char *argv[]) {
34 client_options opt{PROGRAM_NAME, PROGRAM_VERSION, PROGRAM_DESCRIPTION};
35
36 for (const auto &def : opt.defaults) {
37 switch (def.opt.val) {
38 case 'H': // no need for --hash
39 case 'b': // binary proto not available
40 break;
41 default:
42 opt.add(def);
43 }
44 }
45
46 opt.add("file", 'f', required_argument, "Output to file instead of standard output.");
47
48 if (!opt.parse(argc, argv)) {
49 exit(EXIT_FAILURE);
50 }
51
52 if (opt.isset("quiet") && !opt.isset("file")) {
53 std::cerr << "--quiet operation was requested, but --file was not set.\n";
54 exit(EXIT_FAILURE);
55 }
56
57 memcached_st memc;
58 if (!check_memcached(opt, memc)) {
59 exit(EXIT_FAILURE);
60 }
61
62 if (!opt.apply(&memc)) {
63 exit(EXIT_FAILURE);
64 }
65
66 memcached_dump_fn cb[1] = {&print};
67 std::ofstream outfile{};
68 std::ostream *outstream = check_ostream(opt, opt.argof("file"), outfile);
69
70 auto rc = memcached_dump(&memc, cb, outstream, 1);
71
72 if (outfile) {
73 if (opt.isset("debug")) {
74 std::cerr << "Flushing " << opt.argof("file") << ".\n";
75 }
76 outfile.flush();
77 }
78
79 if (MEMCACHED_SUCCESS != rc) {
80 if (!opt.isset("quiet")) {
81 std::cerr << "Failed to dump keys:" << memcached_last_error_message(&memc) << "\n";
82 }
83 memcached_free(&memc);
84 exit(EXIT_FAILURE);
85 }
86
87 memcached_free(&memc);
88 exit(EXIT_SUCCESS);
89 }