1 /* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */
3 #include "cli/objectlistcommand.hpp"
4 #include "cli/objectlistutility.hpp"
5 #include "base/logger.hpp"
6 #include "base/application.hpp"
7 #include "base/convert.hpp"
8 #include "base/configobject.hpp"
9 #include "base/configtype.hpp"
10 #include "base/json.hpp"
11 #include "base/netstring.hpp"
12 #include "base/stdiostream.hpp"
13 #include "base/debug.hpp"
14 #include "base/objectlock.hpp"
15 #include "base/console.hpp"
16 #include <boost/algorithm/string/join.hpp>
17 #include <boost/algorithm/string/replace.hpp>
22 using namespace icinga;
23 namespace po = boost::program_options;
25 REGISTER_CLICOMMAND("object/list", ObjectListCommand);
27 String ObjectListCommand::GetDescription() const
29 return "Lists all Icinga 2 objects.";
32 String ObjectListCommand::GetShortDescription() const
34 return "lists all objects";
37 void ObjectListCommand::InitParameters(boost::program_options::options_description& visibleDesc,
38 boost::program_options::options_description& hiddenDesc) const
40 visibleDesc.add_options()
41 ("count,c", "display object counts by types")
42 ("name,n", po::value<std::string>(), "filter by name matches")
43 ("type,t", po::value<std::string>(), "filter by type matches");
47 * The entry point for the "object list" CLI command.
49 * @returns An exit status.
51 int ObjectListCommand::Run(const boost::program_options::variables_map& vm, const std::vector<std::string>& ap) const
53 String objectfile = Configuration::ObjectsPath;
55 if (!Utility::PathExists(objectfile)) {
56 Log(LogCritical, "cli")
57 << "Cannot open objects file '" << Configuration::ObjectsPath << "'.";
58 Log(LogCritical, "cli", "Run 'icinga2 daemon -C' to validate config and generate the cache file.");
63 fp.open(objectfile.CStr(), std::ios_base::in);
65 StdioStream::Ptr sfp = new StdioStream(&fp, false);
66 unsigned long objects_count = 0;
67 std::map<String, int> type_count;
69 String name_filter, type_filter;
72 name_filter = vm["name"].as<std::string>();
74 type_filter = vm["type"].as<std::string>();
79 StreamReadContext src;
81 StreamReadStatus srs = NetString::ReadStringFromStream(sfp, &message, src);
86 if (srs != StatusNewItem)
89 ObjectListUtility::PrintObject(std::cout, first, message, type_count, name_filter, type_filter);
96 if (vm.count("count")) {
100 PrintTypeCounts(std::cout, type_count);
104 Log(LogNotice, "cli")
105 << "Parsed " << objects_count << " objects.";
110 void ObjectListCommand::PrintTypeCounts(std::ostream& fp, const std::map<String, int>& type_count)
112 typedef std::map<String, int>::value_type TypeCount;
114 for (const TypeCount& kv : type_count) {
115 fp << "Found " << kv.second << " " << kv.first << " object";