xref: /freebsd/contrib/kyua/cli/main.cpp (revision 8a7df6c58d549bd2eaa5cad30b2ef93c3eca3c18)
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/googletest.hpp"
61 #include "engine/plain.hpp"
62 #include "engine/scheduler.hpp"
63 #include "engine/tap.hpp"
64 #include "store/exceptions.hpp"
65 #include "utils/cmdline/commands_map.ipp"
66 #include "utils/cmdline/exceptions.hpp"
67 #include "utils/cmdline/globals.hpp"
68 #include "utils/cmdline/options.hpp"
69 #include "utils/cmdline/parser.ipp"
70 #include "utils/cmdline/ui.hpp"
71 #include "utils/config/tree.ipp"
72 #include "utils/env.hpp"
73 #include "utils/format/macros.hpp"
74 #include "utils/fs/operations.hpp"
75 #include "utils/fs/path.hpp"
76 #include "utils/logging/macros.hpp"
77 #include "utils/logging/operations.hpp"
78 #include "utils/optional.ipp"
79 #include "utils/sanity.hpp"
80 #include "utils/signals/exceptions.hpp"
81 
82 namespace cmdline = utils::cmdline;
83 namespace config = utils::config;
84 namespace fs = utils::fs;
85 namespace logging = utils::logging;
86 namespace signals = utils::signals;
87 namespace scheduler = engine::scheduler;
88 
89 using utils::none;
90 using utils::optional;
91 
92 
93 namespace {
94 
95 
96 /// Registers all valid scheduler interfaces.
97 ///
98 /// This is part of Kyua's setup but it is a bit strange to find it here.  I am
99 /// not sure what a better location would be though, so for now this is good
100 /// enough.
101 static void
102 register_scheduler_interfaces(void)
103 {
104     scheduler::register_interface(
105         "atf", std::shared_ptr< scheduler::interface >(
106             new engine::atf_interface()));
107     scheduler::register_interface(
108         "googletest", std::shared_ptr< scheduler::interface >(
109             new engine::googletest_interface()));
110     scheduler::register_interface(
111         "plain", std::shared_ptr< scheduler::interface >(
112             new engine::plain_interface()));
113     scheduler::register_interface(
114         "tap", std::shared_ptr< scheduler::interface >(
115             new engine::tap_interface()));
116 }
117 
118 
119 /// Executes the given subcommand with proper usage_error reporting.
120 ///
121 /// \param ui Object to interact with the I/O of the program.
122 /// \param command The subcommand to execute.
123 /// \param args The part of the command line passed to the subcommand.  The
124 ///     first item of this collection must match the command name.
125 /// \param user_config The runtime configuration to pass to the subcommand.
126 ///
127 /// \return The exit code of the command.  Typically 0 on success, some other
128 /// integer otherwise.
129 ///
130 /// \throw cmdline::usage_error If the user input to the subcommand is invalid.
131 ///     This error does not encode the command name within it, so this function
132 ///     extends the message in the error to specify which subcommand was
133 ///     affected.
134 /// \throw std::exception This propagates any uncaught exception.  Such
135 ///     exceptions are bugs, but we let them propagate so that the runtime will
136 ///     abort and dump core.
137 static int
138 run_subcommand(cmdline::ui* ui, cli::cli_command* command,
139                const cmdline::args_vector& args,
140                const config::tree& user_config)
141 {
142     try {
143         PRE(command->name() == args[0]);
144         return command->main(ui, args, user_config);
145     } catch (const cmdline::usage_error& e) {
146         throw std::pair< std::string, cmdline::usage_error >(
147             command->name(), e);
148     }
149 }
150 
151 
152 /// Exception-safe version of main.
153 ///
154 /// This function provides the real meat of the entry point of the program.  It
155 /// is allowed to throw some known exceptions which are parsed by the caller.
156 /// Doing so keeps this function simpler and allow tests to actually validate
157 /// that the errors reported are accurate.
158 ///
159 /// \return The exit code of the program.  Should be EXIT_SUCCESS on success and
160 /// EXIT_FAILURE on failure.  The caller extends this to additional integers for
161 /// errors reported through exceptions.
162 ///
163 /// \param ui Object to interact with the I/O of the program.
164 /// \param argc The number of arguments passed on the command line.
165 /// \param argv NULL-terminated array containing the command line arguments.
166 /// \param mock_command An extra command provided for testing purposes; should
167 ///     just be NULL other than for tests.
168 ///
169 /// \throw cmdline::usage_error If the user ran the program with invalid
170 ///     arguments.
171 /// \throw std::exception This propagates any uncaught exception.  Such
172 ///     exceptions are bugs, but we let them propagate so that the runtime will
173 ///     abort and dump core.
174 static int
175 safe_main(cmdline::ui* ui, int argc, const char* const argv[],
176           cli::cli_command_ptr mock_command)
177 {
178     cmdline::options_vector options;
179     options.push_back(&cli::config_option);
180     options.push_back(&cli::variable_option);
181     const cmdline::string_option loglevel_option(
182         "loglevel", "Level of the messages to log", "level", "info");
183     options.push_back(&loglevel_option);
184     const cmdline::path_option logfile_option(
185         "logfile", "Path to the log file", "file",
186         cli::detail::default_log_name().c_str());
187     options.push_back(&logfile_option);
188 
189     cmdline::commands_map< cli::cli_command > commands;
190 
191     commands.insert(new cli::cmd_about());
192     commands.insert(new cli::cmd_config());
193     commands.insert(new cli::cmd_db_exec());
194     commands.insert(new cli::cmd_db_migrate());
195     commands.insert(new cli::cmd_help(&options, &commands));
196 
197     commands.insert(new cli::cmd_debug(), "Workspace");
198     commands.insert(new cli::cmd_list(), "Workspace");
199     commands.insert(new cli::cmd_prepare(), "Workspace");
200     commands.insert(new cli::cmd_test(), "Workspace");
201 
202     commands.insert(new cli::cmd_report(), "Reporting");
203     commands.insert(new cli::cmd_report_html(), "Reporting");
204     commands.insert(new cli::cmd_report_junit(), "Reporting");
205 
206     if (mock_command.get() != NULL)
207         commands.insert(std::move(mock_command));
208 
209     const cmdline::parsed_cmdline cmdline = cmdline::parse(argc, argv, options);
210 
211     const fs::path logfile(cmdline.get_option< cmdline::path_option >(
212         "logfile"));
213     fs::mkdir_p(logfile.branch_path(), 0755);
214     LD(F("Log file is %s") % logfile);
215     utils::install_crash_handlers(logfile.str());
216     try {
217         logging::set_persistency(cmdline.get_option< cmdline::string_option >(
218             "loglevel"), logfile);
219     } catch (const std::range_error& e) {
220         throw cmdline::usage_error(e.what());
221     }
222 
223     if (cmdline.arguments().empty())
224         throw cmdline::usage_error("No command provided");
225     const std::string cmdname = cmdline.arguments()[0];
226 
227     const config::tree user_config = cli::load_config(cmdline,
228                                                       cmdname != "help");
229 
230     cli::cli_command* command = commands.find(cmdname);
231     if (command == NULL)
232         throw cmdline::usage_error(F("Unknown command '%s'") % cmdname);
233     register_scheduler_interfaces();
234     return run_subcommand(ui, command, cmdline.arguments(), user_config);
235 }
236 
237 
238 }  // anonymous namespace
239 
240 
241 /// Gets the name of the default log file.
242 ///
243 /// \return The path to the log file.
244 fs::path
245 cli::detail::default_log_name(void)
246 {
247     // Update doc/troubleshooting.texi if you change this algorithm.
248     const optional< std::string > home(utils::getenv("HOME"));
249     if (home) {
250         return logging::generate_log_name(fs::path(home.get()) / ".kyua" /
251                                           "logs", cmdline::progname());
252     } else {
253         const optional< std::string > tmpdir(utils::getenv("TMPDIR"));
254         if (tmpdir) {
255             return logging::generate_log_name(fs::path(tmpdir.get()),
256                                               cmdline::progname());
257         } else {
258             return logging::generate_log_name(fs::path("/tmp"),
259                                               cmdline::progname());
260         }
261     }
262 }
263 
264 
265 /// Testable entry point, with catch-all exception handlers.
266 ///
267 /// This entry point does not perform any initialization of global state; it is
268 /// provided to allow unit-testing of the utility's entry point.
269 ///
270 /// \param ui Object to interact with the I/O of the program.
271 /// \param argc The number of arguments passed on the command line.
272 /// \param argv NULL-terminated array containing the command line arguments.
273 /// \param mock_command An extra command provided for testing purposes; should
274 ///     just be NULL other than for tests.
275 ///
276 /// \return 0 on success, some other integer on error.
277 ///
278 /// \throw std::exception This propagates any uncaught exception.  Such
279 ///     exceptions are bugs, but we let them propagate so that the runtime will
280 ///     abort and dump core.
281 int
282 cli::main(cmdline::ui* ui, const int argc, const char* const* const argv,
283           cli_command_ptr mock_command)
284 {
285     try {
286         const int exit_code = safe_main(ui, argc, argv, std::move(mock_command));
287 
288         // Codes above 1 are reserved to report conditions captured as
289         // exceptions below.
290         INV(exit_code == EXIT_SUCCESS || exit_code == EXIT_FAILURE);
291 
292         return exit_code;
293     } catch (const signals::interrupted_error& e) {
294         cmdline::print_error(ui, F("%s.") % e.what());
295         // Re-deliver the interruption signal to self so that we terminate with
296         // the right status.  At this point we should NOT have any custom signal
297         // handlers in place.
298         ::kill(getpid(), e.signo());
299         LD("Interrupt signal re-delivery did not terminate program");
300         // If we reach this, something went wrong because we did not exit as
301         // intended.  Return an internal error instead.  (Would be nicer to
302         // abort in principle, but it wouldn't be a nice experience if it ever
303         // happened.)
304         return 2;
305     } catch (const std::pair< std::string, cmdline::usage_error >& e) {
306         const std::string message = F("Usage error for command %s: %s.") %
307             e.first % e.second.what();
308         LE(message);
309         ui->err(message);
310         ui->err(F("Type '%s help %s' for usage information.") %
311                 cmdline::progname() % e.first);
312         return 3;
313     } catch (const cmdline::usage_error& e) {
314         const std::string message = F("Usage error: %s.") % e.what();
315         LE(message);
316         ui->err(message);
317         ui->err(F("Type '%s help' for usage information.") %
318                 cmdline::progname());
319         return 3;
320     } catch (const store::old_schema_error& e) {
321         const std::string message = F("The database has schema version %s, "
322                                       "which is too old; please use db-migrate "
323                                       "to upgrade it.") % e.old_version();
324         cmdline::print_error(ui, message);
325         return 2;
326     } catch (const std::runtime_error& e) {
327         cmdline::print_error(ui, F("%s.") % e.what());
328         return 2;
329     }
330 }
331 
332 
333 /// Delegate for ::main().
334 ///
335 /// This function is supposed to be called directly from the top-level ::main()
336 /// function.  It takes care of initializing internal libraries and then calls
337 /// main(ui, argc, argv).
338 ///
339 /// \pre This function can only be called once.
340 ///
341 /// \throw std::exception This propagates any uncaught exception.  Such
342 ///     exceptions are bugs, but we let them propagate so that the runtime will
343 ///     abort and dump core.
344 int
345 cli::main(const int argc, const char* const* const argv)
346 {
347     logging::set_inmemory();
348 
349     LI(F("%s %s") % PACKAGE % VERSION);
350 
351     std::string plain_args;
352     for (const char* const* arg = argv; *arg != NULL; arg++)
353         plain_args += F(" %s") % *arg;
354     LI(F("Command line:%s") % plain_args);
355 
356     cmdline::init(argv[0]);
357     cmdline::ui ui;
358 
359     const int exit_code = main(&ui, argc, argv);
360     LI(F("Clean exit with code %s") % exit_code);
361     return exit_code;
362 }
363