cad294671f22fca0310cf0f1dd507480fde9098c
[awesomized/libmemcached] / libtest / cmdline.cc
1 /* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
2 *
3 * libtest
4 *
5 * Copyright (C) 2011 Data Differential, http://datadifferential.com/
6 *
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 3 of the License, or (at your option) any later version.
11 *
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
22 #include <config.h>
23 #include <libtest/common.h>
24
25 using namespace libtest;
26
27 #include <cstdlib>
28 #include <cstring>
29 #include <cerrno>
30 #include <fcntl.h>
31 #include <fstream>
32 #include <memory>
33 #include <poll.h>
34 #include <spawn.h>
35 #include <sstream>
36 #include <string>
37 #include <sys/stat.h>
38 #include <sys/types.h>
39
40 extern "C" {
41 static int exited_successfully(int status)
42 {
43 if (status == 0)
44 {
45 return EXIT_SUCCESS;
46 }
47
48 if (WIFEXITED(status) == true)
49 {
50 return WEXITSTATUS(status);
51 }
52 else if (WIFSIGNALED(status) == true)
53 {
54 return WTERMSIG(status);
55 }
56
57 return EXIT_FAILURE;
58 }
59 }
60
61 namespace {
62
63 std::string print_argv(char * * & built_argv, const size_t& argc)
64 {
65 std::stringstream arg_buffer;
66
67 for (size_t x= 0; x < argc; x++)
68 {
69 arg_buffer << built_argv[x] << " ";
70 }
71
72 return arg_buffer.str();
73 }
74
75 std::string print_argv(char** argv)
76 {
77 std::stringstream arg_buffer;
78
79 for (char** ptr= argv; *ptr; ptr++)
80 {
81 arg_buffer << *ptr << " ";
82 }
83
84 return arg_buffer.str();
85 }
86
87 static Application::error_t int_to_error_t(int arg)
88 {
89 switch (arg)
90 {
91 case 127:
92 return Application::INVALID;
93
94 case 0:
95 return Application::SUCCESS;
96
97 default:
98 case 1:
99 return Application::FAILURE;
100 }
101 }
102 }
103
104 namespace libtest {
105
106 Application::Application(const std::string& arg, const bool _use_libtool_arg) :
107 _use_libtool(_use_libtool_arg),
108 _use_valgrind(false),
109 _use_gdb(false),
110 _argc(0),
111 _exectuble(arg),
112 built_argv(NULL),
113 _pid(-1)
114 {
115 if (_use_libtool)
116 {
117 if (libtool() == NULL)
118 {
119 throw fatal_message("libtool requested, but know libtool was found");
120 }
121 }
122
123 // Find just the name of the application with no path
124 {
125 size_t found= arg.find_last_of("/\\");
126 if (found)
127 {
128 _exectuble_name= arg.substr(found +1);
129 }
130 else
131 {
132 _exectuble_name= arg;
133 }
134 }
135
136 if (_use_libtool and getenv("PWD"))
137 {
138 _exectuble_with_path+= getenv("PWD");
139 _exectuble_with_path+= "/";
140 }
141 _exectuble_with_path+= _exectuble;
142 }
143
144 Application::~Application()
145 {
146 murder();
147 delete_argv();
148 }
149
150 Application::error_t Application::run(const char *args[])
151 {
152 stdin_fd.reset();
153 stdout_fd.reset();
154 stderr_fd.reset();
155 _stdout_buffer.clear();
156 _stderr_buffer.clear();
157
158 posix_spawn_file_actions_t file_actions;
159 posix_spawn_file_actions_init(&file_actions);
160
161 stdin_fd.dup_for_spawn(Application::Pipe::READ, file_actions, STDIN_FILENO);
162 stdout_fd.dup_for_spawn(Application::Pipe::WRITE, file_actions, STDOUT_FILENO);
163 stderr_fd.dup_for_spawn(Application::Pipe::WRITE, file_actions, STDERR_FILENO);
164
165 create_argv(args);
166
167 int spawn_ret;
168 if (_use_gdb)
169 {
170 std::string gdb_run_file= create_tmpfile(_exectuble_name);
171 std::fstream file_stream;
172 file_stream.open(gdb_run_file.c_str(), std::fstream::out | std::fstream::trunc);
173
174 _gdb_filename= create_tmpfile(_exectuble_name);
175 file_stream
176 << "set logging redirect on" << std::endl
177 << "set logging file " << _gdb_filename << std::endl
178 << "set logging overwrite on" << std::endl
179 << "set logging on" << std::endl
180 << "set environment LIBTEST_IN_GDB=1" << std::endl
181 << "run " << arguments() << std::endl
182 << "thread apply all bt" << std::endl
183 << "quit" << std::endl;
184
185 fatal_assert(file_stream.good());
186 file_stream.close();
187
188 if (_use_libtool)
189 {
190 // libtool --mode=execute gdb -f -x binary
191 char *argv[]= {
192 const_cast<char *>(libtool()),
193 const_cast<char *>("--mode=execute"),
194 const_cast<char *>("gdb"),
195 const_cast<char *>("-batch"),
196 const_cast<char *>("-f"),
197 const_cast<char *>("-x"),
198 const_cast<char *>(gdb_run_file.c_str()),
199 const_cast<char *>(_exectuble_with_path.c_str()),
200 0};
201
202 spawn_ret= posix_spawnp(&_pid, libtool(), &file_actions, NULL, argv, NULL);
203 }
204 else
205 {
206 // gdb binary
207 char *argv[]= {
208 const_cast<char *>("gdb"),
209 const_cast<char *>("-batch"),
210 const_cast<char *>("-f"),
211 const_cast<char *>("-x"),
212 const_cast<char *>(gdb_run_file.c_str()),
213 const_cast<char *>(_exectuble_with_path.c_str()),
214 0};
215 spawn_ret= posix_spawnp(&_pid, "gdb", &file_actions, NULL, argv, NULL);
216 }
217 }
218 else
219 {
220 if (_use_libtool)
221 {
222 spawn_ret= posix_spawn(&_pid, built_argv[0], &file_actions, NULL, built_argv, NULL);
223 }
224 else
225 {
226 spawn_ret= posix_spawnp(&_pid, built_argv[0], &file_actions, NULL, built_argv, NULL);
227 }
228 }
229
230 posix_spawn_file_actions_destroy(&file_actions);
231
232 stdin_fd.close(Application::Pipe::READ);
233 stdout_fd.close(Application::Pipe::WRITE);
234 stderr_fd.close(Application::Pipe::WRITE);
235
236 if (spawn_ret)
237 {
238 _pid= -1;
239 return Application::INVALID;
240 }
241
242 return Application::SUCCESS;
243 }
244
245 bool Application::check() const
246 {
247 Error << "Testing " << _exectuble;
248 if (kill(_pid, 0) == 0)
249 {
250 return true;
251 }
252
253 return false;
254 }
255
256 void Application::murder()
257 {
258 slurp();
259 kill(_pid, SIGTERM);
260 }
261
262 // false means that no data was returned
263 bool Application::slurp()
264 {
265 struct pollfd fds[2];
266 fds[0].fd= stdout_fd.fd()[0];
267 fds[0].events= POLLIN;
268 fds[0].revents= 0;
269 fds[1].fd= stderr_fd.fd()[0];
270 fds[1].events= POLLIN;
271 fds[1].revents= 0;
272
273 int active_fd;
274 if ((active_fd= poll(fds, 2, 400)) == -1)
275 {
276 int error;
277 switch ((error= errno))
278 {
279 #ifdef TARGET_OS_LINUX
280 case ERESTART:
281 #endif
282 case EINTR:
283 break;
284
285 case EFAULT:
286 case ENOMEM:
287 fatal_message(strerror(error));
288 break;
289
290 case EINVAL:
291 fatal_message("RLIMIT_NOFILE exceeded, or if OSX the timeout value was invalid");
292 break;
293
294 default:
295 fatal_message(strerror(error));
296 break;
297 }
298 }
299
300 if (active_fd == 0)
301 {
302 return false;
303 }
304
305 bool data_was_read= false;
306 if (fds[0].revents & POLLIN)
307 {
308 ssize_t read_length;
309 char buffer[1024]= { 0 };
310 while ((read_length= ::read(stdout_fd.fd()[0], buffer, sizeof(buffer))))
311 {
312 if (read_length == -1)
313 {
314 switch(errno)
315 {
316 case EAGAIN:
317 continue;
318
319 default:
320 Error << strerror(errno);
321 break;
322 }
323
324 break;
325 }
326
327 data_was_read= true;
328 _stdout_buffer.reserve(read_length +1);
329 for (size_t x= 0; x < read_length; x++)
330 {
331 _stdout_buffer.push_back(buffer[x]);
332 }
333 // @todo Suck up all output code here
334 }
335 }
336
337 if (fds[1].revents & POLLIN)
338 {
339 stderr_fd.nonblock();
340
341 ssize_t read_length;
342 char buffer[1024]= { 0 };
343 while ((read_length= ::read(stderr_fd.fd()[0], buffer, sizeof(buffer))))
344 {
345 if (read_length == -1)
346 {
347 switch(errno)
348 {
349 case EAGAIN:
350 continue;
351
352 default:
353 Error << strerror(errno);
354 break;
355 }
356
357 break;
358 }
359
360 data_was_read= true;
361 _stderr_buffer.reserve(read_length +1);
362 for (size_t x= 0; x < read_length; x++)
363 {
364 _stderr_buffer.push_back(buffer[x]);
365 }
366 // @todo Suck up all errput code here
367 }
368 }
369
370 return data_was_read;
371 }
372
373 Application::error_t Application::wait(bool nohang)
374 {
375 if (_pid == -1)
376 {
377 return Application::INVALID;
378 }
379
380 slurp();
381
382 error_t exit_code= FAILURE;
383 {
384 int status= 0;
385 pid_t waited_pid;
386 if ((waited_pid= waitpid(_pid, &status, nohang ? WNOHANG : 0)) == -1)
387 {
388 switch (errno)
389 {
390 case ECHILD:
391 exit_code= Application::SUCCESS;
392 break;
393
394 default:
395 Error << "Error occured while waitpid(" << strerror(errno) << ") on pid " << int(_pid);
396 }
397 }
398 else if (waited_pid == 0)
399 {
400 exit_code= Application::SUCCESS;
401 }
402 else
403 {
404 if (waited_pid != _pid)
405 {
406 throw libtest::fatal(LIBYATL_DEFAULT_PARAM, "Pid mismatch, %d != %d", int(waited_pid), int(_pid));
407 }
408 exit_code= int_to_error_t(exited_successfully(status));
409 }
410 }
411
412 #if 0
413 if (exit_code == Application::INVALID)
414 {
415 Error << print_argv(built_argv, _argc);
416 }
417 #endif
418
419 return exit_code;
420 }
421
422 void Application::add_long_option(const std::string& name, const std::string& option_value)
423 {
424 std::string arg(name);
425 arg+= option_value;
426 _options.push_back(std::make_pair(arg, std::string()));
427 }
428
429 void Application::add_option(const std::string& arg)
430 {
431 _options.push_back(std::make_pair(arg, std::string()));
432 }
433
434 void Application::add_option(const std::string& name, const std::string& value)
435 {
436 _options.push_back(std::make_pair(name, value));
437 }
438
439 Application::Pipe::Pipe()
440 {
441 _fd[0]= -1;
442 _fd[1]= -1;
443 _open[0]= false;
444 _open[1]= false;
445 }
446
447 void Application::Pipe::nonblock()
448 {
449 int ret;
450 if ((ret= fcntl(_fd[0], F_GETFL, 0)) == -1)
451 {
452 Error << "fcntl(F_GETFL) " << strerror(errno);
453 throw strerror(errno);
454 }
455
456 if ((ret= fcntl(_fd[0], F_SETFL, ret | O_NONBLOCK)) == -1)
457 {
458 Error << "fcntl(F_SETFL) " << strerror(errno);
459 throw strerror(errno);
460 }
461 }
462
463 void Application::Pipe::reset()
464 {
465 close(READ);
466 close(WRITE);
467
468 if (pipe(_fd) == -1)
469 {
470 throw fatal_message(strerror(errno));
471 }
472 _open[0]= true;
473 _open[1]= true;
474
475 if (0)
476 {
477 nonblock();
478 }
479 }
480
481 Application::Pipe::~Pipe()
482 {
483 close(READ);
484 close(WRITE);
485 }
486
487 void Application::Pipe::dup_for_spawn(const close_t& arg, posix_spawn_file_actions_t& file_actions, const int newfildes)
488 {
489 int type= int(arg);
490
491 int ret;
492 if ((ret= posix_spawn_file_actions_adddup2(&file_actions, _fd[type], newfildes )) < 0)
493 {
494 Error << "posix_spawn_file_actions_adddup2(" << strerror(ret) << ")";
495 throw fatal_message(strerror(ret));
496 }
497
498 if ((ret= posix_spawn_file_actions_addclose(&file_actions, _fd[type])) < 0)
499 {
500 Error << "posix_spawn_file_actions_adddup2(" << strerror(ret) << ")";
501 throw fatal_message(strerror(ret));
502 }
503 }
504
505 void Application::Pipe::close(const close_t& arg)
506 {
507 int type= int(arg);
508
509 if (_open[type])
510 {
511 int ret;
512 if (::close(_fd[type]) == -1)
513 {
514 Error << "close(" << strerror(errno) << ")";
515 }
516 _open[type]= false;
517 _fd[type]= -1;
518 }
519 }
520
521 void Application::create_argv(const char *args[])
522 {
523 _argc= 2 +_use_libtool ? 2 : 0; // +1 for the command, +2 for libtool/mode=execute, +1 for the NULL
524
525 if (_use_libtool)
526 {
527 _argc+= 2; // +2 for libtool --mode=execute
528 }
529
530 /*
531 valgrind --error-exitcode=1 --leak-check=yes --show-reachable=yes --track-fds=yes --malloc-fill=A5 --free-fill=DE
532 */
533 if (_use_valgrind)
534 {
535 _argc+= 7;
536 }
537 else if (_use_gdb) // gdb
538 {
539 _argc+= 1;
540 }
541
542 for (Options::const_iterator iter= _options.begin(); iter != _options.end(); iter++)
543 {
544 _argc++;
545 if ((*iter).second.empty() == false)
546 {
547 _argc++;
548 }
549 }
550
551 if (args)
552 {
553 for (const char **ptr= args; *ptr; ++ptr)
554 {
555 _argc++;
556 }
557 }
558
559 delete_argv();
560 built_argv= new char * [_argc];
561
562 size_t x= 0;
563 if (_use_libtool)
564 {
565 assert(libtool());
566 built_argv[x++]= strdup(libtool());
567 built_argv[x++]= strdup("--mode=execute");
568 }
569
570 if (_use_valgrind)
571 {
572 /*
573 valgrind --error-exitcode=1 --leak-check=yes --show-reachable=yes --track-fds=yes --malloc-fill=A5 --free-fill=DE
574 */
575 built_argv[x++]= strdup("valgrind");
576 built_argv[x++]= strdup("--error-exitcode=1");
577 built_argv[x++]= strdup("--leak-check=yes");
578 built_argv[x++]= strdup("--show-reachable=yes");
579 built_argv[x++]= strdup("--track-fds=yes");
580 built_argv[x++]= strdup("--malloc-fill=A5");
581 built_argv[x++]= strdup("--free-fill=DE");
582 }
583 else if (_use_gdb)
584 {
585 built_argv[x++]= strdup("gdb");
586 }
587
588 built_argv[x++]= strdup(_exectuble_with_path.c_str());
589
590 for (Options::const_iterator iter= _options.begin(); iter != _options.end(); iter++)
591 {
592 built_argv[x++]= strdup((*iter).first.c_str());
593 if ((*iter).second.empty() == false)
594 {
595 built_argv[x++]= strdup((*iter).second.c_str());
596 }
597 }
598
599 if (args)
600 {
601 for (const char **ptr= args; *ptr; ++ptr)
602 {
603 built_argv[x++]= strdup(*ptr);
604 }
605 }
606 built_argv[_argc -1]= NULL;
607 }
608
609 std::string Application::print()
610 {
611 return print_argv(built_argv, _argc);
612 }
613
614 std::string Application::arguments()
615 {
616 std::stringstream arg_buffer;
617
618 for (size_t x= 1 + _use_libtool ? 2 : 0;
619 x < _argc and built_argv[x];
620 x++)
621 {
622 arg_buffer << built_argv[x] << " ";
623 }
624
625 return arg_buffer.str();
626 }
627
628 void Application::delete_argv()
629 {
630 if (built_argv)
631 {
632 for (size_t x= 0; x < _argc; x++)
633 {
634 if (built_argv[x])
635 {
636 ::free(built_argv[x]);
637 }
638 }
639 delete[] built_argv;
640 built_argv= NULL;
641 _argc= 0;
642 }
643 }
644
645
646 int exec_cmdline(const std::string& command, const char *args[], bool use_libtool)
647 {
648 Application app(command, use_libtool);
649
650 Application::error_t ret= app.run(args);
651
652 if (ret != Application::SUCCESS)
653 {
654 return int(ret);
655 }
656
657 return int(app.wait(false));
658 }
659
660 const char *gearmand_binary()
661 {
662 return GEARMAND_BINARY;
663 }
664
665 } // namespace exec_cmdline