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