6058bc67df9cabeb2240081963233024a275b9bf
[awesomized/libmemcached] / src / bin / memping.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 Michael Wallner <mike@php.net> |
13 +--------------------------------------------------------------------+
14 */
15
16 #include "mem_config.h"
17
18 #define PROGRAM_NAME "memping"
19 #define PROGRAM_DESCRIPTION "Ping a server or a set of servers."
20 #define PROGRAM_VERSION "1.1"
21
22 #include "common/options.hpp"
23 #include "common/checks.hpp"
24
25 #include "libmemcached/util.h"
26
27 static memcached_return_t ping(const memcached_st *memc, const memcached_instance_st *s, void *ctx) {
28 auto opt = static_cast<client_options *>(ctx);
29 memcached_return_t rc;
30 bool ok;
31
32 if (opt->isset("debug")) {
33 std::cerr << "Trying to ping" << s->_hostname << ":" << s->port() << ".\n";
34 }
35
36 if (auto username = opt->argof("username")) {
37 auto password = opt->argof("password");
38 ok = libmemcached_util_ping2(s->_hostname, s->port(), username, password, &rc);
39 } else {
40 ok = libmemcached_util_ping(s->_hostname, s->port(), &rc);
41 }
42 if (!ok && !opt->isset("quiet")) {
43 std::cerr << "Failed to ping '" << s->_hostname << ":" << s->port()
44 << ":" << memcached_strerror(memc, rc) << ".\n";
45 }
46
47 return rc;
48 }
49
50 int main(int argc, char *argv[]) {
51 client_options opt{PROGRAM_NAME, PROGRAM_VERSION, PROGRAM_DESCRIPTION};
52
53 for (const auto &def : opt.defaults) {
54 switch (def.opt.val) {
55 case 'h': // --help
56 case 'V': // --version
57 case 'v': // --verbose
58 case 'd': // --debug
59 case 'q': // --quiet
60 case 's': // --servers
61 case 'u': // --username
62 case 'p': // --password
63 opt.add(def);
64 break;
65 default:
66 break;
67 }
68 }
69
70 if (!opt.parse(argc, argv, nullptr)) {
71 exit(EXIT_FAILURE);
72 }
73
74 memcached_st memc;
75 if (!check_memcached(opt, memc)) {
76 exit(EXIT_FAILURE);
77 }
78
79 if (!opt.apply(&memc)) {
80 memcached_free(&memc);
81 exit(EXIT_FAILURE);
82 }
83
84 auto exit_code = EXIT_SUCCESS;
85 memcached_server_fn cb[1] = {&ping};
86 if (!memcached_success(memcached_server_cursor(&memc, cb, &opt, 1))) {
87 exit_code = EXIT_FAILURE;
88 }
89
90 memcached_free(&memc);
91 exit(exit_code);
92 }