Merge lp:~tangent-org/libmemcached/1.0-build/ Build: jenkins-Libmemcached-187
[m6w6/libmemcached] / libtest / cmdline.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 using namespace libtest;
42
43 #include <cstdlib>
44 #include <cstring>
45 #include <cerrno>
46 #include <fcntl.h>
47 #include <fstream>
48 #include <memory>
49 #ifdef HAVE_POLL_H
50 # include <poll.h>
51 #endif
52 #ifdef HAVE_SPAWN_H
53 # include <spawn.h>
54 #endif
55 #include <sstream>
56 #include <string>
57 #include <sys/stat.h>
58 #include <sys/types.h>
59 #include <unistd.h>
60
61 #include <algorithm>
62
63 #ifndef __USE_GNU
64 static char **environ= NULL;
65 #endif
66
67 #ifndef FD_CLOEXEC
68 # define FD_CLOEXEC 0
69 #endif
70
71 namespace {
72
73 std::string print_argv(libtest::vchar_ptr_t& built_argv)
74 {
75 std::stringstream arg_buffer;
76
77 for (vchar_ptr_t::iterator iter= built_argv.begin();
78 iter != built_argv.end();
79 ++iter)
80 {
81 arg_buffer << *iter << " ";
82 }
83
84 return arg_buffer.str();
85 }
86
87 #if 0
88 std::string print_argv(char** argv)
89 {
90 std::stringstream arg_buffer;
91
92 for (char** ptr= argv; *ptr; ++ptr)
93 {
94 arg_buffer << *ptr << " ";
95 }
96
97 return arg_buffer.str();
98 }
99 #endif
100
101 static Application::error_t int_to_error_t(int arg)
102 {
103 switch (arg)
104 {
105 case 127:
106 return Application::INVALID_POSIX_SPAWN;
107
108 case 0:
109 return Application::SUCCESS;
110
111 case 1:
112 return Application::FAILURE;
113
114 default:
115 return Application::UNKNOWN;
116 }
117 }
118 }
119
120 namespace libtest {
121
122 Application::Application(const std::string& arg, const bool _use_libtool_arg) :
123 _use_libtool(_use_libtool_arg),
124 _use_valgrind(false),
125 _use_gdb(false),
126 _use_ptrcheck(false),
127 _will_fail(false),
128 _argc(0),
129 _exectuble(arg),
130 stdin_fd(STDIN_FILENO),
131 stdout_fd(STDOUT_FILENO),
132 stderr_fd(STDERR_FILENO),
133 _pid(-1),
134 _status(0),
135 _app_exit_state(UNINITIALIZED)
136 {
137 if (_use_libtool)
138 {
139 if (libtool() == NULL)
140 {
141 fatal_message("libtool requested, but know libtool was found");
142 }
143 }
144
145 // Find just the name of the application with no path
146 {
147 size_t found= arg.find_last_of("/\\");
148 if (found)
149 {
150 _exectuble_name= arg.substr(found +1);
151 }
152 else
153 {
154 _exectuble_name= arg;
155 }
156 }
157
158 if (_use_libtool and getenv("PWD"))
159 {
160 _exectuble_with_path+= getenv("PWD");
161 _exectuble_with_path+= "/";
162 }
163 _exectuble_with_path+= _exectuble;
164 }
165
166 Application::~Application()
167 {
168 murder();
169 delete_argv();
170 }
171
172 Application::error_t Application::run(const char *args[])
173 {
174 stdin_fd.reset();
175 stdout_fd.reset();
176 stderr_fd.reset();
177 _stdout_buffer.clear();
178 _stderr_buffer.clear();
179
180 posix_spawn_file_actions_t file_actions;
181 posix_spawn_file_actions_init(&file_actions);
182
183 stdin_fd.dup_for_spawn(file_actions);
184 stdout_fd.dup_for_spawn(file_actions);
185 stderr_fd.dup_for_spawn(file_actions);
186
187 posix_spawnattr_t spawnattr;
188 posix_spawnattr_init(&spawnattr);
189
190 short flags= 0;
191
192 // Child should not block signals
193 flags |= POSIX_SPAWN_SETSIGMASK;
194
195 sigset_t mask;
196 sigemptyset(&mask);
197
198 fatal_assert(posix_spawnattr_setsigmask(&spawnattr, &mask) == 0);
199
200 #if defined(POSIX_SPAWN_USEVFORK) || defined(__linux__)
201 // Use USEVFORK on linux
202 flags |= POSIX_SPAWN_USEVFORK;
203 #endif
204
205 flags |= POSIX_SPAWN_SETPGROUP;
206 fatal_assert(posix_spawnattr_setpgroup(&spawnattr, 0) == 0);
207
208 fatal_assert(posix_spawnattr_setflags(&spawnattr, flags) == 0);
209
210 create_argv(args);
211
212 int spawn_ret;
213 if (_use_gdb)
214 {
215 std::string gdb_run_file= create_tmpfile(_exectuble_name);
216 std::fstream file_stream;
217 file_stream.open(gdb_run_file.c_str(), std::fstream::out | std::fstream::trunc);
218
219 _gdb_filename= create_tmpfile(_exectuble_name);
220 file_stream
221 << "set logging redirect on" << std::endl
222 << "set logging file " << _gdb_filename << std::endl
223 << "set logging overwrite on" << std::endl
224 << "set logging on" << std::endl
225 << "set environment LIBTEST_IN_GDB=1" << std::endl
226 << "run " << arguments() << std::endl
227 << "thread apply all bt" << std::endl
228 << "quit" << std::endl;
229
230 fatal_assert(file_stream.good());
231 file_stream.close();
232
233 if (_use_libtool)
234 {
235 // libtool --mode=execute gdb -f -x binary
236 char *argv[]= {
237 const_cast<char *>(libtool()),
238 const_cast<char *>("--mode=execute"),
239 const_cast<char *>("gdb"),
240 const_cast<char *>("-batch"),
241 const_cast<char *>("-f"),
242 const_cast<char *>("-x"),
243 const_cast<char *>(gdb_run_file.c_str()),
244 const_cast<char *>(_exectuble_with_path.c_str()),
245 0};
246
247 spawn_ret= posix_spawnp(&_pid, libtool(), &file_actions, &spawnattr, argv, environ);
248 }
249 else
250 {
251 // gdb binary
252 char *argv[]= {
253 const_cast<char *>("gdb"),
254 const_cast<char *>("-batch"),
255 const_cast<char *>("-f"),
256 const_cast<char *>("-x"),
257 const_cast<char *>(gdb_run_file.c_str()),
258 const_cast<char *>(_exectuble_with_path.c_str()),
259 0};
260 spawn_ret= posix_spawnp(&_pid, "gdb", &file_actions, &spawnattr, argv, environ);
261 }
262 }
263 else
264 {
265 spawn_ret= posix_spawn(&_pid, built_argv[0], &file_actions, &spawnattr, &built_argv[0], NULL);
266 }
267
268 posix_spawn_file_actions_destroy(&file_actions);
269 posix_spawnattr_destroy(&spawnattr);
270
271 stdin_fd.close(Application::Pipe::READ);
272 stdout_fd.close(Application::Pipe::WRITE);
273 stderr_fd.close(Application::Pipe::WRITE);
274
275 if (spawn_ret != 0)
276 {
277 if (_will_fail == false)
278 {
279 Error << strerror(spawn_ret) << "(" << spawn_ret << ")";
280 }
281 _pid= -1;
282 return Application::INVALID_POSIX_SPAWN;
283 }
284
285 assert(_pid != -1);
286 if (_pid == -1)
287 {
288 return Application::INVALID_POSIX_SPAWN;
289 }
290
291 #if 0
292 app_thread_st* _app_thread= new app_thread_st(_pid, _status, built_argv[0], _app_exit_state);
293 int error;
294 if ((error= pthread_create(&_thread, NULL, &app_thread, _app_thread)) != 0)
295 {
296 Error << "pthread_create() died during pthread_create(" << strerror(error) << ")";
297 return Application::FAILURE;
298 }
299 #endif
300
301 return Application::SUCCESS;
302 }
303
304 bool Application::check() const
305 {
306 if (_pid > 1 and kill(_pid, 0) == 0)
307 {
308 return true;
309 }
310
311 return false;
312 }
313
314 void Application::murder()
315 {
316 if (check())
317 {
318 int count= 5;
319 while ((count--) > 0 and check())
320 {
321 if (kill(_pid, SIGTERM) == 0)
322 {
323 join();
324 }
325 else
326 {
327 Error << "kill(pid, SIGTERM) failed after kill with error of " << strerror(errno);
328 continue;
329 }
330
331 break;
332 }
333
334 // If for whatever reason it lives, kill it hard
335 if (check())
336 {
337 Error << "using SIGKILL, things will likely go poorly from this point";
338 (void)kill(_pid, SIGKILL);
339 }
340 }
341 slurp();
342 }
343
344 // false means that no data was returned
345 bool Application::slurp()
346 {
347 struct pollfd fds[2];
348 fds[0].fd= stdout_fd.fd();
349 fds[0].events= POLLRDNORM;
350 fds[0].revents= 0;
351 fds[1].fd= stderr_fd.fd();
352 fds[1].events= POLLRDNORM;
353 fds[1].revents= 0;
354
355 int active_fd;
356 if ((active_fd= poll(fds, 2, 0)) == -1)
357 {
358 int error;
359 switch ((error= errno))
360 {
361 #ifdef TARGET_OS_LINUX
362 case ERESTART:
363 #endif
364 case EINTR:
365 break;
366
367 case EFAULT:
368 case ENOMEM:
369 fatal_message(strerror(error));
370 break;
371
372 case EINVAL:
373 fatal_message("RLIMIT_NOFILE exceeded, or if OSX the timeout value was invalid");
374 break;
375
376 default:
377 fatal_message(strerror(error));
378 break;
379 }
380
381 return false;
382 }
383
384 if (active_fd == 0)
385 {
386 return false;
387 }
388
389 bool data_was_read= false;
390 if (fds[0].revents & POLLRDNORM)
391 {
392 if (stdout_fd.read(_stdout_buffer) == true)
393 {
394 data_was_read= true;
395 }
396 }
397
398 if (fds[1].revents & POLLRDNORM)
399 {
400 if (stderr_fd.read(_stderr_buffer) == true)
401 {
402 data_was_read= true;
403 }
404 }
405
406 return data_was_read;
407 }
408
409 Application::error_t Application::join()
410 {
411 pid_t waited_pid= waitpid(_pid, &_status, 0);
412 if (waited_pid == _pid and WIFEXITED(_status) == false)
413 {
414 /*
415 What we are looking for here is how the exit status happened.
416 - 127 means that posix_spawn() itself had an error.
417 - If WEXITSTATUS is positive we need to see if it is a signal that we sent to kill the process. If not something bad happened in the process itself.
418 - Finally something has happened that we don't currently understand.
419 */
420 if (WEXITSTATUS(_status) == 127)
421 {
422 _app_exit_state= Application::INVALID_POSIX_SPAWN;
423 std::string error_string("posix_spawn() failed pid:");
424 error_string+= _pid;
425 error_string+= " name:";
426 error_string+= built_argv[0];
427 throw std::logic_error(error_string);
428 }
429 else if (WIFSIGNALED(_status))
430 {
431 if (WTERMSIG(_status) != SIGTERM and WTERMSIG(_status) != SIGHUP)
432 {
433 _app_exit_state= Application::INVALID_POSIX_SPAWN;
434 std::string error_string(built_argv[0]);
435 error_string+= " was killed by signal ";
436 error_string+= strsignal(WTERMSIG(_status));
437 throw std::runtime_error(error_string);
438 }
439
440 // If we terminted it on purpose then it counts as a success.
441 #if defined(DEBUG)
442 if (DEBUG)
443 {
444 Out << "waitpid() application terminated at request"
445 << " pid:" << _pid
446 << " name:" << built_argv[0];
447 }
448 #endif
449 }
450 else
451 {
452 _app_exit_state= Application::UNKNOWN;
453 Error << "Unknown logic state at exit:" << WEXITSTATUS(_status)
454 << " pid:" << _pid
455 << " name:" << built_argv[0];
456 }
457 }
458 else if (waited_pid == _pid and WIFEXITED(_status))
459 {
460 _app_exit_state= int_to_error_t(WEXITSTATUS(_status));
461 }
462 else if (waited_pid == -1)
463 {
464 _app_exit_state= Application::UNKNOWN;
465 Error << "waitpid() returned errno:" << strerror(errno);
466 }
467 else
468 {
469 _app_exit_state= Application::UNKNOWN;
470 throw std::logic_error("waitpid() returned an unknown value");
471 }
472
473 return _app_exit_state;
474 }
475
476 void Application::add_long_option(const std::string& name, const std::string& option_value)
477 {
478 std::string arg(name);
479 arg+= option_value;
480 _options.push_back(std::make_pair(arg, std::string()));
481 }
482
483 void Application::add_option(const std::string& arg)
484 {
485 _options.push_back(std::make_pair(arg, std::string()));
486 }
487
488 void Application::add_option(const std::string& name, const std::string& value)
489 {
490 _options.push_back(std::make_pair(name, value));
491 }
492
493 Application::Pipe::Pipe(int arg) :
494 _std_fd(arg)
495 {
496 _pipe_fd[READ]= -1;
497 _pipe_fd[WRITE]= -1;
498 _open[READ]= false;
499 _open[WRITE]= false;
500 }
501
502 int Application::Pipe::Pipe::fd()
503 {
504 if (_std_fd == STDOUT_FILENO)
505 {
506 return _pipe_fd[READ];
507 }
508 else if (_std_fd == STDERR_FILENO)
509 {
510 return _pipe_fd[READ];
511 }
512
513 return _pipe_fd[WRITE]; // STDIN_FILENO
514 }
515
516
517 bool Application::Pipe::read(libtest::vchar_t& arg)
518 {
519 fatal_assert(_std_fd == STDOUT_FILENO or _std_fd == STDERR_FILENO);
520
521 bool data_was_read= false;
522
523 libtest::vchar_t buffer;
524 buffer.resize(1024);
525 ssize_t read_length;
526 while ((read_length= ::read(_pipe_fd[READ], &buffer[0], buffer.size())))
527 {
528 if (read_length == -1)
529 {
530 switch(errno)
531 {
532 case EAGAIN:
533 break;
534
535 default:
536 Error << strerror(errno);
537 break;
538 }
539
540 break;
541 }
542
543 data_was_read= true;
544 arg.reserve(read_length +1);
545 for (size_t x= 0; x < size_t(read_length); ++x)
546 {
547 arg.push_back(buffer[x]);
548 }
549 // @todo Suck up all errput code here
550 }
551
552 return data_was_read;
553 }
554
555 void Application::Pipe::nonblock()
556 {
557 int flags;
558 {
559 flags= fcntl(_pipe_fd[READ], F_GETFL, 0);
560 } while (flags == -1 and (errno == EINTR or errno == EAGAIN));
561
562 if (flags == -1)
563 {
564 Error << "fcntl(F_GETFL) " << strerror(errno);
565 throw strerror(errno);
566 }
567
568 int rval;
569 do
570 {
571 rval= fcntl(_pipe_fd[READ], F_SETFL, flags | O_NONBLOCK);
572 } while (rval == -1 and (errno == EINTR or errno == EAGAIN));
573
574 if (rval == -1)
575 {
576 Error << "fcntl(F_SETFL) " << strerror(errno);
577 throw strerror(errno);
578 }
579 }
580
581 void Application::Pipe::reset()
582 {
583 close(READ);
584 close(WRITE);
585
586 #if defined(HAVE_PIPE2) && HAVE_PIPE2
587 if (pipe2(_pipe_fd, O_NONBLOCK|O_CLOEXEC) == -1)
588 #else
589 if (pipe(_pipe_fd) == -1)
590 #endif
591 {
592 fatal_message(strerror(errno));
593 }
594 _open[0]= true;
595 _open[1]= true;
596
597 #if defined(HAVE_PIPE2) && HAVE_PIPE2
598 {
599 nonblock();
600 cloexec();
601 }
602 #endif
603 }
604
605 void Application::Pipe::cloexec()
606 {
607 //if (SOCK_CLOEXEC == 0)
608 {
609 if (FD_CLOEXEC)
610 {
611 int flags;
612 do
613 {
614 flags= fcntl(_pipe_fd[WRITE], F_GETFD, 0);
615 } while (flags == -1 and (errno == EINTR or errno == EAGAIN));
616
617 if (flags == -1)
618 {
619 Error << "fcntl(F_GETFD) " << strerror(errno);
620 throw strerror(errno);
621 }
622
623 int rval;
624 do
625 {
626 rval= fcntl(_pipe_fd[WRITE], F_SETFD, flags | FD_CLOEXEC);
627 } while (rval == -1 && (errno == EINTR or errno == EAGAIN));
628
629 if (rval == -1)
630 {
631 Error << "fcntl(F_SETFD) " << strerror(errno);
632 throw strerror(errno);
633 }
634 }
635 }
636 }
637
638 Application::Pipe::~Pipe()
639 {
640 if (_pipe_fd[0] != -1)
641 {
642 ::close(_pipe_fd[0]);
643 }
644
645 if (_pipe_fd[1] != -1)
646 {
647 ::close(_pipe_fd[1]);
648 }
649 }
650
651 void Application::Pipe::dup_for_spawn(posix_spawn_file_actions_t& file_actions)
652 {
653 int type= STDIN_FILENO == _std_fd ? 0 : 1;
654
655 int ret;
656 if ((ret= posix_spawn_file_actions_adddup2(&file_actions, _pipe_fd[type], _std_fd )) < 0)
657 {
658 Error << "posix_spawn_file_actions_adddup2(" << strerror(ret) << ")";
659 fatal_message(strerror(ret));
660 }
661
662 if ((ret= posix_spawn_file_actions_addclose(&file_actions, _pipe_fd[type])) < 0)
663 {
664 Error << "posix_spawn_file_actions_adddup2(" << strerror(ret) << ")";
665 fatal_message(strerror(ret));
666 }
667 }
668
669 void Application::Pipe::close(const close_t& arg)
670 {
671 int type= int(arg);
672
673 if (_open[type])
674 {
675 if (::close(_pipe_fd[type]) == -1)
676 {
677 Error << "close(" << strerror(errno) << ")";
678 }
679 _open[type]= false;
680 _pipe_fd[type]= -1;
681 }
682 }
683
684 void Application::create_argv(const char *args[])
685 {
686 delete_argv();
687 if (_use_libtool)
688 {
689 assert(libtool());
690 vchar::append(built_argv, libtool());
691 vchar::append(built_argv, "--mode=execute");
692 }
693
694 if (_use_valgrind)
695 {
696 /*
697 valgrind --error-exitcode=1 --leak-check=yes --track-fds=yes --malloc-fill=A5 --free-fill=DE
698 */
699 vchar::append(built_argv, "valgrind");
700 vchar::append(built_argv, "--error-exitcode=1");
701 vchar::append(built_argv, "--leak-check=yes");
702 #if 0
703 vchar::append(built_argv, "--show-reachable=yes"));
704 #endif
705 vchar::append(built_argv, "--track-fds=yes");
706 #if 0
707 built_argv[x++]= strdup("--track-origin=yes");
708 #endif
709 vchar::append(built_argv, "--malloc-fill=A5");
710 vchar::append(built_argv, "--free-fill=DE");
711
712 std::string log_file= create_tmpfile("valgrind");
713 libtest::vchar_t buffer;
714 buffer.resize(1024);
715 int length= snprintf(&buffer[0], buffer.size(), "--log-file=%s", log_file.c_str());
716 fatal_assert(length > 0 and size_t(length) < buffer.size());
717 vchar::append(built_argv, &buffer[0]);
718 }
719 else if (_use_ptrcheck)
720 {
721 /*
722 valgrind --error-exitcode=1 --tool=exp-ptrcheck --log-file=
723 */
724 vchar::append(built_argv, "valgrind");
725 vchar::append(built_argv, "--error-exitcode=1");
726 vchar::append(built_argv, "--tool=exp-ptrcheck");
727 std::string log_file= create_tmpfile("ptrcheck");
728 libtest::vchar_t buffer;
729 buffer.resize(1024);
730 int length= snprintf(&buffer[0], buffer.size(), "--log-file=%s", log_file.c_str());
731 fatal_assert(length > 0 and size_t(length) < buffer.size());
732 vchar::append(built_argv, &buffer[0]);
733 }
734 else if (_use_gdb)
735 {
736 vchar::append(built_argv, "gdb");
737 }
738
739 vchar::append(built_argv, _exectuble_with_path.c_str());
740
741 for (Options::const_iterator iter= _options.begin(); iter != _options.end(); ++iter)
742 {
743 vchar::append(built_argv, (*iter).first.c_str());
744 if ((*iter).second.empty() == false)
745 {
746 vchar::append(built_argv, (*iter).second.c_str());
747 }
748 }
749
750 if (args)
751 {
752 for (const char **ptr= args; *ptr; ++ptr)
753 {
754 vchar::append(built_argv, *ptr);
755 }
756 }
757 built_argv.push_back(NULL);
758 }
759
760 std::string Application::print()
761 {
762 return print_argv(built_argv);
763 }
764
765 std::string Application::arguments()
766 {
767 std::stringstream arg_buffer;
768
769 // Skip printing out the libtool reference
770 for (size_t x= _use_libtool ? 2 : 0; x < _argc; ++x)
771 {
772 if (built_argv[x])
773 {
774 arg_buffer << built_argv[x] << " ";
775 }
776 }
777
778 return arg_buffer.str();
779 }
780
781 void Application::delete_argv()
782 {
783 std::for_each(built_argv.begin(), built_argv.end(), FreeFromVector());
784
785 built_argv.clear();
786 _argc= 0;
787 }
788
789
790 int exec_cmdline(const std::string& command, const char *args[], bool use_libtool)
791 {
792 Application app(command, use_libtool);
793
794 Application::error_t ret= app.run(args);
795
796 if (ret != Application::SUCCESS)
797 {
798 return int(ret);
799 }
800
801 return int(app.join());
802 }
803
804 const char *gearmand_binary()
805 {
806 return GEARMAND_BINARY;
807 }
808
809 const char *drizzled_binary()
810 {
811 return DRIZZLED_BINARY;
812 }
813
814 } // namespace exec_cmdline