a80a181239fb1f7d9ac42b486cac7370a7a5aaa8
[awesomized/libmemcached] / libtest / server.cc
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
37 #include "libtest/yatlcon.h"
38
39 #include <libtest/common.h>
40
41 #include <cassert>
42 #include <cerrno>
43 #include <climits>
44 #include <cstdlib>
45 #include <iostream>
46
47 #include <algorithm>
48 #include <functional>
49 #include <locale>
50 #include <unistd.h>
51
52 // trim from end
53 static inline std::string &rtrim(std::string &s)
54 {
55 s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
56 return s;
57 }
58
59 #include <libtest/server.h>
60 #include <libtest/stream.h>
61 #include <libtest/killpid.h>
62
63 namespace libtest {
64
65 std::ostream& operator<<(std::ostream& output, const Server &arg)
66 {
67 if (arg.is_socket())
68 {
69 output << arg.hostname();
70 }
71 else
72 {
73 output << arg.hostname() << ":" << arg.port();
74 }
75
76 if (arg.has_pid())
77 {
78 output << " Pid:" << arg.pid();
79 }
80
81 if (arg.has_socket())
82 {
83 output << " Socket:" << arg.socket();
84 }
85
86 if (arg.running().empty() == false)
87 {
88 output << " Exec:" << arg.running();
89 }
90
91 return output; // for multiple << operators
92 }
93
94 #ifdef __GLIBC__
95 namespace {
96
97 class Buffer
98 {
99 public:
100 Buffer(char *b) : b_(b) {}
101 ~Buffer() { free(b_); }
102 char* buf() { return b_; }
103 private:
104 char *b_;
105 };
106
107 }
108 #endif // __GLIBC__
109
110 #define MAGIC_MEMORY 123570
111
112 Server::Server(const std::string& host_arg, const in_port_t port_arg,
113 const std::string& executable, const bool _is_libtool,
114 bool is_socket_arg) :
115 _magic(MAGIC_MEMORY),
116 _is_socket(is_socket_arg),
117 _port(port_arg),
118 _hostname(host_arg),
119 _app(executable, _is_libtool),
120 out_of_ban_killed_(false),
121 _timeout(40)
122 {
123 }
124
125 Server::~Server()
126 {
127 kill();
128 }
129
130 bool Server::check()
131 {
132 _app.slurp();
133 _app.check();
134 return true;
135 }
136
137 bool Server::validate()
138 {
139 return _magic == MAGIC_MEMORY;
140 }
141
142 // If the server exists, kill it
143 bool Server::cycle()
144 {
145 uint32_t limit= 3;
146
147 // Try to ping, and kill the server #limit number of times
148 while (--limit and
149 is_pid_valid(_app.pid()))
150 {
151 if (kill())
152 {
153 Log << "Killed existing server," << *this;
154 dream(0, 50000);
155 continue;
156 }
157 }
158
159 // For whatever reason we could not kill it, and we reached limit
160 if (limit == 0)
161 {
162 Error << "Reached limit, could not kill server";
163 return false;
164 }
165
166 return true;
167 }
168
169 bool Server::wait_for_pidfile() const
170 {
171 Wait wait(pid_file(), 4);
172
173 return wait.successful();
174 }
175
176 bool Server::has_pid() const
177 {
178 return (_app.pid() > 1);
179 }
180
181
182 bool Server::start()
183 {
184 // If we find that we already have a pid then kill it.
185 if (has_pid() == true)
186 {
187 #if 0
188 fatal_message("has_pid() failed, programer error");
189 #endif
190 }
191
192 // This needs more work.
193 #if 0
194 if (gdb_is_caller())
195 {
196 _app.use_gdb();
197 }
198 #endif
199
200 if (port() == LIBTEST_FAIL_PORT)
201 {
202 throw libtest::disconnected(LIBYATL_DEFAULT_PARAM,
203 hostname(), port(), "Called failure");
204 }
205
206 if (getenv("YATL_PTRCHECK_SERVER"))
207 {
208 _app.use_ptrcheck();
209 }
210 else if (getenv("YATL_VALGRIND_SERVER"))
211 {
212 _app.use_valgrind();
213 }
214
215 out_of_ban_killed(false);
216 if (args(_app) == false)
217 {
218 throw libtest::disconnected(LIBYATL_DEFAULT_PARAM,
219 hostname(), port(), "Could not build command()");
220 }
221
222 libtest::release_port(_port);
223
224 Application::error_t ret;
225 if (Application::SUCCESS != (ret= _app.run()))
226 {
227 throw libtest::disconnected(LIBYATL_DEFAULT_PARAM,
228 hostname(), port(), "Application::run() %s", libtest::Application::toString(ret));
229 return false;
230 }
231 _running= _app.print();
232
233 if (valgrind_is_caller())
234 {
235 dream(5, 50000);
236 }
237
238 size_t repeat= 5;
239 _app.slurp();
240 while (--repeat)
241 {
242 if (pid_file().empty() == false)
243 {
244 Wait wait(pid_file(), 8);
245
246 if (wait.successful() == false)
247 {
248 if (_app.check())
249 {
250 _app.slurp();
251 continue;
252 }
253
254 #ifdef __GLIBC__
255 Buffer buf( get_current_dir_name());
256 char *getcwd_buf= buf.buf();
257 #else
258 libtest::vchar_t buf;
259 buf.resize(PATH_MAX);
260 char *getcwd_buf= getcwd(&buf[0], buf.size());
261 #endif // __GLIBC__
262 throw libtest::disconnected(LIBYATL_DEFAULT_PARAM,
263 hostname(), port(),
264 "Unable to open pidfile in %s for: %s stderr:%s",
265 getcwd_buf ? getcwd_buf : "",
266 _running.c_str(),
267 _app.stderr_c_str());
268 }
269 }
270 }
271
272 bool pinged= false;
273 uint32_t this_wait= 0;
274 {
275 uint32_t waited;
276 uint32_t retry;
277
278 for (waited= 0, retry= 7; ; retry++, waited+= this_wait)
279 {
280 if (_app.check() == false)
281 {
282 break;
283 }
284
285 if ((pinged= ping()) == true)
286 {
287 break;
288 }
289 else if (waited >= _timeout)
290 {
291 break;
292 }
293
294 Error << "ping(" << _app.pid() << ") wait: " << this_wait << " " << hostname() << ":" << port() << " " << error();
295
296 this_wait= retry * retry / 3 + 1;
297 libtest::dream(this_wait, 0);
298 }
299 }
300
301 if (pinged == false)
302 {
303 // If we happen to have a pid file, lets try to kill it
304 if ((pid_file().empty() == false) and (access(pid_file().c_str(), R_OK) == 0))
305 {
306 _app.slurp();
307 if (kill_file(pid_file()) == false)
308 {
309 throw libtest::disconnected(LIBYATL_DEFAULT_PARAM,
310 hostname(), port(),
311 "Failed to kill off server, waited: %u after startup occurred, when pinging failed: %.*s stderr:%.*s",
312 this_wait,
313 int(_running.size()), _running.c_str(),
314 int(_app.stderr_result_length()), _app.stderr_c_str());
315 }
316 else
317 {
318 throw libtest::disconnected(LIBYATL_DEFAULT_PARAM,
319 hostname(), port(),
320 "Failed native ping(), pid: %d was alive: %s waited: %u server started, having pid_file. exec: %.*s stderr:%.*s",
321 int(_app.pid()),
322 _app.check() ? "true" : "false",
323 this_wait,
324 int(_running.size()), _running.c_str(),
325 int(_app.stderr_result_length()), _app.stderr_c_str());
326 }
327 }
328 else
329 {
330 throw libtest::disconnected(LIBYATL_DEFAULT_PARAM,
331 hostname(), port(),
332 "Failed native ping(), pid: %d is alive: %s waited: %u server started. exec: %.*s stderr:%.*s",
333 int(_app.pid()),
334 _app.check() ? "true" : "false",
335 this_wait,
336 int(_running.size()), _running.c_str(),
337 int(_app.stderr_result_length()), _app.stderr_c_str());
338 }
339 _running.clear();
340
341 return false;
342 }
343
344 return has_pid();
345 }
346
347 void Server::reset_pid()
348 {
349 _running.clear();
350 _pid_file.clear();
351 }
352
353 pid_t Server::pid() const
354 {
355 return _app.pid();
356 }
357
358 void Server::add_option(const std::string& arg)
359 {
360 _options.push_back(std::make_pair(arg, std::string()));
361 }
362
363 void Server::add_option(const std::string& name_, const std::string& value_)
364 {
365 _options.push_back(std::make_pair(name_, value_));
366 }
367
368 bool Server::set_socket_file()
369 {
370 libtest::vchar_t file_buffer;
371 file_buffer.resize(FILENAME_MAX);
372 file_buffer[0]= 0;
373
374 if (broken_pid_file())
375 {
376 snprintf(&file_buffer[0], file_buffer.size(), "/tmp/%s.socketXXXXXX", name());
377 }
378 else
379 {
380 snprintf(&file_buffer[0], file_buffer.size(), "var/run/%s.socketXXXXXX", name());
381 }
382
383 int fd;
384 if ((fd= mkstemp(&file_buffer[0])) == -1)
385 {
386 perror(&file_buffer[0]);
387 return false;
388 }
389 close(fd);
390 unlink(&file_buffer[0]);
391
392 _socket= &file_buffer[0];
393
394 return true;
395 }
396
397 bool Server::set_pid_file()
398 {
399 libtest::vchar_t file_buffer;
400 file_buffer.resize(FILENAME_MAX);
401 file_buffer[0]= 0;
402
403 if (broken_pid_file())
404 {
405 snprintf(&file_buffer[0], file_buffer.size(), "/tmp/%s.pidXXXXXX", name());
406 }
407 else
408 {
409 snprintf(&file_buffer[0], file_buffer.size(), "var/run/%s.pidXXXXXX", name());
410 }
411
412 int fd;
413 if ((fd= mkstemp(&file_buffer[0])) == -1)
414 {
415 throw libtest::fatal(LIBYATL_DEFAULT_PARAM, "mkstemp() failed on %s with %s", &file_buffer[0], strerror(errno));
416 }
417 close(fd);
418 unlink(&file_buffer[0]);
419
420 _pid_file= &file_buffer[0];
421
422 return true;
423 }
424
425 bool Server::set_log_file()
426 {
427 libtest::vchar_t file_buffer;
428 file_buffer.resize(FILENAME_MAX);
429 file_buffer[0]= 0;
430
431 snprintf(&file_buffer[0], file_buffer.size(), "var/log/%s.logXXXXXX", name());
432 int fd;
433 if ((fd= mkstemp(&file_buffer[0])) == -1)
434 {
435 throw libtest::fatal(LIBYATL_DEFAULT_PARAM, "mkstemp() failed on %s with %s", &file_buffer[0], strerror(errno));
436 }
437 close(fd);
438
439 _log_file= &file_buffer[0];
440
441 return true;
442 }
443
444 bool Server::args(Application& app)
445 {
446
447 // Set a log file if it was requested (and we can)
448 if (has_log_file_option())
449 {
450 set_log_file();
451 log_file_option(app, _log_file);
452 }
453
454 if (getenv("LIBTEST_SYSLOG") and has_syslog())
455 {
456 app.add_option("--syslog");
457 }
458
459 // Update pid_file
460 {
461 if (_pid_file.empty() and set_pid_file() == false)
462 {
463 return false;
464 }
465
466 pid_file_option(app, pid_file());
467 }
468
469 if (has_socket_file_option())
470 {
471 if (set_socket_file() == false)
472 {
473 return false;
474 }
475
476 socket_file_option(app, _socket);
477 }
478
479 if (has_port_option())
480 {
481 port_option(app, _port);
482 }
483
484 for (Options::const_iterator iter= _options.begin(); iter != _options.end(); ++iter)
485 {
486 if ((*iter).second.empty() == false)
487 {
488 app.add_option((*iter).first, (*iter).second);
489 }
490 else
491 {
492 app.add_option((*iter).first);
493 }
494 }
495
496 return true;
497 }
498
499 bool Server::kill()
500 {
501 if (check_pid(_app.pid())) // If we kill it, reset
502 {
503 _app.murder();
504 if (broken_pid_file() and pid_file().empty() == false)
505 {
506 unlink(pid_file().c_str());
507 }
508
509 if (broken_socket_cleanup() and has_socket() and not socket().empty())
510 {
511 unlink(socket().c_str());
512 }
513
514 reset_pid();
515
516 return true;
517 }
518
519 return false;
520 }
521
522 } // namespace libtest