1 // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
2 // vim: ts=8 sw=2 smarttab
4 * Ceph - scalable distributed file system
6 * Copyright (C) 2011 New Dream Network
8 * This is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License version 2.1, as published by the Free Software
11 * Foundation. See file COPYING.
15 #include "common/admin_socket.h"
16 #include "common/errno.h"
17 #include "common/safe_io.h"
18 #include "common/admin_socket_client.h"
22 using std::ostringstream;
24 const char* get_rand_socket_path()
26 static char *g_socket_path = NULL;
28 if (g_socket_path == NULL) {
30 const char *tdir = getenv("TMPDIR");
34 snprintf(buf, sizeof(((struct sockaddr_un*)0)->sun_path),
35 "%s/perfcounters_test_socket.%ld.%ld",
36 tdir, (long int)getpid(), time(NULL));
37 g_socket_path = (char*)strdup(buf);
42 static std::string asok_connect(const std::string &path, int *fd)
44 int socket_fd = socket(PF_UNIX, SOCK_STREAM, 0);
48 oss << "socket(PF_UNIX, SOCK_STREAM, 0) failed: " << cpp_strerror(err);
52 struct sockaddr_un address;
53 memset(&address, 0, sizeof(struct sockaddr_un));
54 address.sun_family = AF_UNIX;
55 snprintf(address.sun_path, sizeof(address.sun_path), "%s", path.c_str());
57 if (::connect(socket_fd, (struct sockaddr *) &address,
58 sizeof(struct sockaddr_un)) != 0) {
61 oss << "connect(" << socket_fd << ") failed: " << cpp_strerror(err);
69 if (::setsockopt(socket_fd, SOL_SOCKET, SO_RCVTIMEO, &timer, sizeof(timer))) {
72 oss << "setsockopt(" << socket_fd << ", SO_RCVTIMEO) failed: "
79 if (::setsockopt(socket_fd, SOL_SOCKET, SO_SNDTIMEO, &timer, sizeof(timer))) {
82 oss << "setsockopt(" << socket_fd << ", SO_SNDTIMEO) failed: "
92 static std::string asok_request(int socket_fd, std::string request)
94 ssize_t res = safe_write(socket_fd, request.c_str(), request.length() + 1);
98 oss << "safe_write(" << socket_fd << ") failed to write request code: "
106 AdminSocketClient(const std::string &path)
111 std::string AdminSocketClient::ping(bool *ok)
114 std::string result = do_request("{\"prefix\":\"0\"}", &version);
115 *ok = result == "" && version.length() == 1;
119 std::string AdminSocketClient::do_request(std::string request, std::string *result)
121 int socket_fd = 0, res;
123 uint32_t message_size_raw, message_size;
125 std::string err = asok_connect(m_path, &socket_fd);
129 err = asok_request(socket_fd, request);
133 res = safe_read_exact(socket_fd, &message_size_raw,
134 sizeof(message_size_raw));
138 oss << "safe_read(" << socket_fd << ") failed to read message size: "
143 message_size = ntohl(message_size_raw);
144 buffer.resize(message_size, 0);
145 res = safe_read_exact(socket_fd, &buffer[0], message_size);
149 oss << "safe_read(" << socket_fd << ") failed: " << cpp_strerror(e);
153 //printf("MESSAGE FROM SERVER: %s\n", buffer.c_str());
154 std::swap(*result, buffer);