Merge in updated yatl.
[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
413 if (waited_pid == _pid and WIFEXITED(_status) == false)
414 {
415 /*
416 What we are looking for here is how the exit status happened.
417 - 127 means that posix_spawn() itself had an error.
418 - 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.
419 - Finally something has happened that we don't currently understand.
420 */
421 if (WEXITSTATUS(_status) == 127)
422 {
423 _app_exit_state= Application::INVALID_POSIX_SPAWN;
424 std::string error_string("posix_spawn() failed pid:");
425 error_string+= _pid;
426 error_string+= " name:";
427 error_string+= built_argv[0];
428 throw std::logic_error(error_string);
429 }
430 else if (WIFSIGNALED(_status))
431 {
432 if (WTERMSIG(_status) != SIGTERM and WTERMSIG(_status) != SIGHUP)
433 {
434 _app_exit_state= Application::INVALID_POSIX_SPAWN;
435 std::string error_string(built_argv[0]);
436 error_string+= " was killed by signal ";
437 error_string+= strsignal(WTERMSIG(_status));
438 throw std::runtime_error(error_string);
439 }
440
441 // If we terminted it on purpose then it counts as a success.
442 Out << "waitpid() application terminated at request"
443 << " pid:" << _pid
444 << " name:" << built_argv[0];
445 }
446 else
447 {
448 _app_exit_state= Application::UNKNOWN;
449 Error << "Unknown logic state at exit:" << WEXITSTATUS(_status)
450 << " pid:" << _pid
451 << " name:" << built_argv[0];
452 }
453 }
454 else if (waited_pid == _pid and WIFEXITED(_status))
455 {
456 _app_exit_state= int_to_error_t(WEXITSTATUS(_status));
457 }
458 else if (waited_pid == -1)
459 {
460 _app_exit_state= Application::UNKNOWN;
461 Error << "waitpid() returned errno:" << strerror(errno);
462 }
463 else
464 {
465 _app_exit_state= Application::UNKNOWN;
466 throw std::logic_error("waitpid() returned an unknown value");
467 }
468
469 return _app_exit_state;
470 }
471
472 void Application::add_long_option(const std::string& name, const std::string& option_value)
473 {
474 std::string arg(name);
475 arg+= option_value;
476 _options.push_back(std::make_pair(arg, std::string()));
477 }
478
479 void Application::add_option(const std::string& arg)
480 {
481 _options.push_back(std::make_pair(arg, std::string()));
482 }
483
484 void Application::add_option(const std::string& name, const std::string& value)
485 {
486 _options.push_back(std::make_pair(name, value));
487 }
488
489 Application::Pipe::Pipe(int arg) :
490 _std_fd(arg)
491 {
492 _pipe_fd[READ]= -1;
493 _pipe_fd[WRITE]= -1;
494 _open[READ]= false;
495 _open[WRITE]= false;
496 }
497
498 int Application::Pipe::Pipe::fd()
499 {
500 if (_std_fd == STDOUT_FILENO)
501 {
502 return _pipe_fd[READ];
503 }
504 else if (_std_fd == STDERR_FILENO)
505 {
506 return _pipe_fd[READ];
507 }
508
509 return _pipe_fd[WRITE]; // STDIN_FILENO
510 }
511
512
513 bool Application::Pipe::read(libtest::vchar_t& arg)
514 {
515 fatal_assert(_std_fd == STDOUT_FILENO or _std_fd == STDERR_FILENO);
516
517 bool data_was_read= false;
518
519 libtest::vchar_t buffer;
520 buffer.resize(1024);
521 ssize_t read_length;
522 while ((read_length= ::read(_pipe_fd[READ], &buffer[0], buffer.size())))
523 {
524 if (read_length == -1)
525 {
526 switch(errno)
527 {
528 case EAGAIN:
529 break;
530
531 default:
532 Error << strerror(errno);
533 break;
534 }
535
536 break;
537 }
538
539 data_was_read= true;
540 arg.reserve(read_length +1);
541 for (size_t x= 0; x < size_t(read_length); ++x)
542 {
543 arg.push_back(buffer[x]);
544 }
545 // @todo Suck up all errput code here
546 }
547
548 return data_was_read;
549 }
550
551 void Application::Pipe::nonblock()
552 {
553 int flags;
554 {
555 flags= fcntl(_pipe_fd[READ], F_GETFL, 0);
556 } while (flags == -1 and (errno == EINTR or errno == EAGAIN));
557
558 if (flags == -1)
559 {
560 Error << "fcntl(F_GETFL) " << strerror(errno);
561 throw strerror(errno);
562 }
563
564 int rval;
565 do
566 {
567 rval= fcntl(_pipe_fd[READ], F_SETFL, flags | O_NONBLOCK);
568 } while (rval == -1 and (errno == EINTR or errno == EAGAIN));
569
570 if (rval == -1)
571 {
572 Error << "fcntl(F_SETFL) " << strerror(errno);
573 throw strerror(errno);
574 }
575 }
576
577 void Application::Pipe::reset()
578 {
579 close(READ);
580 close(WRITE);
581
582 #if defined(HAVE_PIPE2) && HAVE_PIPE2
583 if (pipe2(_pipe_fd, O_NONBLOCK|O_CLOEXEC) == -1)
584 #else
585 if (pipe(_pipe_fd) == -1)
586 #endif
587 {
588 fatal_message(strerror(errno));
589 }
590 _open[0]= true;
591 _open[1]= true;
592
593 #if defined(HAVE_PIPE2) && HAVE_PIPE2
594 {
595 nonblock();
596 cloexec();
597 }
598 #endif
599 }
600
601 void Application::Pipe::cloexec()
602 {
603 //if (SOCK_CLOEXEC == 0)
604 {
605 if (FD_CLOEXEC)
606 {
607 int flags;
608 do
609 {
610 flags= fcntl(_pipe_fd[WRITE], F_GETFD, 0);
611 } while (flags == -1 and (errno == EINTR or errno == EAGAIN));
612
613 if (flags == -1)
614 {
615 Error << "fcntl(F_GETFD) " << strerror(errno);
616 throw strerror(errno);
617 }
618
619 int rval;
620 do
621 {
622 rval= fcntl(_pipe_fd[WRITE], F_SETFD, flags | FD_CLOEXEC);
623 } while (rval == -1 && (errno == EINTR or errno == EAGAIN));
624
625 if (rval == -1)
626 {
627 Error << "fcntl(F_SETFD) " << strerror(errno);
628 throw strerror(errno);
629 }
630 }
631 }
632 }
633
634 Application::Pipe::~Pipe()
635 {
636 if (_pipe_fd[0] != -1)
637 {
638 ::close(_pipe_fd[0]);
639 }
640
641 if (_pipe_fd[1] != -1)
642 {
643 ::close(_pipe_fd[1]);
644 }
645 }
646
647 void Application::Pipe::dup_for_spawn(posix_spawn_file_actions_t& file_actions)
648 {
649 int type= STDIN_FILENO == _std_fd ? 0 : 1;
650
651 int ret;
652 if ((ret= posix_spawn_file_actions_adddup2(&file_actions, _pipe_fd[type], _std_fd )) < 0)
653 {
654 Error << "posix_spawn_file_actions_adddup2(" << strerror(ret) << ")";
655 fatal_message(strerror(ret));
656 }
657
658 if ((ret= posix_spawn_file_actions_addclose(&file_actions, _pipe_fd[type])) < 0)
659 {
660 Error << "posix_spawn_file_actions_adddup2(" << strerror(ret) << ")";
661 fatal_message(strerror(ret));
662 }
663 }
664
665 void Application::Pipe::close(const close_t& arg)
666 {
667 int type= int(arg);
668
669 if (_open[type])
670 {
671 if (::close(_pipe_fd[type]) == -1)
672 {
673 Error << "close(" << strerror(errno) << ")";
674 }
675 _open[type]= false;
676 _pipe_fd[type]= -1;
677 }
678 }
679
680 void Application::create_argv(const char *args[])
681 {
682 delete_argv();
683 if (_use_libtool)
684 {
685 assert(libtool());
686 built_argv.push_back(strdup(libtool()));
687 built_argv.push_back(strdup("--mode=execute"));
688 }
689
690 if (_use_valgrind)
691 {
692 /*
693 valgrind --error-exitcode=1 --leak-check=yes --track-fds=yes --malloc-fill=A5 --free-fill=DE
694 */
695 built_argv.push_back(strdup("valgrind"));
696 built_argv.push_back(strdup("--error-exitcode=1"));
697 built_argv.push_back(strdup("--leak-check=yes"));
698 #if 0
699 built_argv.push_back(strdup("--show-reachable=yes"));
700 #endif
701 built_argv.push_back(strdup("--track-fds=yes"));
702 #if 0
703 built_argv[x++]= strdup("--track-origin=yes");
704 #endif
705 built_argv.push_back(strdup("--malloc-fill=A5"));
706 built_argv.push_back(strdup("--free-fill=DE"));
707
708 std::string log_file= create_tmpfile("valgrind");
709 libtest::vchar_t buffer;
710 buffer.resize(1024);
711 int length= snprintf(&buffer[0], buffer.size(), "--log-file=%s", log_file.c_str());
712 fatal_assert(length > 0 and size_t(length) < buffer.size());
713 built_argv.push_back(strdup(&buffer[0]));
714 }
715 else if (_use_ptrcheck)
716 {
717 /*
718 valgrind --error-exitcode=1 --tool=exp-ptrcheck --log-file=
719 */
720 built_argv.push_back(strdup("valgrind"));
721 built_argv.push_back(strdup("--error-exitcode=1"));
722 built_argv.push_back(strdup("--tool=exp-ptrcheck"));
723 std::string log_file= create_tmpfile("ptrcheck");
724 libtest::vchar_t buffer;
725 buffer.resize(1024);
726 int length= snprintf(&buffer[0], buffer.size(), "--log-file=%s", log_file.c_str());
727 fatal_assert(length > 0 and size_t(length) < buffer.size());
728 built_argv.push_back(&buffer[0]);
729 }
730 else if (_use_gdb)
731 {
732 built_argv.push_back(strdup("gdb"));
733 }
734
735 built_argv.push_back(strdup(_exectuble_with_path.c_str()));
736
737 for (Options::const_iterator iter= _options.begin(); iter != _options.end(); ++iter)
738 {
739 built_argv.push_back(strdup((*iter).first.c_str()));
740 if ((*iter).second.empty() == false)
741 {
742 built_argv.push_back(strdup((*iter).second.c_str()));
743 }
744 }
745
746 if (args)
747 {
748 for (const char **ptr= args; *ptr; ++ptr)
749 {
750 built_argv.push_back(strdup(*ptr));
751 }
752 }
753 built_argv.push_back(NULL);
754 }
755
756 std::string Application::print()
757 {
758 return print_argv(built_argv);
759 }
760
761 std::string Application::arguments()
762 {
763 std::stringstream arg_buffer;
764
765 for (size_t x= (1 +_use_libtool) ? 2 : 0;
766 x < _argc and built_argv[x];
767 ++x)
768 {
769 arg_buffer << built_argv[x] << " ";
770 }
771
772 return arg_buffer.str();
773 }
774
775 struct DeleteFromVector
776 {
777 template <class T>
778 void operator() ( T* ptr) const
779 {
780 free(ptr);
781 }
782 };
783
784 void Application::delete_argv()
785 {
786 std::for_each(built_argv.begin(), built_argv.end(), DeleteFromVector());
787
788 built_argv.clear();
789 _argc= 0;
790 }
791
792
793 int exec_cmdline(const std::string& command, const char *args[], bool use_libtool)
794 {
795 Application app(command, use_libtool);
796
797 Application::error_t ret= app.run(args);
798
799 if (ret != Application::SUCCESS)
800 {
801 return int(ret);
802 }
803
804 return int(app.join());
805 }
806
807 const char *gearmand_binary()
808 {
809 return GEARMAND_BINARY;
810 }
811
812 const char *drizzled_binary()
813 {
814 return DRIZZLED_BINARY;
815 }
816
817 } // namespace exec_cmdline