server.cc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  1. /* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
  2. *
  3. * Data Differential YATL (i.e. libtest) library
  4. *
  5. * Copyright (C) 2012 Data Differential, http://datadifferential.com/
  6. *
  7. * Redistribution and use in source and binary forms, with or without
  8. * modification, are permitted provided that the following conditions are
  9. * met:
  10. *
  11. * * Redistributions of source code must retain the above copyright
  12. * notice, this list of conditions and the following disclaimer.
  13. *
  14. * * Redistributions in binary form must reproduce the above
  15. * copyright notice, this list of conditions and the following disclaimer
  16. * in the documentation and/or other materials provided with the
  17. * distribution.
  18. *
  19. * * The names of its contributors may not be used to endorse or
  20. * promote products derived from this software without specific prior
  21. * written permission.
  22. *
  23. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  24. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  25. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  26. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  27. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  28. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  29. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  30. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  31. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  32. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  33. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  34. *
  35. */
  36. #include "libtest/yatlcon.h"
  37. #include <libtest/common.h>
  38. #include <cassert>
  39. #include <cerrno>
  40. #include <climits>
  41. #include <cstdlib>
  42. #include <iostream>
  43. #include <algorithm>
  44. #include <functional>
  45. #include <locale>
  46. #include <unistd.h>
  47. #include <libtest/server.h>
  48. #include <libtest/stream.h>
  49. #include <libtest/killpid.h>
  50. namespace libtest {
  51. std::ostream& operator<<(std::ostream& output, const Server &arg)
  52. {
  53. if (arg.is_socket())
  54. {
  55. output << arg.hostname();
  56. }
  57. else
  58. {
  59. output << arg.hostname() << ":" << arg.port();
  60. }
  61. if (arg.has_pid())
  62. {
  63. output << " Pid:" << arg.pid();
  64. }
  65. if (arg.has_socket())
  66. {
  67. output << " Socket:" << arg.socket();
  68. }
  69. if (arg.running().empty() == false)
  70. {
  71. output << " Exec:" << arg.running();
  72. }
  73. return output; // for multiple << operators
  74. }
  75. #ifdef __GLIBC__
  76. namespace {
  77. class Buffer
  78. {
  79. public:
  80. Buffer(char *b) : b_(b) {}
  81. ~Buffer() { if (b_) free(b_); }
  82. char* buf() { return b_; }
  83. private:
  84. char *b_;
  85. };
  86. }
  87. #endif // __GLIBC__
  88. #define MAGIC_MEMORY 123570
  89. Server::Server(const std::string& host_arg, const in_port_t port_arg,
  90. const std::string& executable, const bool _is_libtool,
  91. bool is_socket_arg) :
  92. _magic(MAGIC_MEMORY),
  93. _is_socket(is_socket_arg),
  94. _port(port_arg),
  95. _hostname(host_arg),
  96. _app(executable, _is_libtool),
  97. out_of_ban_killed_(false),
  98. _error_file{nullptr},
  99. _error_line{},
  100. _timeout(40)
  101. {
  102. }
  103. Server::~Server()
  104. {
  105. kill();
  106. }
  107. bool Server::check()
  108. {
  109. _app.slurp();
  110. _app.check();
  111. return true;
  112. }
  113. bool Server::validate()
  114. {
  115. return _magic == MAGIC_MEMORY;
  116. }
  117. // If the server exists, kill it
  118. bool Server::cycle()
  119. {
  120. uint32_t limit= 3;
  121. // Try to ping, and kill the server #limit number of times
  122. while (--limit and
  123. is_pid_valid(_app.pid()))
  124. {
  125. if (kill())
  126. {
  127. Log << "Killed existing server," << *this;
  128. dream(0, 50000);
  129. continue;
  130. }
  131. }
  132. // For whatever reason we could not kill it, and we reached limit
  133. if (limit == 0)
  134. {
  135. Error << "Reached limit, could not kill server";
  136. return false;
  137. }
  138. return true;
  139. }
  140. bool Server::wait_for_pidfile() const
  141. {
  142. Wait wait(pid_file(), 4);
  143. return wait.successful();
  144. }
  145. bool Server::init(const char *argv[])
  146. {
  147. for (const char **ptr= argv; ptr && *ptr ; ++ptr)
  148. {
  149. add_option(*ptr);
  150. }
  151. return build();
  152. }
  153. bool Server::has_pid() const
  154. {
  155. return (_app.pid() > 1);
  156. }
  157. bool Server::is_valgrind() const
  158. {
  159. return getenv("YATL_VALGRIND_SERVER") or valgrind_is_caller();
  160. }
  161. #pragma GCC diagnostic push
  162. #pragma GCC diagnostic ignored "-Wunreachable-code"
  163. bool Server::start()
  164. {
  165. // If we find that we already have a pid then kill it.
  166. if (has_pid() == true)
  167. {
  168. #if 0
  169. fatal_message("has_pid() failed, programer error");
  170. #endif
  171. }
  172. if (getenv("YATL_GDB_SERVER"))
  173. {
  174. _app.use_gdb(true);
  175. }
  176. if (port() == LIBTEST_FAIL_PORT)
  177. {
  178. throw libtest::disconnected(LIBYATL_DEFAULT_PARAM,
  179. hostname(), port(), "Called failure");
  180. }
  181. if (getenv("YATL_PTRCHECK_SERVER"))
  182. {
  183. _app.use_ptrcheck(true);
  184. }
  185. else if (is_valgrind())
  186. {
  187. _app.use_valgrind(true);
  188. }
  189. out_of_ban_killed(false);
  190. if (args(_app) == false)
  191. {
  192. throw libtest::disconnected(LIBYATL_DEFAULT_PARAM,
  193. hostname(), port(), "Could not build command()");
  194. }
  195. libtest::release_port(_port);
  196. Application::error_t ret;
  197. if (Application::SUCCESS != (ret= _app.run()))
  198. {
  199. throw libtest::disconnected(LIBYATL_DEFAULT_PARAM,
  200. hostname(), port(), "Application::run() %s", libtest::Application::toString(ret));
  201. return false;
  202. }
  203. _running= _app.print();
  204. if (valgrind_is_caller())
  205. {
  206. dream(5, 50000);
  207. }
  208. size_t repeat= 5;
  209. _app.slurp();
  210. while (--repeat)
  211. {
  212. if (pid_file().empty() == false)
  213. {
  214. Wait wait(pid_file(), 8);
  215. if (wait.successful() == false)
  216. {
  217. if (_app.check())
  218. {
  219. _app.slurp();
  220. continue;
  221. }
  222. #ifdef __GLIBC__
  223. Buffer buf( get_current_dir_name());
  224. char *getcwd_buf= buf.buf();
  225. #else
  226. libtest::vchar_t buf;
  227. buf.resize(PATH_MAX);
  228. char *getcwd_buf= getcwd(&buf[0], buf.size());
  229. #endif // __GLIBC__
  230. throw libtest::disconnected(LIBYATL_DEFAULT_PARAM,
  231. hostname(), port(),
  232. "Unable to open pidfile in %s for: %s stderr:%s",
  233. getcwd_buf ? getcwd_buf : "",
  234. _running.c_str(),
  235. _app.stderr_c_str());
  236. }
  237. }
  238. }
  239. bool pinged= false;
  240. uint32_t this_wait= 0;
  241. {
  242. uint32_t waited;
  243. uint32_t retry;
  244. for (waited= 0, retry= 1; ; retry++, waited+= this_wait)
  245. {
  246. if (_app.check() == false)
  247. {
  248. break;
  249. }
  250. if ((pinged= ping()) == true)
  251. {
  252. break;
  253. }
  254. else if (waited >= _timeout)
  255. {
  256. break;
  257. }
  258. this_wait= retry * retry / 3 + 1;
  259. libtest::dream(this_wait, 0);
  260. }
  261. }
  262. if (pinged == false)
  263. {
  264. #if 0
  265. Error << "Failed to ping(" << _app.pid() << ") wait: " << this_wait << " " << hostname() << ":" << port() << " run:" << _running << " " << error();
  266. #endif
  267. // If we happen to have a pid file, lets try to kill it
  268. if ((pid_file().empty() == false) and (access(pid_file().c_str(), R_OK) == 0))
  269. {
  270. _app.slurp();
  271. if (kill_file(pid_file()) == false)
  272. {
  273. throw libtest::disconnected(error_file(), error_line(), __PRETTY_FUNCTION__,
  274. hostname(), port(),
  275. "ping(%s) additionally failed to kill off server, waited: %u after startup occurred failed: %.*s error:%s stderr:%.*s",
  276. error().c_str(),
  277. this_wait,
  278. int(_running.size()), _running.c_str(),
  279. int(_app.stderr_result_length()), _app.stderr_c_str());
  280. }
  281. else
  282. {
  283. throw libtest::disconnected(error_file(), error_line(), __PRETTY_FUNCTION__,
  284. hostname(), port(),
  285. "ping(%s) additionally failed pid: %d was alive: %s waited: %u server started, having pid_file. exec: %.*s stderr:%.*s",
  286. error().c_str(),
  287. int(_app.pid()),
  288. _app.check() ? "true" : "false",
  289. this_wait,
  290. int(_running.size()), _running.c_str(),
  291. int(_app.stderr_result_length()), _app.stderr_c_str());
  292. }
  293. }
  294. else
  295. {
  296. throw libtest::disconnected(error_file(), error_line(), __PRETTY_FUNCTION__,
  297. hostname(), port(),
  298. "ping(%s), additionally pid: %d is alive: %s waited: %u server started. exec: %.*s stderr:%.*s",
  299. error().c_str(),
  300. int(_app.pid()),
  301. _app.check() ? "true" : "false",
  302. this_wait,
  303. int(_running.size()), _running.c_str(),
  304. int(_app.stderr_result_length()), _app.stderr_c_str());
  305. }
  306. _running.clear();
  307. return false;
  308. }
  309. return has_pid();
  310. }
  311. #pragma GCC diagnostic pop
  312. void Server::reset_pid()
  313. {
  314. _running.clear();
  315. _pid_file.clear();
  316. }
  317. pid_t Server::pid() const
  318. {
  319. return _app.pid();
  320. }
  321. void Server::add_option(const std::string& arg)
  322. {
  323. _options.push_back(std::make_pair(arg, std::string()));
  324. }
  325. void Server::add_option(const std::string& name_, const std::string& value_)
  326. {
  327. _options.push_back(std::make_pair(name_, value_));
  328. }
  329. bool Server::set_socket_file()
  330. {
  331. libtest::vchar_t file_buffer;
  332. file_buffer.resize(FILENAME_MAX);
  333. file_buffer[0]= 0;
  334. if (broken_pid_file())
  335. {
  336. snprintf(&file_buffer[0], file_buffer.size(), "/tmp/%s.socketXXXXXX", name());
  337. }
  338. else
  339. {
  340. snprintf(&file_buffer[0], file_buffer.size(), "var/run/%s.socketXXXXXX", name());
  341. }
  342. int fd;
  343. if ((fd= mkstemp(&file_buffer[0])) == -1)
  344. {
  345. perror(&file_buffer[0]);
  346. return false;
  347. }
  348. close(fd);
  349. unlink(&file_buffer[0]);
  350. _socket= &file_buffer[0];
  351. return true;
  352. }
  353. bool Server::set_pid_file()
  354. {
  355. libtest::vchar_t file_buffer;
  356. file_buffer.resize(FILENAME_MAX);
  357. file_buffer[0]= 0;
  358. if (broken_pid_file())
  359. {
  360. snprintf(&file_buffer[0], file_buffer.size(), "/tmp/%s.pidXXXXXX", name());
  361. }
  362. else
  363. {
  364. snprintf(&file_buffer[0], file_buffer.size(), "var/run/%s.pidXXXXXX", name());
  365. }
  366. int fd;
  367. if ((fd= mkstemp(&file_buffer[0])) == -1)
  368. {
  369. throw libtest::fatal(LIBYATL_DEFAULT_PARAM, "mkstemp() failed on %s with %s", &file_buffer[0], strerror(errno));
  370. }
  371. close(fd);
  372. unlink(&file_buffer[0]);
  373. _pid_file= &file_buffer[0];
  374. return true;
  375. }
  376. bool Server::set_log_file()
  377. {
  378. libtest::vchar_t file_buffer;
  379. file_buffer.resize(FILENAME_MAX);
  380. file_buffer[0]= 0;
  381. snprintf(&file_buffer[0], file_buffer.size(), "var/log/%s.logXXXXXX", name());
  382. int fd;
  383. if ((fd= mkstemp(&file_buffer[0])) == -1)
  384. {
  385. throw libtest::fatal(LIBYATL_DEFAULT_PARAM, "mkstemp() failed on %s with %s", &file_buffer[0], strerror(errno));
  386. }
  387. close(fd);
  388. _log_file= &file_buffer[0];
  389. return true;
  390. }
  391. bool Server::args(Application& app)
  392. {
  393. // Set a log file if it was requested (and we can)
  394. if (has_log_file_option())
  395. {
  396. set_log_file();
  397. log_file_option(app, _log_file);
  398. }
  399. if (getenv("LIBTEST_SYSLOG") and has_syslog())
  400. {
  401. app.add_option("--syslog");
  402. }
  403. // Update pid_file
  404. {
  405. if (_pid_file.empty() and set_pid_file() == false)
  406. {
  407. return false;
  408. }
  409. pid_file_option(app, pid_file());
  410. }
  411. if (has_socket_file_option())
  412. {
  413. if (set_socket_file() == false)
  414. {
  415. return false;
  416. }
  417. socket_file_option(app, _socket);
  418. }
  419. if (has_port_option())
  420. {
  421. port_option(app, _port);
  422. }
  423. for (Options::const_iterator iter= _options.begin(); iter != _options.end(); ++iter)
  424. {
  425. if ((*iter).first.empty() == false)
  426. {
  427. if ((*iter).second.empty() == false)
  428. {
  429. app.add_option((*iter).first, (*iter).second);
  430. }
  431. else
  432. {
  433. app.add_option((*iter).first);
  434. }
  435. }
  436. }
  437. return true;
  438. }
  439. bool Server::kill()
  440. {
  441. if (check_pid(_app.pid())) // If we kill it, reset
  442. {
  443. _app.murder();
  444. if (broken_pid_file() and pid_file().empty() == false)
  445. {
  446. unlink(pid_file().c_str());
  447. }
  448. if (broken_socket_cleanup() and has_socket() and not socket().empty())
  449. {
  450. unlink(socket().c_str());
  451. }
  452. reset_pid();
  453. return true;
  454. }
  455. return false;
  456. }
  457. } // namespace libtest