aboutsummaryrefslogtreecommitdiffstats
path: root/ejabberdrpc.py
blob: 7de19e686cfafb0440413e86e03c21090b740cf0 (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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import ipaddress
import re

from packaging import version

# rfc6052: IPv6 Addressing of IPv4/IPv6 Translators
nat64 = ipaddress.ip_network("64:ff9b::/96")


class EjabberdMetrics:
    """
    class to fetch metrics per xmlrpc
    """
    def __init__(self, url, login=None, api="rpc", muc_host: str = 'conference'):
        self._login = login
        self.muc_host = muc_host
        if api == "rpc":
            self.url = url
            self._cmd = self._rpc
        else:
            import requests

            self._url = url
            self.session = requests.Session()
            self._cmd = self._rest

    @property
    def _auth(self):
        if self._login is not None:
            return f"{self._login['user']}@{self._login['server']}", self._login['password']
        return None

    @property
    def _verstring(self):
        if self._login is not None:
            ver_str = re.compile('([1-9][0-9.-]*)')
            status = self._cmd('status', {})

            # matches
            tmp = ver_str.findall(status)[0]

            # return parsed version string
            return version.parse(tmp)

        return None

    def _rest(self, command: str, data) -> dict:
        # add authentication header to the session obj
        if self.session.auth is None:
            self.session.auth = self._auth

        # post
        r = self.session.post('/'.join([self._url, command]), json=data)

        # proceed if response is ok
        if r.ok:
            return r.json()

        return {}

    def _rpc(self, command: str, data):
        from xmlrpc import client

        with client.ServerProxy(self.url) as server:
            fn = getattr(server, command)
            try:
                if self._login is not None:
                    return fn(self._login, data)
                return fn(data)
            except:
                return {}

    def _client(self, resource):
        clientmap = {
            "Conv6ations for Sum7": ["Conversations with IPv6"],
            "Conversations": [],
            "Pix-Art Messenger": [],
            "Gajim": ["gajim"],
            "Psi+": [],
            "jitsi": [],
            "Dino": ["dino"],
            "poezio": [],
            "profanity": [],
            "Xabber": [],
            "ChatSecure": ["chatsecure"]
        }

        for client, names in clientmap.items():
            for c in names:
                if c in resource:
                    return client
            if client in resource:
                return client
        return "other"

    @staticmethod
    def _ipversion(ip):
        addr = ipaddress.ip_address(ip)
        if addr.version == 6:
            if addr.ipv4_mapped:
                return 4
            if addr in nat64:
                return 4
        return addr.version

    def fetch_onlineuser(self):
        tmp = self._cmd("connected_users_info", {})
        if "connected_users_info" not in tmp:
            return tmp
        data = []
        for c in tmp["connected_users_info"]:
            if "session" not in c:
                continue
            user = {}
            for attrs in c["session"]:
                for k, v in attrs.items():
                    user[k] = v
            data.append(user)
        return data

    def fetch_nodes(self):
        result = self._cmd("list_cluster", {})
        if "nodes" not in result:
            return result
        data = []
        for node in result["nodes"]:
            data.append(node["node"])
        return data

    def fetch_vhosts(self):
        result = self._cmd("registered_vhosts", {})
        if "vhosts" not in result:
            return result
        data = []
        for vhost in result["vhosts"]:
            data.append(vhost["vhost"])
        return data

    def fetch_s2s_in(self):
        result = self._cmd("incoming_s2s_number", {})
        if "s2s_incoming" not in result:
            return result
        return result["s2s_incoming"]

    def fetch_s2s_out(self):
        result = self._cmd("outgoing_s2s_number", {})
        if "s2s_outgoing" not in result:
            return result
        return result["s2s_outgoing"]

    def fetch_registered(self, vhost=None):
        if vhost is None:
            result = self._cmd("stats", {"name":"registeredusers"})
            if "stat" in result:
                return result["stat"]
        else:
            result = self._cmd("stats_host", {"name":"registeredusers", "host": vhost})
            if "stat" in result:
                return result["stat"]

    def fetch_muc(self, vhost=None):
        host = "global"
        if vhost is not None:
            if self._verstring.major >= 19:
                host = '.'.join([self.muc_host, vhost])
            else:
                host = vhost
        result = self._cmd("muc_online_rooms", {"host": host})
        if "rooms" in result:
            return len(result["rooms"])
        return len(result)

    def update(self):
        # nodes
        self._nodes = self.fetch_nodes()

        # vhosts
        self._vhosts = self.fetch_vhosts()

        # registered
        if not hasattr(self, "_registered"):
            self._registered = {}
        self._registered[None] = self.fetch_registered()

        # muc
        if not hasattr(self, "_muc"):
            self._muc = {}
        self._muc[None] = self.fetch_muc()

        # registered + muc
        for vhost in self._vhosts:
            self._registered[vhost] = self.fetch_registered(vhost)
            self._muc[vhost] = self.fetch_muc(vhost)

        # online user
        self._onlineuser = self.fetch_onlineuser()

        # s2s
        self._s2s_in = self.fetch_s2s_in()
        self._s2s_out = self.fetch_s2s_out()

    def get_online_by(self, by="node", parse=None, vhost=None, node=None):
        parser = parse or (lambda a: a)
        if not hasattr(self, "_onlineuser"):
            self._onlineuser = self.fetch_onlineuser()
        data = {}

        for conn in self._onlineuser:
            if vhost is not None and vhost not in conn["jid"]:
                continue
            if node is not None and node != conn["node"]:
                continue
            if by not in conn:
                continue
            value = parser(conn[by])
            if value not in data:
                data[value] = 1
            else:
                data[value] += 1
        return data

    def get_online_by_node(self, vhost=None):
        return self.get_online_by("node", vhost=vhost)

    def get_online_by_vhost(self, node=None):
        return self.get_online_by("jid", parse=lambda jid: jid[jid.find("@")+1:jid.find("/")], node=node)

    def get_online_by_status(self, vhost=None, node=None):
        return self.get_online_by("status", vhost=vhost, node=node)

    def get_online_by_connection(self, vhost=None, node=None):
        return self.get_online_by("connection", vhost=vhost, node=node)

    def get_online_by_client(self, vhost=None, node=None):
        return self.get_online_by("resource", parse=self._client, vhost=vhost, node=node)

    def get_online_by_ipversion(self, vhost=None, node=None):
        return self.get_online_by("ip", parse=self._ipversion, vhost=vhost, node=node)

    def get_online_client_by(self, by="ip", parse=None, vhost=None, node=None):
        parser = parse or self._ipversion
        if not hasattr(self, "_onlineuser"):
            self._onlineuser = self.fetch_onlineuser()
        data = {}

        for conn in self._onlineuser:
            client = "other"
            if "resource" in conn:
                client = self._client(conn["resource"])
            if client not in data:
                data[client] = {}
            if vhost is not None and vhost not in conn["jid"]:
                continue
            if node is not None and node != conn["node"]:
                continue
            if by not in conn:
                continue
            value = parser(conn[by])
            if value not in data[client]:
                data[client][value] = 1
            else:
                data[client][value] += 1
        return data

    def get_online_client_by_ipversion(self, vhost=None, node=None):
        return self.get_online_client_by("ip", parse=self._ipversion, vhost=vhost, node=node)

    def get_registered(self, vhost=None):
        if not hasattr(self, "_registered"):
            self._registered = {}
        if vhost not in self._registered:
            self._registered[vhost] = self.fetch_registered(vhost)
        return self._registered[vhost]

    def get_muc(self, vhost=None):
        if not hasattr(self, "_muc"):
            self._muc = {}
        if vhost not in self._muc:
            self._muc[vhost] = self.fetch_muc(vhost)
        return self._muc[vhost]

    def get_vhosts(self):
        if not hasattr(self, "_vhosts"):
            self._vhosts = self.fetch_vhosts()
        return self._vhosts

    def get_s2s_in(self):
        if not hasattr(self, "_s2s_in"):
            self._s2s_in = self.fetch_s2s_in()
        return self._s2s_in

    def get_s2s_out(self):
        if not hasattr(self, "_s2s_out"):
            self._s2s_out = self.fetch_s2s_out()
        return self._s2s_out

    def get_vhost_metrics(self, vhost): 
        data = {
            "registered": self.get_registered(vhost),
            "muc": self.get_muc(vhost),
            "online_by_status": self.get_online_by_status(vhost),
            "online_by_client": self.get_online_by_client(vhost),
            "online_by_ipversion": self.get_online_by_ipversion(vhost),
            "online_by_connection": self.get_online_by_connection(vhost),
            "online_by_node": self.get_online_by_node(vhost)
        }

        return data

    def get_nodes(self):
        if not hasattr(self, "_nodes"):
            self._nodes = self.fetch_nodes()
        return self._nodes

    def get_node_metrics(self, node): 
        data = {
            "online_by_status": self.get_online_by_status(node=node),
            "online_by_client": self.get_online_by_client(node=node),
            "online_by_ipversion": self.get_online_by_ipversion(node=node),
            "online_by_connection": self.get_online_by_connection(node=node),
            "online_by_vhost": self.get_online_by_vhost(node=node)
        }

        return data

    def get_all(self):
        data = {
            "registered": self.get_registered(),
            "muc": self.get_muc(),
            "online_by_status": self.get_online_by_status(),
            "online_by_client": self.get_online_by_client(),
            "online_by_ipversion": self.get_online_by_ipversion(),
            "online_by_connection": self.get_online_by_connection(),
            "online_by_node": self.get_online_by_node(),
            "online_by_vhost": self.get_online_by_vhost()
        }

        vhosts = {}
        for host in self.get_vhosts():
            vhosts[host] = self.get_vhost_metrics(host)
        data["vhosts"] = vhosts
        
        nodes = {}
        for node in self.get_nodes():
            nodes[node] = self.get_node_metrics(node)

        data["online_client_by_ipversion"] = self.get_online_client_by_ipversion()
        data["nodes"] = nodes
        
        data["s2s_in"] = self.get_s2s_in()
        data["s2s_out"] = self.get_s2s_out()
        return data


if __name__ == "__main__":
    import os
    import json

    # load config
    path = os.path.dirname(__file__)
    with open("/".join([path, "config.json"]), "r", encoding="utf-8") as f:
        config = json.load(f)

    url = config['url'] if "url" in config else "http://[::1]:5280/api"
    login = config['login'] if "login" in config else None
    api = config['api'] if "api" in config else "rest"

    metric = EjabberdMetrics(url, login=login, api=api)
   
    data = metric.get_all()
    print(json.dumps(data, indent=True))