7f3a2d1eda5947444f60a7e23392e893c7642b26
[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() { if (b_) 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 return _app.check();
134 }
135
136 bool Server::validate()
137 {
138 return _magic == MAGIC_MEMORY;
139 }
140
141 // If the server exists, kill it
142 bool Server::cycle()
143 {
144 uint32_t limit= 3;
145
146 // Try to ping, and kill the server #limit number of times
147 while (--limit and
148 is_pid_valid(_app.pid()))
149 {
150 if (kill())
151 {
152 Log << "Killed existing server," << *this;
153 dream(0, 50000);
154 continue;
155 }
156 }
157
158 // For whatever reason we could not kill it, and we reached limit
159 if (limit == 0)
160 {
161 Error << "Reached limit, could not kill server";
162 return false;
163 }
164
165 return true;
166 }
167
168 bool Server::wait_for_pidfile() const
169 {
170 Wait wait(pid_file(), 4);
171
172 return wait.successful();
173 }
174
175 bool Server::init(const char *argv[])
176 {
177 if (argv)
178 {
179 for (const char **ptr= argv; *ptr ; ++ptr)
180 {
181 if (ptr)
182 {
183 add_option(*ptr);
184 }
185 }
186 }
187
188 return build();
189 }
190
191 bool Server::has_pid() const
192 {
193 return (_app.pid() > 1);
194 }
195
196
197 bool Server::start()
198 {
199 if (getenv("YATL_GDB_SERVER"))
200 {
201 _app.use_gdb(true);
202 }
203
204 if (port() == LIBTEST_FAIL_PORT)
205 {
206 throw libtest::disconnected(LIBYATL_DEFAULT_PARAM,
207 hostname(), port(), "Called failure");
208 }
209
210 if (getenv("YATL_PTRCHECK_SERVER"))
211 {
212 _app.use_ptrcheck(true);
213 }
214 else if (getenv("YATL_VALGRIND_SERVER"))
215 {
216 _app.use_valgrind(true);
217 }
218
219 out_of_ban_killed(false);
220 if (args(_app) == false)
221 {
222 throw libtest::disconnected(LIBYATL_DEFAULT_PARAM,
223 hostname(), port(), "Could not build command()");
224 }
225
226 libtest::release_port(_port);
227
228 Application::error_t ret;
229 if (Application::SUCCESS != (ret= _app.run()))
230 {
231 throw libtest::disconnected(LIBYATL_DEFAULT_PARAM,
232 hostname(), port(), "Application::run() %s", libtest::Application::toString(ret));
233 return false;
234 }
235 _running= _app.print();
236
237 if (valgrind_is_caller())
238 {
239 dream(5, 50000);
240 }
241
242 size_t repeat= 5;
243 _app.slurp();
244 while (--repeat)
245 {
246 if (pid_file().empty() == false)
247 {
248 Wait wait(pid_file(), 8);
249
250 if (wait.successful() == false)
251 {
252 if (_app.check())
253 {
254 _app.slurp();
255 continue;
256 }
257
258 #ifdef __GLIBC__
259 Buffer buf( get_current_dir_name());
260 char *getcwd_buf= buf.buf();
261 #else
262 libtest::vchar_t buf;
263 buf.resize(PATH_MAX);
264 char *getcwd_buf= getcwd(&buf[0], buf.size());
265 #endif // __GLIBC__
266 throw libtest::disconnected(LIBYATL_DEFAULT_PARAM,
267 hostname(), port(),
268 "Unable to open pidfile in %s for: %s stderr:%s",
269 getcwd_buf ? getcwd_buf : "",
270 _running.c_str(),
271 _app.stderr_c_str());
272 }
273 }
274 }
275
276 bool pinged= false;
277 uint32_t this_wait= 0;
278 {
279 uint32_t waited;
280 uint32_t retry;
281
282 for (waited= 0, retry= 1; ; retry++, waited+= this_wait)
283 {
284 if (_app.check() == false)
285 {
286 break;
287 }
288
289 if ((pinged= ping()) == true)
290 {
291 break;
292 }
293 else if (waited >= _timeout)
294 {
295 break;
296 }
297
298 this_wait= retry * retry / 3 + 1;
299 libtest::dream(this_wait, 0);
300 }
301 }
302
303 if (pinged == false)
304 {
305 #if 0
306 Error << "Failed to ping(" << _app.pid() << ") wait: " << this_wait << " " << hostname() << ":" << port() << " run:" << _running << " " << error();
307 #endif
308
309 // If we happen to have a pid file, lets try to kill it
310 if ((pid_file().empty() == false) and (access(pid_file().c_str(), R_OK) == 0))
311 {
312 _app.slurp();
313 if (kill_file(pid_file()) == false)
314 {
315 throw libtest::disconnected(LIBYATL_DEFAULT_PARAM,
316 hostname(), port(),
317 "Failed to kill off server, waited: %u after startup occurred, when pinging failed: %.*s stderr:%.*s",
318 this_wait,
319 int(_running.size()), _running.c_str(),
320 int(_app.stderr_result_length()), _app.stderr_c_str());
321 }
322 else
323 {
324 throw libtest::disconnected(LIBYATL_DEFAULT_PARAM,
325 hostname(), port(),
326 "Failed native ping(), pid: %d was alive: %s waited: %u server started, having pid_file. exec: %.*s stderr:%.*s",
327 int(_app.pid()),
328 _app.check() ? "true" : "false",
329 this_wait,
330 int(_running.size()), _running.c_str(),
331 int(_app.stderr_result_length()), _app.stderr_c_str());
332 }
333 }
334 else
335 {
336 throw libtest::disconnected(LIBYATL_DEFAULT_PARAM,
337 hostname(), port(),
338 "Failed native ping(), pid: %d is alive: %s waited: %u server started. exec: %.*s stderr:%.*s",
339 int(_app.pid()),
340 _app.check() ? "true" : "false",
341 this_wait,
342 int(_running.size()), _running.c_str(),
343 int(_app.stderr_result_length()), _app.stderr_c_str());
344 }
345 _running.clear();
346
347 return false;
348 }
349
350 return has_pid();
351 }
352
353 void Server::reset_pid()
354 {
355 _running.clear();
356 _pid_file.clear();
357 }
358
359 pid_t Server::pid() const
360 {
361 return _app.pid();
362 }
363
364 void Server::add_option(const std::string& arg)
365 {
366 _options.push_back(std::make_pair(arg, std::string()));
367 }
368
369 void Server::add_option(const std::string& name_, const std::string& value_)
370 {
371 _options.push_back(std::make_pair(name_, value_));
372 }
373
374 bool Server::set_socket_file()
375 {
376 libtest::vchar_t file_buffer;
377 file_buffer.resize(FILENAME_MAX);
378 file_buffer[0]= 0;
379
380 if (broken_pid_file())
381 {
382 snprintf(&file_buffer[0], file_buffer.size(), "/tmp/%s.socketXXXXXX", name());
383 }
384 else
385 {
386 snprintf(&file_buffer[0], file_buffer.size(), "var/run/%s.socketXXXXXX", name());
387 }
388
389 int fd;
390 if ((fd= mkstemp(&file_buffer[0])) == -1)
391 {
392 perror(&file_buffer[0]);
393 return false;
394 }
395 close(fd);
396 unlink(&file_buffer[0]);
397
398 _socket= &file_buffer[0];
399
400 return true;
401 }
402
403 bool Server::set_pid_file()
404 {
405 libtest::vchar_t file_buffer;
406 file_buffer.resize(FILENAME_MAX);
407 file_buffer[0]= 0;
408
409 if (broken_pid_file())
410 {
411 snprintf(&file_buffer[0], file_buffer.size(), "/tmp/%s.pidXXXXXX", name());
412 }
413 else
414 {
415 snprintf(&file_buffer[0], file_buffer.size(), "var/run/%s.pidXXXXXX", name());
416 }
417
418 int fd;
419 if ((fd= mkstemp(&file_buffer[0])) == -1)
420 {
421 throw libtest::fatal(LIBYATL_DEFAULT_PARAM, "mkstemp() failed on %s with %s", &file_buffer[0], strerror(errno));
422 }
423 close(fd);
424 unlink(&file_buffer[0]);
425
426 _pid_file= &file_buffer[0];
427
428 return true;
429 }
430
431 bool Server::set_log_file()
432 {
433 libtest::vchar_t file_buffer;
434 file_buffer.resize(FILENAME_MAX);
435 file_buffer[0]= 0;
436
437 snprintf(&file_buffer[0], file_buffer.size(), "var/log/%s.logXXXXXX", name());
438 int fd;
439 if ((fd= mkstemp(&file_buffer[0])) == -1)
440 {
441 throw libtest::fatal(LIBYATL_DEFAULT_PARAM, "mkstemp() failed on %s with %s", &file_buffer[0], strerror(errno));
442 }
443 close(fd);
444
445 _log_file= &file_buffer[0];
446
447 return true;
448 }
449
450 bool Server::args(Application& app)
451 {
452
453 // Set a log file if it was requested (and we can)
454 if (has_log_file_option())
455 {
456 set_log_file();
457 log_file_option(app, _log_file);
458 }
459
460 if (getenv("LIBTEST_SYSLOG") and has_syslog())
461 {
462 app.add_option("--syslog");
463 }
464
465 // Update pid_file
466 {
467 if (_pid_file.empty() and set_pid_file() == false)
468 {
469 return false;
470 }
471
472 pid_file_option(app, pid_file());
473 }
474
475 if (has_socket_file_option())
476 {
477 if (set_socket_file() == false)
478 {
479 return false;
480 }
481
482 socket_file_option(app, _socket);
483 }
484
485 if (has_port_option())
486 {
487 port_option(app, _port);
488 }
489
490 for (Options::const_iterator iter= _options.begin(); iter != _options.end(); ++iter)
491 {
492 if ((*iter).first.empty() == false)
493 {
494 if ((*iter).second.empty() == false)
495 {
496 app.add_option((*iter).first, (*iter).second);
497 }
498 else
499 {
500 app.add_option((*iter).first);
501 }
502 }
503 }
504
505 return true;
506 }
507
508 bool Server::kill()
509 {
510 if (check_pid(_app.pid())) // If we kill it, reset
511 {
512 _app.murder();
513 if (broken_pid_file() and pid_file().empty() == false)
514 {
515 unlink(pid_file().c_str());
516 }
517
518 if (broken_socket_cleanup() and has_socket() and not socket().empty())
519 {
520 unlink(socket().c_str());
521 }
522
523 reset_pid();
524
525 return true;
526 }
527
528 return false;
529 }
530
531 } // namespace libtest