-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathts3.chart.py
More file actions
303 lines (237 loc) · 9.68 KB
/
ts3.chart.py
File metadata and controls
303 lines (237 loc) · 9.68 KB
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
#!/usr/bin/env python
"""
NetData plugin for active users on TeamSpeak 3 servers.
Please set user and password for your TeamSpeakQuery login in the 'ts3.conf'.
The MIT License (MIT)
Copyright (c) 2016-2017 Jan Arnold
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# @Title : ts3.chart
# @Description : NetData plugin for active users on TeamSpeak 3 servers
# @Author : Jan Arnold
# @Email : jan.arnold (at) coraxx.net
# @Copyright : Copyright (C) 2016-2017 Jan Arnold
# @License : MIT
# @Maintainer : Jan Arnold
# @Date : 2018/10/02
# @Version : 0.9
# @Status : stable
# @Usage : Automatically processed by netdata
# @Notes : With default NetData installation put this file under
# : /usr/libexec/netdata/python.d/ and the config file under
# : /etc/netdata/python.d/
# @Python_version : >3.6.2 or >2.7.3
"""
import os
import re
import select
from bases.FrameworkServices.SocketService import SocketService
# Basic plugin settings for netdata.
update_every = 1
priority = 60000
retries = 10
ORDER = ['users', 'bandwidth_total', 'bandwidth_filetransfer', 'packetloss']
CHARTS = {
'users': {
'options': [None, 'Users online', 'users', 'Users', 'ts3.connected_user', 'line'],
'lines': [
['connected_users', 'online', 'absolute']
]
},
'bandwidth_total': {
'options': [None, 'Bandwidth total', 'kb/s', 'Bandwidth', 'ts3.bandwidth_total', 'area'],
'lines': [
['bandwidth_total_received', 'received', 'absolute', 1, 1000],
['bandwidth_total_sent', 'sent', 'absolute', -1, 1000]
]
},
'bandwidth_filetransfer': {
'options': [None, 'Bandwidth filetransfer', 'kb/s', 'Bandwidth', 'ts3.bandwidth_filetransfer', 'area'],
'lines': [
['bandwidth_filetransfer_received', 'received', 'absolute', 1, 1000],
['bandwidth_filetransfer_sent', 'sent', 'absolute', -1, 1000]
]
},
'packetloss': {
'options': [None, 'Average data packet loss', 'packets loss %', 'Packet Loss', 'ts3.packetloss', 'line'],
'lines': [
['packetloss_speech', 'speech', 'absolute', 1, 1000],
['packetloss_keepalive', 'keepalive', 'absolute', 1, 1000],
['packetloss_control', 'control', 'absolute', 1, 1000],
['packetloss_total', 'total', 'absolute', 1, 1000],
]
}
}
class Service(SocketService):
def __init__(self, configuration=None, name=None):
SocketService.__init__(self, configuration=configuration, name=name)
# Default TeamSpeak Server connection settings.
self.host = "127.0.0.1"
self.port = "10011"
# Connection socket settings.
self.unix_socket = None
self._keep_alive = True
self.request = "serverinfo\n"
self.loggedIn = False
# Chart information handled by netdata.
self.order = ORDER
self.definitions = CHARTS
def check(self):
"""
Parse configuration and check if local Teamspeak server is running
:return: boolean
"""
self._parse_config()
try:
self.user = self.configuration['user']
if self.user == '':
raise KeyError
except KeyError:
self.error(
"Please specify a TeamSpeak Server query user inside the ts3.conf!", "Disabling plugin...")
return False
try:
self.passwd = self.configuration['pass']
if self.passwd == '':
raise KeyError
except KeyError:
self.error(
"Please specify a TeamSpeak Server query password inside the ts3.conf!", "Disabling plugin...")
return False
try:
self.sid = self.configuration['sid']
except KeyError:
self.sid = 1
self.debug("No sid specified. Using: '{0}'".format(self.sid))
# Check once if TS3 is running when host is localhost.
if self.host in ['localhost', '127.0.0.1']:
TS3_running = False
pids = [pid for pid in os.listdir('/proc') if pid.isdigit()]
for pid in pids:
try:
if b'ts3server' in open(os.path.join('/proc', pid, 'cmdline').encode(), 'rb').read():
TS3_running = True
break
except IOError as e:
self.error(e)
if TS3_running is False:
self.error("No local TeamSpeak server running. Disabling plugin...")
return False
else:
self.debug("TeamSpeak server process found. Connecting...")
return True
def _send(self, request=None):
"""
Send request.
:return: boolean
"""
# Send request if it is needed
if self.request != "".encode():
try:
if not self.loggedIn:
self._sock.send("login {0} {1}\n".format(self.user, self.passwd).encode())
self._receive()
self._sock.send("use sid={0}\n".format(self.sid).encode())
self._receive()
self.loggedIn = True
self._sock.send(self.request)
except Exception as e:
self.loggedIn = False
self._disconnect()
self.error(
str(e),
"used configuration: host:", str(self.host),
"port:", str(self.port),
"socket:", str(self.unix_socket)
)
return False
return True
def _receive(self, raw=False):
"""
Receive data from socket
:return: str
"""
data = ""
while True:
try:
ready_to_read, _, in_error = select.select([self._sock], [], [], 5)
except Exception as e:
self.debug("SELECT", str(e))
self._disconnect()
break
if len(ready_to_read) > 0:
buf = self._sock.recv(4096)
if len(buf) == 0 or buf is None: # handle server disconnect
break
self.debug(str(buf))
data += buf.decode("utf-8")
if self._check_raw_data(data):
break
else:
self.error("Socket timed out.")
self._disconnect()
break
return data
def _get_data(self):
"""
Format data received from socket
:return: dict
"""
data = {}
try:
raw = self._get_raw_data()
except (ValueError, AttributeError):
self.error("No data received.")
return None
reg = re.compile(
"virtualserver_clientsonline=(\d*)|" +
"virtualserver_queryclientsonline=(\d*)|" +
"connection_bandwidth_sent_last_second_total=(\d*)|" +
"connection_bandwidth_received_last_second_total=(\d*)|" +
"connection_filetransfer_bandwidth_sent=(\d*)|" +
"connection_filetransfer_bandwidth_received=(\d*)|" +
"virtualserver_total_packetloss_speech=(\d+\.\d+)|" +
"virtualserver_total_packetloss_keepalive=(\d+\.\d+)|" +
"virtualserver_total_packetloss_control=(\d+\.\d+)|" +
"virtualserver_total_packetloss_total=(\d+\.\d+)"
)
regex = reg.findall(raw)
self.debug(str(regex))
if regex == []:
self.error("Information could not be extracted")
return None
try:
# Clients and query clients connected.
connected_users = int(regex[0][0]) - int(regex[1][1])
data["connected_users"] = connected_users
# Bandwidth info from server in bytes/s.
data["bandwidth_total_sent"] = int(regex[8][2])
data["bandwidth_total_received"] = int(regex[9][3])
data["bandwidth_filetransfer_sent"] = int(regex[6][4])
data["bandwidth_filetransfer_received"] = int(regex[7][5])
# The average packet loss.
data["packetloss_speech"] = float(regex[2][6]) * 100000
data["packetloss_keepalive"] = float(regex[3][7]) * 100000
data["packetloss_control"] = float(regex[4][8]) * 100000
data["packetloss_total"] = float(regex[5][9]) * 100000
except Exception as e:
self.error(str(e))
return None
return data
def _check_raw_data(self, data):
if data.endswith("msg=ok\n\r"):
return True
else:
return False