Update
[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 "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 delete_argv();
147 }
148
149 Application::error_t Application::run(const char *args[])
150 {
151 stdin_fd.reset();
152 stdout_fd.reset();
153 stderr_fd.reset();
154 _stdout_buffer.clear();
155 _stderr_buffer.clear();
156
157 posix_spawn_file_actions_t file_actions;
158 posix_spawn_file_actions_init(&file_actions);
159
160 stdin_fd.dup_for_spawn(Application::Pipe::READ, file_actions, STDIN_FILENO);
161 stdout_fd.dup_for_spawn(Application::Pipe::WRITE, file_actions, STDOUT_FILENO);
162 stderr_fd.dup_for_spawn(Application::Pipe::WRITE, file_actions, STDERR_FILENO);
163
164 create_argv(args);
165
166 int spawn_ret;
167 if (_use_gdb)
168 {
169 std::string gdb_run_file= create_tmpfile(_exectuble_name);
170 std::fstream file_stream;
171 file_stream.open(gdb_run_file.c_str(), std::fstream::out | std::fstream::trunc);
172
173 _gdb_filename= create_tmpfile(_exectuble_name);
174 file_stream
175 << "set logging redirect on" << std::endl
176 << "set logging file " << _gdb_filename << std::endl
177 << "set logging overwrite on" << std::endl
178 << "set logging on" << std::endl
179 << "set environment LIBTEST_IN_GDB=1" << std::endl
180 << "run " << arguments() << std::endl
181 << "thread apply all bt" << std::endl
182 << "quit" << std::endl;
183
184 fatal_assert(file_stream.good());
185 file_stream.close();
186
187 if (_use_libtool)
188 {
189 // libtool --mode=execute gdb -f -x binary
190 char *argv[]= {
191 const_cast<char *>(libtool()),
192 const_cast<char *>("--mode=execute"),
193 const_cast<char *>("gdb"),
194 const_cast<char *>("-batch"),
195 const_cast<char *>("-f"),
196 const_cast<char *>("-x"),
197 const_cast<char *>(gdb_run_file.c_str()),
198 const_cast<char *>(_exectuble_with_path.c_str()),
199 0};
200
201 spawn_ret= posix_spawnp(&_pid, libtool(), &file_actions, NULL, argv, NULL);
202 }
203 else
204 {
205 // gdb binary
206 char *argv[]= {
207 const_cast<char *>("gdb"),
208 const_cast<char *>("-batch"),
209 const_cast<char *>("-f"),
210 const_cast<char *>("-x"),
211 const_cast<char *>(gdb_run_file.c_str()),
212 const_cast<char *>(_exectuble_with_path.c_str()),
213 0};
214 spawn_ret= posix_spawnp(&_pid, "gdb", &file_actions, NULL, argv, NULL);
215 }
216 }
217 else
218 {
219 if (_use_libtool)
220 {
221 spawn_ret= posix_spawn(&_pid, built_argv[0], &file_actions, NULL, built_argv, NULL);
222 }
223 else
224 {
225 spawn_ret= posix_spawnp(&_pid, built_argv[0], &file_actions, NULL, built_argv, NULL);
226 }
227 }
228
229 posix_spawn_file_actions_destroy(&file_actions);
230
231 stdin_fd.close(Application::Pipe::READ);
232 stdout_fd.close(Application::Pipe::WRITE);
233 stderr_fd.close(Application::Pipe::WRITE);
234
235 if (spawn_ret)
236 {
237 return Application::INVALID;
238 }
239
240 return Application::SUCCESS;
241 }
242
243 bool Application::check() const
244 {
245 Error << "Testing " << _exectuble;
246 if (kill(_pid, 0) == 0)
247 {
248 return true;
249 }
250
251 return false;
252 }
253
254 void Application::murder()
255 {
256 slurp();
257 kill(_pid, SIGTERM);
258 }
259
260 // false means that no data was returned
261 bool Application::slurp()
262 {
263 struct pollfd fds[2];
264 fds[0].fd= stdout_fd.fd()[0];
265 fds[0].events= POLLIN;
266 fds[0].revents= 0;
267 fds[1].fd= stderr_fd.fd()[0];
268 fds[1].events= POLLIN;
269 fds[1].revents= 0;
270
271 int active_fd;
272 if ((active_fd= poll(fds, 2, 400)) == -1)
273 {
274 int error;
275 switch ((error= errno))
276 {
277 #ifdef TARGET_OS_LINUX
278 case ERESTART:
279 #endif
280 case EINTR:
281 break;
282
283 case EFAULT:
284 case ENOMEM:
285 fatal_message(strerror(error));
286 break;
287
288 case EINVAL:
289 fatal_message("RLIMIT_NOFILE exceeded, or if OSX the timeout value was invalid");
290 break;
291
292 default:
293 fatal_message(strerror(error));
294 break;
295 }
296 }
297
298 if (active_fd == 0)
299 {
300 return false;
301 }
302
303 if (fds[0].revents == POLLIN)
304 {
305 ssize_t read_length;
306 char buffer[1024]= { 0 };
307 while ((read_length= ::read(stdout_fd.fd()[0], buffer, sizeof(buffer))))
308 {
309 if (read_length == -1)
310 {
311 switch(errno)
312 {
313 case EAGAIN:
314 continue;
315
316 default:
317 Error << strerror(errno);
318 break;
319 }
320
321 break;
322 }
323 _stdout_buffer.reserve(read_length +1);
324 for (size_t x= 0; x < read_length; x++)
325 {
326 _stdout_buffer.push_back(buffer[x]);
327 }
328 // @todo Suck up all output code here
329 }
330 }
331
332 if (fds[1].revents == POLLIN)
333 {
334 ssize_t read_length;
335 char buffer[1024]= { 0 };
336 while ((read_length= ::read(stderr_fd.fd()[0], buffer, sizeof(buffer))))
337 {
338 if (read_length == -1)
339 {
340 switch(errno)
341 {
342 case EAGAIN:
343 continue;
344
345 default:
346 Error << strerror(errno);
347 break;
348 }
349
350 break;
351 }
352 _stderr_buffer.reserve(read_length +1);
353 for (size_t x= 0; x < read_length; x++)
354 {
355 _stderr_buffer.push_back(buffer[x]);
356 }
357 // @todo Suck up all errput code here
358 }
359 }
360
361 return true;
362 }
363
364 Application::error_t Application::wait()
365 {
366 fatal_assert(_pid != -1);
367
368 slurp();
369
370 error_t exit_code= FAILURE;
371 {
372 int status= 0;
373 pid_t waited_pid;
374 if ((waited_pid= waitpid(_pid, &status, 0)) == -1)
375 {
376 switch (errno)
377 {
378 case ECHILD:
379 exit_code= Application::SUCCESS;
380 break;
381
382 default:
383 Error << "Error occured while waitpid(" << strerror(errno) << ") on pid " << int(_pid);
384 }
385 }
386 else
387 {
388 if (waited_pid != _pid)
389 {
390 throw libtest::fatal(LIBYATL_DEFAULT_PARAM, "Pid mismatch, %d != %d", int(waited_pid), int(_pid));
391 }
392 exit_code= int_to_error_t(exited_successfully(status));
393 }
394 }
395
396 #if 0
397 if (exit_code == Application::INVALID)
398 {
399 Error << print_argv(built_argv, _argc);
400 }
401 #endif
402
403 return exit_code;
404 }
405
406 void Application::add_long_option(const std::string& name, const std::string& option_value)
407 {
408 std::string arg(name);
409 arg+= option_value;
410 _options.push_back(std::make_pair(arg, std::string()));
411 }
412
413 void Application::add_option(const std::string& arg)
414 {
415 _options.push_back(std::make_pair(arg, std::string()));
416 }
417
418 void Application::add_option(const std::string& name, const std::string& value)
419 {
420 _options.push_back(std::make_pair(name, value));
421 }
422
423 Application::Pipe::Pipe()
424 {
425 _fd[0]= -1;
426 _fd[1]= -1;
427 _open[0]= false;
428 _open[1]= false;
429 }
430
431 void Application::Pipe::nonblock()
432 {
433 int ret;
434 if ((ret= fcntl(_fd[0], F_GETFL, 0)) == -1)
435 {
436 Error << "fcntl(F_GETFL) " << strerror(errno);
437 throw strerror(errno);
438 }
439
440 if ((ret= fcntl(_fd[0], F_SETFL, ret | O_NONBLOCK)) == -1)
441 {
442 Error << "fcntl(F_SETFL) " << strerror(errno);
443 throw strerror(errno);
444 }
445 }
446
447 void Application::Pipe::reset()
448 {
449 close(READ);
450 close(WRITE);
451
452 if (pipe(_fd) == -1)
453 {
454 throw strerror(errno);
455 }
456 _open[0]= true;
457 _open[1]= true;
458
459 if (0)
460 {
461 nonblock();
462 }
463 }
464
465 Application::Pipe::~Pipe()
466 {
467 close(READ);
468 close(WRITE);
469 }
470
471 void Application::Pipe::dup_for_spawn(const close_t& arg, posix_spawn_file_actions_t& file_actions, const int newfildes)
472 {
473 int type= int(arg);
474
475 int ret;
476 if ((ret= posix_spawn_file_actions_adddup2(&file_actions, _fd[type], newfildes )) < 0)
477 {
478 Error << "posix_spawn_file_actions_adddup2(" << strerror(ret) << ")";
479 throw strerror(ret);
480 }
481
482 if ((ret= posix_spawn_file_actions_addclose(&file_actions, _fd[type])) < 0)
483 {
484 Error << "posix_spawn_file_actions_adddup2(" << strerror(ret) << ")";
485 throw strerror(ret);
486 }
487 }
488
489 void Application::Pipe::close(const close_t& arg)
490 {
491 int type= int(arg);
492
493 if (_open[type])
494 {
495 int ret;
496 if (::close(_fd[type]) == -1)
497 {
498 Error << "close(" << strerror(errno) << ")";
499 }
500 _open[type]= false;
501 _fd[type]= -1;
502 }
503 }
504
505 void Application::create_argv(const char *args[])
506 {
507 _argc= 2 +_use_libtool ? 2 : 0; // +1 for the command, +2 for libtool/mode=execute, +1 for the NULL
508
509 if (_use_libtool)
510 {
511 _argc+= 2; // +2 for libtool --mode=execute
512 }
513
514 /*
515 valgrind --error-exitcode=1 --leak-check=yes --show-reachable=yes --track-fds=yes --malloc-fill=A5 --free-fill=DE
516 */
517 if (_use_valgrind)
518 {
519 _argc+= 7;
520 }
521 else if (_use_gdb) // gdb
522 {
523 _argc+= 1;
524 }
525
526 for (Options::const_iterator iter= _options.begin(); iter != _options.end(); iter++)
527 {
528 _argc++;
529 if ((*iter).second.empty() == false)
530 {
531 _argc++;
532 }
533 }
534
535 if (args)
536 {
537 for (const char **ptr= args; *ptr; ++ptr)
538 {
539 _argc++;
540 }
541 }
542
543 delete_argv();
544 built_argv= new char * [_argc];
545
546 size_t x= 0;
547 if (_use_libtool)
548 {
549 assert(libtool());
550 built_argv[x++]= strdup(libtool());
551 built_argv[x++]= strdup("--mode=execute");
552 }
553
554 if (_use_valgrind)
555 {
556 /*
557 valgrind --error-exitcode=1 --leak-check=yes --show-reachable=yes --track-fds=yes --malloc-fill=A5 --free-fill=DE
558 */
559 built_argv[x++]= strdup("valgrind");
560 built_argv[x++]= strdup("--error-exitcode=1");
561 built_argv[x++]= strdup("--leak-check=yes");
562 built_argv[x++]= strdup("--show-reachable=yes");
563 built_argv[x++]= strdup("--track-fds=yes");
564 built_argv[x++]= strdup("--malloc-fill=A5");
565 built_argv[x++]= strdup("--free-fill=DE");
566 }
567 else if (_use_gdb)
568 {
569 built_argv[x++]= strdup("gdb");
570 }
571
572 built_argv[x++]= strdup(_exectuble_with_path.c_str());
573
574 for (Options::const_iterator iter= _options.begin(); iter != _options.end(); iter++)
575 {
576 built_argv[x++]= strdup((*iter).first.c_str());
577 if ((*iter).second.empty() == false)
578 {
579 built_argv[x++]= strdup((*iter).second.c_str());
580 }
581 }
582
583 if (args)
584 {
585 for (const char **ptr= args; *ptr; ++ptr)
586 {
587 built_argv[x++]= strdup(*ptr);
588 }
589 }
590 built_argv[_argc -1]= NULL;
591 }
592
593 std::string Application::print()
594 {
595 return print_argv(built_argv, _argc);
596 }
597
598 std::string Application::arguments()
599 {
600 std::stringstream arg_buffer;
601
602 for (size_t x= 1 + _use_libtool ? 2 : 0;
603 x < _argc and built_argv[x];
604 x++)
605 {
606 arg_buffer << built_argv[x] << " ";
607 }
608
609 return arg_buffer.str();
610 }
611
612 void Application::delete_argv()
613 {
614 if (built_argv)
615 {
616 for (size_t x= 0; x < _argc; x++)
617 {
618 if (built_argv[x])
619 {
620 ::free(built_argv[x]);
621 }
622 }
623 delete[] built_argv;
624 built_argv= NULL;
625 _argc= 0;
626 }
627 }
628
629
630 int exec_cmdline(const std::string& command, const char *args[], bool use_libtool)
631 {
632 Application app(command, use_libtool);
633
634 Application::error_t ret= app.run(args);
635
636 if (ret != Application::SUCCESS)
637 {
638 return int(ret);
639 }
640
641 return int(app.wait());
642 }
643
644 const char *gearmand_binary()
645 {
646 return GEARMAND_BINARY;
647 }
648
649 } // namespace exec_cmdline