1 /* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */
3 #include "cli/consolecommand.hpp"
4 #include "config/configcompiler.hpp"
5 #include "remote/apiclient.hpp"
6 #include "remote/consolehandler.hpp"
7 #include "remote/url.hpp"
8 #include "base/configwriter.hpp"
9 #include "base/serializer.hpp"
10 #include "base/json.hpp"
11 #include "base/console.hpp"
12 #include "base/application.hpp"
13 #include "base/objectlock.hpp"
14 #include "base/unixsocket.hpp"
15 #include "base/utility.hpp"
16 #include "base/networkstream.hpp"
17 #include "base/exception.hpp"
21 #include "cli/editline.hpp"
22 #endif /* HAVE_EDITLINE */
24 using namespace icinga;
25 namespace po = boost::program_options;
27 static ScriptFrame *l_ScriptFrame;
28 static ApiClient::Ptr l_ApiClient;
29 static String l_Session;
31 REGISTER_CLICOMMAND("console", ConsoleCommand);
33 INITIALIZE_ONCE(&ConsoleCommand::StaticInitialize);
35 extern "C" void dbg_spawn_console()
37 ScriptFrame frame(true);
38 ConsoleCommand::RunScriptConsole(frame);
41 extern "C" void dbg_inspect_value(const Value& value)
43 ConfigWriter::EmitValue(std::cout, 1, Serialize(value, 0));
44 std::cout << std::endl;
47 extern "C" void dbg_inspect_object(Object *obj)
49 Object::Ptr objr = obj;
50 dbg_inspect_value(objr);
53 extern "C" void dbg_eval(const char *text)
55 std::unique_ptr<Expression> expr;
58 ScriptFrame frame(true);
59 expr = ConfigCompiler::CompileText("<dbg>", text);
60 Value result = Serialize(expr->Evaluate(frame), 0);
61 dbg_inspect_value(result);
62 } catch (const std::exception& ex) {
63 std::cout << "Error: " << DiagnosticInformation(ex) << "\n";
67 extern "C" void dbg_eval_with_value(const Value& value, const char *text)
69 std::unique_ptr<Expression> expr;
72 ScriptFrame frame(true);
73 frame.Locals = new Dictionary({
76 expr = ConfigCompiler::CompileText("<dbg>", text);
77 Value result = Serialize(expr->Evaluate(frame), 0);
78 dbg_inspect_value(result);
79 } catch (const std::exception& ex) {
80 std::cout << "Error: " << DiagnosticInformation(ex) << "\n";
84 extern "C" void dbg_eval_with_object(Object *object, const char *text)
86 std::unique_ptr<Expression> expr;
89 ScriptFrame frame(true);
90 frame.Locals = new Dictionary({
93 expr = ConfigCompiler::CompileText("<dbg>", text);
94 Value result = Serialize(expr->Evaluate(frame), 0);
95 dbg_inspect_value(result);
96 } catch (const std::exception& ex) {
97 std::cout << "Error: " << DiagnosticInformation(ex) << "\n";
101 void ConsoleCommand::BreakpointHandler(ScriptFrame& frame, ScriptError *ex, const DebugInfo& di)
103 static boost::mutex mutex;
104 boost::mutex::scoped_lock lock(mutex);
106 if (!Application::GetScriptDebuggerEnabled())
109 if (ex && ex->IsHandledByDebugger())
112 std::cout << "Breakpoint encountered.\n";
115 std::cout << "Exception: " << DiagnosticInformation(*ex) << "\n";
116 ex->SetHandledByDebugger(true);
118 ShowCodeLocation(std::cout, di);
120 std::cout << "You can inspect expressions (such as variables) by entering them at the prompt.\n"
121 << "To leave the debugger and continue the program use \"$continue\".\n"
122 << "For further commands see \"$help\".\n";
125 rl_completion_entry_function = ConsoleCommand::ConsoleCompleteHelper;
126 rl_completion_append_character = '\0';
127 #endif /* HAVE_EDITLINE */
129 ConsoleCommand::RunScriptConsole(frame);
132 void ConsoleCommand::StaticInitialize()
134 Expression::OnBreakpoint.connect(&ConsoleCommand::BreakpointHandler);
137 String ConsoleCommand::GetDescription() const
139 return "Interprets Icinga script expressions.";
142 String ConsoleCommand::GetShortDescription() const
144 return "Icinga console";
147 ImpersonationLevel ConsoleCommand::GetImpersonationLevel() const
149 return ImpersonateNone;
152 void ConsoleCommand::InitParameters(boost::program_options::options_description& visibleDesc,
153 boost::program_options::options_description& hiddenDesc) const
155 visibleDesc.add_options()
156 ("connect,c", po::value<std::string>(), "connect to an Icinga 2 instance")
157 ("eval,e", po::value<std::string>(), "evaluate expression and terminate")
158 ("file,r", po::value<std::string>(), "evaluate a file and terminate")
159 ("syntax-only", "only validate syntax (requires --eval or --file)")
160 ("sandbox", "enable sandbox mode")
165 char *ConsoleCommand::ConsoleCompleteHelper(const char *word, int state)
167 static std::vector<String> matches;
171 matches = ConsoleHandler::GetAutocompletionSuggestions(word, *l_ScriptFrame);
174 boost::condition_variable cv;
176 Array::Ptr suggestions;
178 l_ApiClient->AutocompleteScript(l_Session, word, l_ScriptFrame->Sandboxed,
179 std::bind(&ConsoleCommand::AutocompleteScriptCompletionHandler,
180 std::ref(mutex), std::ref(cv), std::ref(ready),
182 std::ref(suggestions)));
185 boost::mutex::scoped_lock lock(mutex);
192 ObjectLock olock(suggestions);
193 std::copy(suggestions->Begin(), suggestions->End(), std::back_inserter(matches));
197 if (state >= static_cast<int>(matches.size()))
200 return strdup(matches[state].CStr());
202 #endif /* HAVE_EDITLINE */
205 * The entry point for the "console" CLI command.
207 * @returns An exit status.
209 int ConsoleCommand::Run(const po::variables_map& vm, const std::vector<std::string>& ap) const
212 rl_completion_entry_function = ConsoleCommand::ConsoleCompleteHelper;
213 rl_completion_append_character = '\0';
214 #endif /* HAVE_EDITLINE */
216 String addr, session;
217 ScriptFrame scriptFrame(true);
219 session = Utility::NewUniqueID();
221 if (vm.count("sandbox"))
222 scriptFrame.Sandboxed = true;
224 scriptFrame.Self = scriptFrame.Locals;
226 if (!vm.count("eval") && !vm.count("file"))
227 std::cout << "Icinga 2 (version: " << Application::GetAppVersion() << ")\n"
228 << "Type $help to view available commands.\n";
231 String addrEnv = Utility::GetFromEnvironment("ICINGA2_API_URL");
232 if (!addrEnv.IsEmpty())
235 if (vm.count("connect"))
236 addr = vm["connect"].as<std::string>();
239 bool syntaxOnly = false;
241 if (vm.count("syntax-only")) {
242 if (vm.count("eval") || vm.count("file"))
245 std::cerr << "The option --syntax-only can only be used in combination with --eval or --file." << std::endl;
250 String commandFileName;
252 if (vm.count("eval"))
253 command = vm["eval"].as<std::string>();
254 else if (vm.count("file")) {
255 commandFileName = vm["file"].as<std::string>();
258 std::ifstream fp(commandFileName.CStr());
259 fp.exceptions(std::ifstream::failbit | std::ifstream::badbit);
260 command = String(std::istreambuf_iterator<char>(fp), std::istreambuf_iterator<char>());
261 } catch (const std::exception&) {
262 std::cerr << "Could not read file '" << commandFileName << "'." << std::endl;
267 return RunScriptConsole(scriptFrame, addr, session, command, commandFileName, syntaxOnly);
270 int ConsoleCommand::RunScriptConsole(ScriptFrame& scriptFrame, const String& addr, const String& session, const String& commandOnce, const String& commandOnceFileName, bool syntaxOnly)
272 std::map<String, String> lines;
276 String homeEnv = Utility::GetFromEnvironment("HOME");
279 std::fstream historyfp;
281 if (!homeEnv.IsEmpty()) {
282 historyPath = String(homeEnv) + "/.icinga2_history";
284 historyfp.open(historyPath.CStr(), std::fstream::in);
287 while (std::getline(historyfp, line.GetData()))
288 add_history(line.CStr());
292 #endif /* HAVE_EDITLINE */
294 l_ScriptFrame = &scriptFrame;
297 if (!addr.IsEmpty()) {
302 } catch (const std::exception& ex) {
303 Log(LogCritical, "ConsoleCommand", ex.what());
307 String usernameEnv = Utility::GetFromEnvironment("ICINGA2_API_USERNAME");
308 String passwordEnv = Utility::GetFromEnvironment("ICINGA2_API_PASSWORD");
310 if (!usernameEnv.IsEmpty())
311 url->SetUsername(usernameEnv);
312 if (!passwordEnv.IsEmpty())
313 url->SetPassword(passwordEnv);
315 if (url->GetPort().IsEmpty())
316 url->SetPort("5665");
318 l_ApiClient = new ApiClient(url->GetHost(), url->GetPort(), url->GetUsername(), url->GetPassword());
321 while (std::cin.good()) {
324 if (commandOnceFileName.IsEmpty())
325 fileName = "<" + Convert::ToString(next_line) + ">";
327 fileName = commandOnceFileName;
331 bool continuation = false;
337 if (commandOnce.IsEmpty()) {
339 std::ostringstream promptbuf;
340 std::ostream& os = promptbuf;
341 #else /* HAVE_EDITLINE */
342 std::ostream& os = std::cout;
343 #endif /* HAVE_EDITLINE */
353 String prompt = promptbuf.str();
356 cline = readline(prompt.CStr());
361 if (commandOnce.IsEmpty() && cline[0] != '\0') {
364 if (!historyPath.IsEmpty()) {
365 historyfp.open(historyPath.CStr(), std::fstream::out | std::fstream::app);
366 historyfp << cline << "\n";
374 #else /* HAVE_EDITLINE */
375 std::getline(std::cin, line);
376 #endif /* HAVE_EDITLINE */
380 if (!line.empty() && line[0] == '$') {
381 if (line == "$continue" || line == "$quit" || line == "$exit")
383 else if (line == "$help")
384 std::cout << "Welcome to the Icinga 2 debug console.\n"
386 " $continue Continue running Icinga 2 (script debugger).\n"
387 " $quit, $exit Stop debugging and quit the console.\n"
388 " $help Print this help.\n\n"
389 "For more information on how to use this console, please consult the documentation at https://icinga.com/docs\n";
391 std::cout << "Unknown debugger command: " << line << "\n";
396 if (!command.empty())
401 std::unique_ptr<Expression> expr;
404 lines[fileName] = command;
409 expr = ConfigCompiler::CompileText(fileName, command);
411 /* This relies on the fact that - for syntax errors - CompileText()
412 * returns an AST where the top-level expression is a 'throw'. */
413 if (!syntaxOnly || dynamic_cast<ThrowExpression *>(expr.get())) {
415 std::cerr << " => " << command << std::endl;
416 result = Serialize(expr->Evaluate(scriptFrame), 0);
421 boost::condition_variable cv;
423 boost::exception_ptr eptr;
425 l_ApiClient->ExecuteScript(l_Session, command, scriptFrame.Sandboxed,
426 std::bind(&ConsoleCommand::ExecuteScriptCompletionHandler,
427 std::ref(mutex), std::ref(cv), std::ref(ready),
429 std::ref(result), std::ref(eptr)));
432 boost::mutex::scoped_lock lock(mutex);
438 boost::rethrow_exception(eptr);
441 if (commandOnce.IsEmpty()) {
442 std::cout << ConsoleColorTag(Console_ForegroundCyan);
443 ConfigWriter::EmitValue(std::cout, 1, result);
444 std::cout << ConsoleColorTag(Console_Normal) << "\n";
446 std::cout << JsonEncode(result) << "\n";
449 } catch (const ScriptError& ex) {
450 if (ex.IsIncompleteExpression() && commandOnce.IsEmpty()) {
455 DebugInfo di = ex.GetDebugInfo();
457 if (commandOnceFileName.IsEmpty() && lines.find(di.Path) != lines.end()) {
458 String text = lines[di.Path];
460 std::vector<String> ulines = text.Split("\n");
462 for (decltype(ulines.size()) i = 1; i <= ulines.size(); i++) {
465 if (i == (decltype(i))di.FirstLine)
466 start = di.FirstColumn;
470 if (i == (decltype(i))di.LastLine)
471 len = di.LastColumn - di.FirstColumn + 1;
473 len = ulines[i - 1].GetLength();
477 if (di.Path != fileName) {
478 std::cout << di.Path << ": " << ulines[i - 1] << "\n";
483 if (i >= (decltype(i))di.FirstLine && i <= (decltype(i))di.LastLine) {
484 std::cout << String(di.Path.GetLength() + offset, ' ');
485 std::cout << String(start, ' ') << String(len, '^') << "\n";
489 ShowCodeLocation(std::cout, di);
492 std::cout << ex.what() << "\n";
494 if (!commandOnce.IsEmpty())
496 } catch (const std::exception& ex) {
497 std::cout << "Error: " << DiagnosticInformation(ex) << "\n";
499 if (!commandOnce.IsEmpty())
507 void ConsoleCommand::ExecuteScriptCompletionHandler(boost::mutex& mutex, boost::condition_variable& cv,
508 bool& ready, const boost::exception_ptr& eptr, const Value& result, Value& resultOut, boost::exception_ptr& eptrOut)
512 boost::rethrow_exception(eptr);
513 } catch (const ScriptError&) {
514 eptrOut = boost::current_exception();
515 } catch (const std::exception& ex) {
516 Log(LogCritical, "ConsoleCommand")
517 << "HTTP query failed: " << ex.what();
520 /* Ensures that the terminal state is resetted */
521 rl_deprep_terminal();
522 #endif /* HAVE_EDITLINE */
524 Application::Exit(EXIT_FAILURE);
531 boost::mutex::scoped_lock lock(mutex);
537 void ConsoleCommand::AutocompleteScriptCompletionHandler(boost::mutex& mutex, boost::condition_variable& cv,
538 bool& ready, const boost::exception_ptr& eptr, const Array::Ptr& result, Array::Ptr& resultOut)
542 boost::rethrow_exception(eptr);
543 } catch (const std::exception& ex) {
544 Log(LogCritical, "ConsoleCommand")
545 << "HTTP query failed: " << ex.what();
548 /* Ensures that the terminal state is resetted */
549 rl_deprep_terminal();
550 #endif /* HAVE_EDITLINE */
552 Application::Exit(EXIT_FAILURE);
559 boost::mutex::scoped_lock lock(mutex);