Merge lp:~tangent-org/libmemcached/1.0-build/ Build: jenkins-Libmemcached-200
[awesomized/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 return;
599 #endif
600 {
601 nonblock();
602 cloexec();
603 }
604 }
605
606 void Application::Pipe::cloexec()
607 {
608 //if (SOCK_CLOEXEC == 0)
609 {
610 if (FD_CLOEXEC)
611 {
612 int flags;
613 do
614 {
615 flags= fcntl(_pipe_fd[WRITE], F_GETFD, 0);
616 } while (flags == -1 and (errno == EINTR or errno == EAGAIN));
617
618 if (flags == -1)
619 {
620 Error << "fcntl(F_GETFD) " << strerror(errno);
621 throw strerror(errno);
622 }
623
624 int rval;
625 do
626 {
627 rval= fcntl(_pipe_fd[WRITE], F_SETFD, flags | FD_CLOEXEC);
628 } while (rval == -1 && (errno == EINTR or errno == EAGAIN));
629
630 if (rval == -1)
631 {
632 Error << "fcntl(F_SETFD) " << strerror(errno);
633 throw strerror(errno);
634 }
635 }
636 }
637 }
638
639 Application::Pipe::~Pipe()
640 {
641 if (_pipe_fd[0] != -1)
642 {
643 ::close(_pipe_fd[0]);
644 }
645
646 if (_pipe_fd[1] != -1)
647 {
648 ::close(_pipe_fd[1]);
649 }
650 }
651
652 void Application::Pipe::dup_for_spawn(posix_spawn_file_actions_t& file_actions)
653 {
654 int type= STDIN_FILENO == _std_fd ? 0 : 1;
655
656 int ret;
657 if ((ret= posix_spawn_file_actions_adddup2(&file_actions, _pipe_fd[type], _std_fd )) < 0)
658 {
659 Error << "posix_spawn_file_actions_adddup2(" << strerror(ret) << ")";
660 fatal_message(strerror(ret));
661 }
662
663 if ((ret= posix_spawn_file_actions_addclose(&file_actions, _pipe_fd[type])) < 0)
664 {
665 Error << "posix_spawn_file_actions_adddup2(" << strerror(ret) << ")";
666 fatal_message(strerror(ret));
667 }
668 }
669
670 void Application::Pipe::close(const close_t& arg)
671 {
672 int type= int(arg);
673
674 if (_open[type])
675 {
676 if (::close(_pipe_fd[type]) == -1)
677 {
678 Error << "close(" << strerror(errno) << ")";
679 }
680 _open[type]= false;
681 _pipe_fd[type]= -1;
682 }
683 }
684
685 void Application::create_argv(const char *args[])
686 {
687 delete_argv();
688 if (_use_libtool)
689 {
690 assert(libtool());
691 vchar::append(built_argv, libtool());
692 vchar::append(built_argv, "--mode=execute");
693 }
694
695 if (_use_valgrind)
696 {
697 /*
698 valgrind --error-exitcode=1 --leak-check=yes --track-fds=yes --malloc-fill=A5 --free-fill=DE
699 */
700 vchar::append(built_argv, "valgrind");
701 vchar::append(built_argv, "--error-exitcode=1");
702 vchar::append(built_argv, "--leak-check=yes");
703 #if 0
704 vchar::append(built_argv, "--show-reachable=yes"));
705 #endif
706 vchar::append(built_argv, "--track-fds=yes");
707 #if 0
708 built_argv[x++]= strdup("--track-origin=yes");
709 #endif
710 vchar::append(built_argv, "--malloc-fill=A5");
711 vchar::append(built_argv, "--free-fill=DE");
712
713 std::string log_file= create_tmpfile("valgrind");
714 libtest::vchar_t buffer;
715 buffer.resize(1024);
716 int length= snprintf(&buffer[0], buffer.size(), "--log-file=%s", log_file.c_str());
717 fatal_assert(length > 0 and size_t(length) < buffer.size());
718 vchar::append(built_argv, &buffer[0]);
719 }
720 else if (_use_ptrcheck)
721 {
722 /*
723 valgrind --error-exitcode=1 --tool=exp-ptrcheck --log-file=
724 */
725 vchar::append(built_argv, "valgrind");
726 vchar::append(built_argv, "--error-exitcode=1");
727 vchar::append(built_argv, "--tool=exp-ptrcheck");
728 std::string log_file= create_tmpfile("ptrcheck");
729 libtest::vchar_t buffer;
730 buffer.resize(1024);
731 int length= snprintf(&buffer[0], buffer.size(), "--log-file=%s", log_file.c_str());
732 fatal_assert(length > 0 and size_t(length) < buffer.size());
733 vchar::append(built_argv, &buffer[0]);
734 }
735 else if (_use_gdb)
736 {
737 vchar::append(built_argv, "gdb");
738 }
739
740 vchar::append(built_argv, _exectuble_with_path.c_str());
741
742 for (Options::const_iterator iter= _options.begin(); iter != _options.end(); ++iter)
743 {
744 vchar::append(built_argv, (*iter).first.c_str());
745 if ((*iter).second.empty() == false)
746 {
747 vchar::append(built_argv, (*iter).second.c_str());
748 }
749 }
750
751 if (args)
752 {
753 for (const char **ptr= args; *ptr; ++ptr)
754 {
755 vchar::append(built_argv, *ptr);
756 }
757 }
758 built_argv.push_back(NULL);
759 }
760
761 std::string Application::print()
762 {
763 return print_argv(built_argv);
764 }
765
766 std::string Application::arguments()
767 {
768 std::stringstream arg_buffer;
769
770 // Skip printing out the libtool reference
771 for (size_t x= _use_libtool ? 2 : 0; x < _argc; ++x)
772 {
773 if (built_argv[x])
774 {
775 arg_buffer << built_argv[x] << " ";
776 }
777 }
778
779 return arg_buffer.str();
780 }
781
782 void Application::delete_argv()
783 {
784 std::for_each(built_argv.begin(), built_argv.end(), FreeFromVector());
785
786 built_argv.clear();
787 _argc= 0;
788 }
789
790
791 int exec_cmdline(const std::string& command, const char *args[], bool use_libtool)
792 {
793 Application app(command, use_libtool);
794
795 Application::error_t ret= app.run(args);
796
797 if (ret != Application::SUCCESS)
798 {
799 return int(ret);
800 }
801
802 return int(app.join());
803 }
804
805 const char *gearmand_binary()
806 {
807 return GEARMAND_BINARY;
808 }
809
810 const char *drizzled_binary()
811 {
812 return DRIZZLED_BINARY;
813 }
814
815 } // namespace exec_cmdline