summaryrefslogtreecommitdiffstats
path: root/lib/remote/apiaction.hpp
blob: f2719c1bb1a65df652ebf5aef753e79f00b1a07f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */

#ifndef APIACTION_H
#define APIACTION_H

#include "remote/i2-remote.hpp"
#include "base/registry.hpp"
#include "base/value.hpp"
#include "base/dictionary.hpp"
#include "base/configobject.hpp"
#include <vector>
#include <boost/algorithm/string/replace.hpp>

namespace icinga
{

/**
 * An action available over the external HTTP API.
 *
 * @ingroup remote
 */
class ApiAction final : public Object
{
public:
	DECLARE_PTR_TYPEDEFS(ApiAction);

	typedef std::function<Value(const ConfigObject::Ptr& target, const Dictionary::Ptr& params)> Callback;

	ApiAction(std::vector<String> registerTypes, Callback function);

	Value Invoke(const ConfigObject::Ptr& target, const Dictionary::Ptr& params);

	const std::vector<String>& GetTypes() const;

	static ApiAction::Ptr GetByName(const String& name);
	static void Register(const String& name, const ApiAction::Ptr& action);
	static void Unregister(const String& name);

private:
	std::vector<String> m_Types;
	Callback m_Callback;
};

/**
 * A registry for API actions.
 *
 * @ingroup remote
 */
class ApiActionRegistry : public Registry<ApiActionRegistry, ApiAction::Ptr>
{
public:
	static ApiActionRegistry *GetInstance();
};

#define REGISTER_APIACTION(name, types, callback) \
	INITIALIZE_ONCE([]() { \
		String registerName = #name; \
		boost::algorithm::replace_all(registerName, "_", "-"); \
		std::vector<String> registerTypes; \
		String typeNames = types; \
		if (!typeNames.IsEmpty()) \
			registerTypes = typeNames.Split(";"); \
		ApiAction::Ptr action = new ApiAction(registerTypes, callback); \
		ApiActionRegistry::GetInstance()->Register(registerName, action); \
	})

}

#endif /* APIACTION_H */