1 // Copyright 2010 The Kyua Authors. 2 // All rights reserved. 3 // 4 // Redistribution and use in source and binary forms, with or without 5 // modification, are permitted provided that the following conditions are 6 // met: 7 // 8 // * Redistributions of source code must retain the above copyright 9 // notice, this list of conditions and the following disclaimer. 10 // * Redistributions in binary form must reproduce the above copyright 11 // notice, this list of conditions and the following disclaimer in the 12 // documentation and/or other materials provided with the distribution. 13 // * Neither the name of Google Inc. nor the names of its contributors 14 // may be used to endorse or promote products derived from this software 15 // without specific prior written permission. 16 // 17 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 18 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 19 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 20 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 21 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 22 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 23 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 24 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 25 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 27 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 29 #include "cli/main.hpp" 30 31 #if defined(HAVE_CONFIG_H) 32 # include "config.h" 33 #endif 34 35 extern "C" { 36 #include <signal.h> 37 #include <unistd.h> 38 } 39 40 #include <cstdlib> 41 #include <iostream> 42 #include <string> 43 #include <utility> 44 45 #include "cli/cmd_about.hpp" 46 #include "cli/cmd_config.hpp" 47 #include "cli/cmd_db_exec.hpp" 48 #include "cli/cmd_db_migrate.hpp" 49 #include "cli/cmd_debug.hpp" 50 #include "cli/cmd_help.hpp" 51 #include "cli/cmd_list.hpp" 52 #include "cli/cmd_prepare.hpp" 53 #include "cli/cmd_report.hpp" 54 #include "cli/cmd_report_html.hpp" 55 #include "cli/cmd_report_junit.hpp" 56 #include "cli/cmd_test.hpp" 57 #include "cli/common.ipp" 58 #include "cli/config.hpp" 59 #include "engine/atf.hpp" 60 #include "engine/plain.hpp" 61 #include "engine/scheduler.hpp" 62 #include "engine/tap.hpp" 63 #include "store/exceptions.hpp" 64 #include "utils/cmdline/commands_map.ipp" 65 #include "utils/cmdline/exceptions.hpp" 66 #include "utils/cmdline/globals.hpp" 67 #include "utils/cmdline/options.hpp" 68 #include "utils/cmdline/parser.ipp" 69 #include "utils/cmdline/ui.hpp" 70 #include "utils/config/tree.ipp" 71 #include "utils/env.hpp" 72 #include "utils/format/macros.hpp" 73 #include "utils/fs/operations.hpp" 74 #include "utils/fs/path.hpp" 75 #include "utils/logging/macros.hpp" 76 #include "utils/logging/operations.hpp" 77 #include "utils/optional.ipp" 78 #include "utils/sanity.hpp" 79 #include "utils/signals/exceptions.hpp" 80 81 namespace cmdline = utils::cmdline; 82 namespace config = utils::config; 83 namespace fs = utils::fs; 84 namespace logging = utils::logging; 85 namespace signals = utils::signals; 86 namespace scheduler = engine::scheduler; 87 88 using utils::none; 89 using utils::optional; 90 91 92 namespace { 93 94 95 /// Registers all valid scheduler interfaces. 96 /// 97 /// This is part of Kyua's setup but it is a bit strange to find it here. I am 98 /// not sure what a better location would be though, so for now this is good 99 /// enough. 100 static void 101 register_scheduler_interfaces(void) 102 { 103 scheduler::register_interface( 104 "atf", std::shared_ptr< scheduler::interface >( 105 new engine::atf_interface())); 106 scheduler::register_interface( 107 "plain", std::shared_ptr< scheduler::interface >( 108 new engine::plain_interface())); 109 scheduler::register_interface( 110 "tap", std::shared_ptr< scheduler::interface >( 111 new engine::tap_interface())); 112 } 113 114 115 /// Executes the given subcommand with proper usage_error reporting. 116 /// 117 /// \param ui Object to interact with the I/O of the program. 118 /// \param command The subcommand to execute. 119 /// \param args The part of the command line passed to the subcommand. The 120 /// first item of this collection must match the command name. 121 /// \param user_config The runtime configuration to pass to the subcommand. 122 /// 123 /// \return The exit code of the command. Typically 0 on success, some other 124 /// integer otherwise. 125 /// 126 /// \throw cmdline::usage_error If the user input to the subcommand is invalid. 127 /// This error does not encode the command name within it, so this function 128 /// extends the message in the error to specify which subcommand was 129 /// affected. 130 /// \throw std::exception This propagates any uncaught exception. Such 131 /// exceptions are bugs, but we let them propagate so that the runtime will 132 /// abort and dump core. 133 static int 134 run_subcommand(cmdline::ui* ui, cli::cli_command* command, 135 const cmdline::args_vector& args, 136 const config::tree& user_config) 137 { 138 try { 139 PRE(command->name() == args[0]); 140 return command->main(ui, args, user_config); 141 } catch (const cmdline::usage_error& e) { 142 throw std::pair< std::string, cmdline::usage_error >( 143 command->name(), e); 144 } 145 } 146 147 148 /// Exception-safe version of main. 149 /// 150 /// This function provides the real meat of the entry point of the program. It 151 /// is allowed to throw some known exceptions which are parsed by the caller. 152 /// Doing so keeps this function simpler and allow tests to actually validate 153 /// that the errors reported are accurate. 154 /// 155 /// \return The exit code of the program. Should be EXIT_SUCCESS on success and 156 /// EXIT_FAILURE on failure. The caller extends this to additional integers for 157 /// errors reported through exceptions. 158 /// 159 /// \param ui Object to interact with the I/O of the program. 160 /// \param argc The number of arguments passed on the command line. 161 /// \param argv NULL-terminated array containing the command line arguments. 162 /// \param mock_command An extra command provided for testing purposes; should 163 /// just be NULL other than for tests. 164 /// 165 /// \throw cmdline::usage_error If the user ran the program with invalid 166 /// arguments. 167 /// \throw std::exception This propagates any uncaught exception. Such 168 /// exceptions are bugs, but we let them propagate so that the runtime will 169 /// abort and dump core. 170 static int 171 safe_main(cmdline::ui* ui, int argc, const char* const argv[], 172 cli::cli_command_ptr mock_command) 173 { 174 cmdline::options_vector options; 175 options.push_back(&cli::config_option); 176 options.push_back(&cli::variable_option); 177 const cmdline::string_option loglevel_option( 178 "loglevel", "Level of the messages to log", "level", "info"); 179 options.push_back(&loglevel_option); 180 const cmdline::path_option logfile_option( 181 "logfile", "Path to the log file", "file", 182 cli::detail::default_log_name().c_str()); 183 options.push_back(&logfile_option); 184 185 cmdline::commands_map< cli::cli_command > commands; 186 187 commands.insert(new cli::cmd_about()); 188 commands.insert(new cli::cmd_config()); 189 commands.insert(new cli::cmd_db_exec()); 190 commands.insert(new cli::cmd_db_migrate()); 191 commands.insert(new cli::cmd_help(&options, &commands)); 192 193 commands.insert(new cli::cmd_debug(), "Workspace"); 194 commands.insert(new cli::cmd_list(), "Workspace"); 195 commands.insert(new cli::cmd_prepare(), "Workspace"); 196 commands.insert(new cli::cmd_test(), "Workspace"); 197 198 commands.insert(new cli::cmd_report(), "Reporting"); 199 commands.insert(new cli::cmd_report_html(), "Reporting"); 200 commands.insert(new cli::cmd_report_junit(), "Reporting"); 201 202 if (mock_command.get() != NULL) 203 commands.insert(std::move(mock_command)); 204 205 const cmdline::parsed_cmdline cmdline = cmdline::parse(argc, argv, options); 206 207 const fs::path logfile(cmdline.get_option< cmdline::path_option >( 208 "logfile")); 209 fs::mkdir_p(logfile.branch_path(), 0755); 210 LD(F("Log file is %s") % logfile); 211 utils::install_crash_handlers(logfile.str()); 212 try { 213 logging::set_persistency(cmdline.get_option< cmdline::string_option >( 214 "loglevel"), logfile); 215 } catch (const std::range_error& e) { 216 throw cmdline::usage_error(e.what()); 217 } 218 219 if (cmdline.arguments().empty()) 220 throw cmdline::usage_error("No command provided"); 221 const std::string cmdname = cmdline.arguments()[0]; 222 223 const config::tree user_config = cli::load_config(cmdline, 224 cmdname != "help"); 225 226 cli::cli_command* command = commands.find(cmdname); 227 if (command == NULL) 228 throw cmdline::usage_error(F("Unknown command '%s'") % cmdname); 229 register_scheduler_interfaces(); 230 return run_subcommand(ui, command, cmdline.arguments(), user_config); 231 } 232 233 234 } // anonymous namespace 235 236 237 /// Gets the name of the default log file. 238 /// 239 /// \return The path to the log file. 240 fs::path 241 cli::detail::default_log_name(void) 242 { 243 // Update doc/troubleshooting.texi if you change this algorithm. 244 const optional< std::string > home(utils::getenv("HOME")); 245 if (home) { 246 return logging::generate_log_name(fs::path(home.get()) / ".kyua" / 247 "logs", cmdline::progname()); 248 } else { 249 const optional< std::string > tmpdir(utils::getenv("TMPDIR")); 250 if (tmpdir) { 251 return logging::generate_log_name(fs::path(tmpdir.get()), 252 cmdline::progname()); 253 } else { 254 return logging::generate_log_name(fs::path("/tmp"), 255 cmdline::progname()); 256 } 257 } 258 } 259 260 261 /// Testable entry point, with catch-all exception handlers. 262 /// 263 /// This entry point does not perform any initialization of global state; it is 264 /// provided to allow unit-testing of the utility's entry point. 265 /// 266 /// \param ui Object to interact with the I/O of the program. 267 /// \param argc The number of arguments passed on the command line. 268 /// \param argv NULL-terminated array containing the command line arguments. 269 /// \param mock_command An extra command provided for testing purposes; should 270 /// just be NULL other than for tests. 271 /// 272 /// \return 0 on success, some other integer on error. 273 /// 274 /// \throw std::exception This propagates any uncaught exception. Such 275 /// exceptions are bugs, but we let them propagate so that the runtime will 276 /// abort and dump core. 277 int 278 cli::main(cmdline::ui* ui, const int argc, const char* const* const argv, 279 cli_command_ptr mock_command) 280 { 281 try { 282 const int exit_code = safe_main(ui, argc, argv, std::move(mock_command)); 283 284 // Codes above 1 are reserved to report conditions captured as 285 // exceptions below. 286 INV(exit_code == EXIT_SUCCESS || exit_code == EXIT_FAILURE); 287 288 return exit_code; 289 } catch (const signals::interrupted_error& e) { 290 cmdline::print_error(ui, F("%s.") % e.what()); 291 // Re-deliver the interruption signal to self so that we terminate with 292 // the right status. At this point we should NOT have any custom signal 293 // handlers in place. 294 ::kill(getpid(), e.signo()); 295 LD("Interrupt signal re-delivery did not terminate program"); 296 // If we reach this, something went wrong because we did not exit as 297 // intended. Return an internal error instead. (Would be nicer to 298 // abort in principle, but it wouldn't be a nice experience if it ever 299 // happened.) 300 return 2; 301 } catch (const std::pair< std::string, cmdline::usage_error >& e) { 302 const std::string message = F("Usage error for command %s: %s.") % 303 e.first % e.second.what(); 304 LE(message); 305 ui->err(message); 306 ui->err(F("Type '%s help %s' for usage information.") % 307 cmdline::progname() % e.first); 308 return 3; 309 } catch (const cmdline::usage_error& e) { 310 const std::string message = F("Usage error: %s.") % e.what(); 311 LE(message); 312 ui->err(message); 313 ui->err(F("Type '%s help' for usage information.") % 314 cmdline::progname()); 315 return 3; 316 } catch (const store::old_schema_error& e) { 317 const std::string message = F("The database has schema version %s, " 318 "which is too old; please use db-migrate " 319 "to upgrade it.") % e.old_version(); 320 cmdline::print_error(ui, message); 321 return 2; 322 } catch (const std::runtime_error& e) { 323 cmdline::print_error(ui, F("%s.") % e.what()); 324 return 2; 325 } 326 } 327 328 329 /// Delegate for ::main(). 330 /// 331 /// This function is supposed to be called directly from the top-level ::main() 332 /// function. It takes care of initializing internal libraries and then calls 333 /// main(ui, argc, argv). 334 /// 335 /// \pre This function can only be called once. 336 /// 337 /// \throw std::exception This propagates any uncaught exception. Such 338 /// exceptions are bugs, but we let them propagate so that the runtime will 339 /// abort and dump core. 340 int 341 cli::main(const int argc, const char* const* const argv) 342 { 343 logging::set_inmemory(); 344 345 LI(F("%s %s") % PACKAGE % VERSION); 346 347 std::string plain_args; 348 for (const char* const* arg = argv; *arg != NULL; arg++) 349 plain_args += F(" %s") % *arg; 350 LI(F("Command line:%s") % plain_args); 351 352 cmdline::init(argv[0]); 353 cmdline::ui ui; 354 355 const int exit_code = main(&ui, argc, argv); 356 LI(F("Clean exit with code %s") % exit_code); 357 return exit_code; 358 } 359