dbaf9c3e3448736f8e60f064fb8ec7b0f98d4ffb
[collectd.git] / src / tss2.c
1 /**
2  * collectd - src/tss2.c
3  * Copyright (C) 2008  Stefan Hacker
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License as published by the
7  * Free Software Foundation; only version 2 of the License is applicable.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License along
15  * with this program; if not, write to the Free Software Foundation, Inc.,
16  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
17  *
18  * Authors:
19  *   Stefan Hacker <d0t at dbclan dot de>
20  **/
21
22
23 /*
24  * Defines
25  */
26  
27 /* Teamspeak query protocol defines */
28 #define TELNET_BANNER   "[TS]\r\n"
29 #define TELNET_BANNER_LENGTH 5
30 #define TELNET_ERROR   "ERROR"
31 #define TELNET_OK          "OK"
32 #define TELNET_QUIT        "quit\r\n"
33
34 /* Predefined settings */
35 #define TELNET_BUFFSIZE 512
36 #define DEFAULT_HOST    "127.0.0.1"
37 #define DEFAULT_PORT    51234
38
39 /* VServer request defines */
40 #define S_REQUEST          "si\r\n"
41 #define S_USERS_ONLINE "server_currentusers="
42 #define S_PACKETS_SEND "server_packetssend="
43 #define S_PACKETS_REC  "server_packetsreceived="
44 #define S_BYTES_SEND   "server_bytessend="
45 #define S_BYTES_REC        "server_bytesreceived="
46
47 /* Global request defines */
48 #define T_REQUEST          "gi\r\n"
49 #define T_USERS_ONLINE "total_users_online="
50 #define T_PACKETS_SEND "total_packetssend="
51 #define T_PACKETS_REC  "total_packetsreceived="
52 #define T_BYTES_SEND   "total_bytessend="
53 #define T_BYTES_REC        "total_bytesreceived="
54
55 /* Convinience defines */
56 #define SOCKET                  int
57 #define INVALID_SOCKET 0
58
59
60 /*
61  * Includes
62  */
63  
64 #include "collectd.h"
65 #include "common.h"
66 #include "plugin.h"
67
68 #include <stdio.h>
69 #include <arpa/inet.h>
70 #include <netinet/in.h>
71 #include <sys/socket.h>
72 #include <sys/select.h>
73 #include <sys/types.h>
74 #include <unistd.h>
75 #include <stdlib.h>
76
77 /*
78  * Variables
79  */
80  
81 /* Server linked list structure */
82 typedef struct server_s {
83         int port;
84         struct server_s *next;
85 } server_t;
86 static server_t *pserver = NULL;
87
88
89 /* Host data */
90 static char *host               = DEFAULT_HOST;
91 static int   port               = DEFAULT_PORT;
92
93 static SOCKET telnet    = INVALID_SOCKET;
94 static FILE *telnet_in  = NULL;
95
96
97 /* Config data */
98 static const char *config_keys[] =
99 {
100     "Host",
101         "Port",
102     "Server",
103     NULL
104 };
105 static int config_keys_num = 3;
106
107
108 /*
109  * Functions
110  */
111
112 static void add_server(server_t *new_server)
113 {
114         /*
115          * Adds a new server to the linked list 
116          */
117         server_t *tmp    = NULL;
118         new_server->next = NULL;
119
120         if(pserver == NULL) {
121                 /* Add the server as the first element */
122                 pserver = new_server;
123         }
124         else {
125                 /* Add the server to the end of the list */
126                 tmp = pserver;
127                 while(tmp->next != NULL) {
128                         tmp = tmp->next;
129                 }
130                 tmp->next = new_server;
131         }
132
133         DEBUG("Registered new server '%d'", new_server->port); 
134 } /* void add_server */
135
136
137 static int do_connect(void)
138 {
139         /*
140          * Tries to establish a connection to the server
141          */
142         struct sockaddr_in addr;
143         
144         /* Establish telnet connection */
145         telnet = socket(AF_INET, SOCK_STREAM, 0);
146         
147         addr.sin_family                 = AF_INET;
148         addr.sin_addr.s_addr    = inet_addr(host);
149         addr.sin_port                   = htons(port);
150
151         if(connect(telnet, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
152                 /* Connection failed */
153                 return -1;
154         }
155         return 0;
156 } /* int do_connect */
157
158
159 static int do_request(char *request)
160 {
161         /*
162          * Pushes a request
163          */
164         int ret = 0;
165         DEBUG("Send Request: '%s'", request);
166         
167         /* Send the request */
168         if((ret = send(telnet, request, strlen(request), 0))==-1) {
169                 /* Send data failed */
170                 if (telnet!=INVALID_SOCKET) {
171                         close(telnet);
172                         telnet = INVALID_SOCKET;
173                 }
174                 char errbuf[1024];
175                 ERROR("tss2 plugin: send data to host '%s' failed: %s",
176                                 host,
177                                 sstrerror(errno, errbuf,
178                                                   sizeof(errbuf)));
179                 return -1;
180         }
181         return ret;
182 } /* int do_request */
183
184
185 static int do_recv(char *buffer, int buffer_size, long int usecs)
186 {
187         /*
188          * Tries to receive from the connection 'timeout' seconds
189          */
190         int        ret = 0;
191         fd_set rset;
192         struct timeval timeout;
193
194         timeout.tv_sec     = 0;
195         timeout.tv_usec    = usecs;
196
197         FD_ZERO(&rset);
198         FD_SET(telnet, &rset);
199
200         if (select(FD_SETSIZE, &rset, NULL, NULL, &timeout) == -1) {
201                 /* Select failed */
202                 if (telnet!=INVALID_SOCKET) {
203                         close(telnet);
204                         telnet = INVALID_SOCKET;
205                 }
206                 
207                 char errbuf[1024];
208                 ERROR("tss2 plugin: select failed: %s",
209                                 sstrerror(errno, errbuf,
210                                 sizeof(errbuf)));
211                 return -1;
212         }
213         if (!FD_ISSET(telnet, &rset)) {
214                 /* Timeout for answer reached --> disconnect */
215                 if (telnet!=INVALID_SOCKET) {
216                         close(telnet);
217                         telnet = INVALID_SOCKET;
218                 }
219                 WARNING("tss2 plugin: request timed out (closed connection)");
220                 return -1;
221         }
222         if ((ret = recv(telnet, buffer, buffer_size, 0)) == -1) {
223                 /* Recv failed */
224                 if (telnet!=INVALID_SOCKET) {
225                         close(telnet);
226                         telnet = INVALID_SOCKET;
227                 }
228                 
229                 char errbuf[1024];
230                 ERROR("tss2 plugin: recv failed: %s",
231                           sstrerror(errno, errbuf,
232                           sizeof(errbuf)));
233                 return -1;
234         }
235         return ret;
236 } /* int do_recv */
237
238
239 static int is_eq(char *eq, char *str) {
240         /*
241          * Checks if the given str starts with eq
242         */
243         if (strlen(eq) > strlen(str)) return -1;
244         return strncmp(eq, str, strlen(eq));
245 }
246
247
248 static long int eval_eq(char *eq, char *str) {
249         /*
250          * Returns the value written behind the eq string in str as a long int
251          */
252         return strtol((char*)&str[strlen(eq)], NULL, 10);
253 }
254
255
256 static int do_recv_line(char *buffer, int buffer_size, long int usecs)
257 {
258         /*
259          * Receives a line from the socket
260          */
261          
262         /*
263          * fgets is blocking but much easier then doing anything else
264          * TODO: Non-blocking Version would be safer
265          */
266         if ((fgets(buffer, buffer_size, telnet_in)) == NULL) {
267                 /* Receive line failed */
268                 if (telnet != INVALID_SOCKET) {
269                         close(telnet);
270                         telnet = INVALID_SOCKET;
271                 }
272                 
273                 char errbuf[1024];
274                 ERROR("tss2 plugin: fgets failed: %s",
275                           sstrerror(errno, errbuf,
276                           sizeof(errbuf)));
277                 return -1;
278         }
279         DEBUG("Line: %s", buffer);
280         return 0;
281 }
282
283
284 static int tss2_config(const char *key, const char *value)
285 {
286         /*
287          * Configuration interpreter function
288          */
289         char *phost = NULL;
290         
291     if (strcasecmp(key, "host") == 0) {
292         /* Host variable found*/
293                 if ((phost = strdup(value)) == NULL) {
294                         char errbuf[1024];
295                         ERROR("tss2 plugin: strdup failed: %s",
296                                 sstrerror(errno, errbuf,
297                                                   sizeof(errbuf)));
298                         return 1;
299                 }
300                 host = (char*)phost;
301         }
302         else if (strcasecmp(key, "port") == 0) {
303                 /* Port variable found */
304                 port = atoi(value);
305         }
306         else if (strcasecmp(key, "server") == 0) {
307                 /* Server variable found */
308                 server_t *new_server = NULL;
309
310                 if ((new_server = (server_t *)malloc(sizeof(server_t))) == NULL) {
311                         char errbuf[1024];
312                         ERROR("tss2 plugin: malloc failed: %s",
313                                   sstrerror (errno, errbuf,
314                                   sizeof (errbuf)));
315                         return 1;
316                 }
317
318                 new_server->port = atoi(value);
319                 add_server((struct server_s*)new_server);
320         }
321         else {
322                 /* Unknow variable found */
323                 return 1;
324         }
325
326         return 0;
327 }
328
329
330 static int tss2_init(void)
331 {
332         /*
333          * Function to initialize the plugin
334          */
335         char buff[TELNET_BANNER_LENGTH + 1]; /*Prepare banner buffer*/
336         
337         /*Connect to telnet*/
338         DEBUG("tss2 plugin: Connecting to '%s:%d'", host, port);
339         if (do_connect()!=0) {
340                 /* Failed */
341                 char errbuf[1024];
342                 ERROR("tss2 plugin: connect to %s:%d failed: %s",
343                         host,
344                         port,
345                         sstrerror(errno, errbuf,
346                                           sizeof(errbuf)));
347                 return 1;
348         }
349         else {
350                 DEBUG("tss2 plugin: connection established!")
351         }
352         
353         /*Check if this is the real thing*/
354         if (do_recv(buff, sizeof(buff), 1) == -1) {
355                 /* Failed */
356                 return 1;
357         }
358         DEBUG("tss2 plugin: received banner '%s'", buff);
359         
360         if (strcmp(buff, TELNET_BANNER)!=0) {
361                 /* Received unexpected banner string */
362                 ERROR("tss2 plugin: host %s:%d is no teamspeak2 query port",
363                         host, port);
364                 return 1;
365         }
366         
367         /*Alright, we are connected now get a file descriptor*/
368         if ((telnet_in = fdopen(telnet, "r")) == NULL) {
369                 /* Failed */
370                 char errbuf[1024];
371                 ERROR("tss2 plugin: fdopen failed",
372                                 sstrerror(errno, errbuf,
373                                 sizeof(errbuf)));
374                 return 1;
375         }
376         DEBUG("tss2 plugin: Connection established", host, port);
377     return 0;
378 } /* int tss2_init */
379
380
381 static void tss2_submit (gauge_t users,
382                                            counter_t bytes_send, counter_t bytes_received,
383                                            counter_t packets_send, counter_t packets_received,
384                                            char *server)
385 {
386         /*
387          * Function to submit values to collectd
388          */
389         value_t v_users[1];
390         value_t v_octets[2];
391         value_t v_packets[2];
392         
393         value_list_t vl_users   = VALUE_LIST_INIT;
394         value_list_t vl_octets  = VALUE_LIST_INIT;
395         value_list_t vl_packets = VALUE_LIST_INIT;
396         
397         /* 
398          * Dispatch users gauge
399          */
400         v_users[0].gauge    = users;
401         
402         vl_users.values     = v_users;
403         vl_users.values_len = STATIC_ARRAY_SIZE (v_users);
404         vl_users.time       = time (NULL);
405
406         
407         strcpy(vl_users.host, hostname_g);
408         strcpy(vl_users.plugin, "tss2");
409         
410         if (server != NULL) {
411                 /* VServer values */
412                 strcpy(vl_users.plugin_instance, "");
413                 strncpy(vl_users.type_instance, server, sizeof(vl_users.type_instance));
414         }
415         
416         plugin_dispatch_values ("users", &vl_users);
417         
418         /* 
419          * Dispatch octets counter
420          */
421         v_octets[0].counter  = bytes_send;
422         v_octets[1].counter  = bytes_received;
423         
424         vl_octets.values     = v_octets;
425         vl_octets.values_len = STATIC_ARRAY_SIZE (v_octets);
426         vl_octets.time       = time (NULL);
427
428         strcpy(vl_octets.host, hostname_g);
429         strcpy(vl_octets.plugin, "tss2");
430         
431         if (server != NULL) {
432                 /* VServer values */
433                 strcpy(vl_octets.plugin_instance, "");
434                 strncpy(vl_octets.type_instance, server, sizeof(vl_octets.type_instance));
435         }
436         
437         plugin_dispatch_values ("octets", &vl_octets);
438
439         /* 
440          * Dispatch packets counter
441          */
442         v_packets[0].counter  = packets_send;
443         v_packets[1].counter  = packets_send;
444         
445         vl_packets.values     = v_packets;
446         vl_packets.values_len = STATIC_ARRAY_SIZE (v_packets);
447         vl_packets.time       = time (NULL);
448         
449         strcpy(vl_packets.host, hostname_g);
450         strcpy(vl_packets.plugin, "tss2");
451         
452         if (server != NULL) {
453                 /* VServer values */
454                 strcpy(vl_packets.plugin_instance, "");
455                 strncpy(vl_packets.type_instance, server, sizeof(vl_packets.type_instance));
456         }
457         
458         plugin_dispatch_values("packets", &vl_packets);
459 } /* void tss2_submit */
460
461
462 static int tss2_read(void)
463 {
464         /*
465          * Tries to read the current values from all servers and to submit them
466          */
467         char buff[TELNET_BUFFSIZE];
468         server_t *tmp;
469     
470         /* Variables for received values */
471         int collected                       = 0;
472         int users_online                        = 0;
473         
474         long int bytes_received         = 0;
475         long int bytes_send                     = 0;
476         long int packets_received       = 0;
477         long int packets_send           = 0;
478         
479         /*Check if we are connected*/
480         if ((telnet == INVALID_SOCKET) && (do_connect() != 0)) {
481                 /* Disconnected and reconnect failed */
482                 char errbuf[1024];
483                 ERROR("tss2 plugin: reconnect to %s:%d failed: %s",
484                         host,
485                         port,
486                         sstrerror(errno, errbuf,
487                                           sizeof(errbuf)));
488                 return -1;
489         }
490         
491         /* Request global server variables */
492         if (do_request(T_REQUEST) == -1) {
493                 /* Collect global info failed */
494                 ERROR("tss2 plugin: Collect global information request failed");
495                 return -1;
496         }
497
498         collected = 0; /* Counts the number of variables found in the reply */
499         
500         for(;;) {
501                 /* Request a line with a timeout of 200ms */
502                 if (do_recv_line(buff, TELNET_BUFFSIZE, 200000) != 0) {
503                         /* Failed */
504                         ERROR("tss2 plugin: Collect global information failed");
505                         return -1;
506                 }
507                 
508                 /*
509                  * Collect the received data
510                  */
511                 if (is_eq(T_USERS_ONLINE, buff) == 0) {
512                         /* Number of users online */
513                         users_online = (int)eval_eq(T_USERS_ONLINE, buff);
514                         DEBUG("users_online: %d", users_online);
515                         collected += 1;
516                 }
517                 else if (is_eq(T_PACKETS_SEND, buff) == 0) {
518                         /* Number of packets send */
519                         packets_send = eval_eq(T_PACKETS_SEND, buff);
520                         DEBUG("packets_send: %ld", packets_send);
521                         collected += 1;
522                 }
523                 else if (is_eq(T_PACKETS_REC, buff) == 0) {
524                         /* Number of packets received */
525                         packets_received = eval_eq(T_PACKETS_REC, buff);
526                         DEBUG("packets_received: %ld", packets_received);
527                         collected += 1;
528                 }
529                 else if (is_eq(T_BYTES_SEND, buff) == 0) {
530                         /* Number of bytes send */
531                         bytes_send = eval_eq(T_BYTES_SEND, buff);
532                         DEBUG("bytes_send: %ld", bytes_send);
533                         collected += 1;
534                 }
535                 else if (is_eq(T_BYTES_REC, buff) == 0) {
536                         /* Number of bytes received */
537                         bytes_received = eval_eq(T_BYTES_REC, buff);
538                         DEBUG("byte_received: %ld", bytes_received);
539                         collected += 1;
540                 }
541                 else if (is_eq(TELNET_OK, buff) == 0) {
542                         /* Received end of transmission flag */
543                         if (collected < 5) {
544                                 /* Not all expected values were received */
545                                 ERROR("tss2 plugin: Couldn't collect all values (%d)", collected);
546                                 return -1;
547                         }
548                         /*
549                          * Everything is fine, let's break out of the loop
550                          */
551                         break;
552                 }
553                 else if (is_eq(TELNET_ERROR, buff) == 0) {
554                         /* An error occured on the servers' side */
555                         ERROR("tss2 plugin: host reported error '%s'", buff);
556                         return -1;
557                 }
558         }
559         
560         /* Forward values to collectd */
561         DEBUG("Full global dataset received");
562         tss2_submit(users_online, bytes_send, bytes_received, packets_send, packets_received, NULL);
563
564         /* Collect values of servers */
565         tmp = pserver;
566         while(tmp != NULL) {
567                 /* Try to select server */
568                 sprintf(buff, "sel %d\r\n", tmp->port);
569                 
570                 if (do_request(buff) == -1) return -1; /* Send the request */
571                 if (do_recv_line(buff, TELNET_BUFFSIZE, 200000)!=0) return -1; /* Receive the first line */
572                 
573                 if (is_eq(buff,TELNET_ERROR) == 0) {
574                         /*Could not select server, go to the next one*/
575                         WARNING("tss2 plugin: Could not select server '%d'", tmp->port);
576                         tmp = tmp->next;
577                         continue;
578                 }
579                 else if (is_eq(TELNET_OK, buff) == 0) {
580                         /*
581                          * VServer selected, now request its information
582                          */
583                         collected = 0; /* Counts the number of variables found in the reply */
584                         
585                         if (do_request(S_REQUEST) == -1) {
586                                 /* Failed */
587                                 WARNING("tss2 plugin: Collect info about server '%d' failed", tmp->port);
588                                 tmp = tmp->next;
589                                 continue;
590                         }
591
592                         for(;;) {
593                                 /* Request a line with a timeout of 200ms */
594                                 if (do_recv_line(buff, TELNET_BUFFSIZE, 200000) !=0 ) {
595                                         ERROR("tss2 plugin: Connection error");
596                                         return -1;
597                                 }
598                                 
599                                 /*
600                                  * Collect the received data
601                                  */
602                                 if (is_eq(S_USERS_ONLINE, buff) == 0) {
603                                         /* Number of users online */
604                                         users_online = (int)eval_eq(S_USERS_ONLINE, buff);
605                                         collected += 1;
606                                 }
607                                 else if (is_eq(S_PACKETS_SEND, buff) == 0) {
608                                         /* Number of packets send */
609                                         packets_send = eval_eq(S_PACKETS_SEND, buff);
610                                         collected += 1;
611                                 }
612                                 else if (is_eq(S_PACKETS_REC, buff) == 0) {
613                                         /* Number of packets received */
614                                         packets_received = eval_eq(S_PACKETS_REC, buff);
615                                         collected += 1;
616                                 }
617                                 else if (is_eq(S_BYTES_SEND, buff) == 0) {
618                                         /* Number of bytes send */
619                                         bytes_send = eval_eq(S_BYTES_SEND, buff);
620                                         collected += 1;
621                                 }
622                                 else if (is_eq(S_BYTES_REC, buff) == 0) {
623                                         /* Number of bytes received */
624                                         bytes_received = eval_eq(S_BYTES_REC, buff);
625                                         collected += 1;
626                                 }
627                                 else if (is_eq(TELNET_OK, buff) == 0) {
628                                         /*
629                                          * Received end of transmission flag, break the loop
630                                          */
631                                         break;
632                                 }
633                                 else if (is_eq(TELNET_ERROR, buff) == 0) {
634                                         /* Error, not good */
635                                         ERROR("tss2 plugin: server '%d' reported error '%s'", tmp->port, buff);
636                                         return -1;
637                                 }
638                         }
639                         
640                         if (collected < 5) {
641                                 /* Not all expected values were received */
642                                 ERROR("tss2 plugin: Couldn't collect all values of server '%d' (%d)", tmp->port, collected);
643                                 tmp = tmp->next;
644                                 continue; /* Continue with the next VServer */
645                         }
646                         
647                         /* Forward values to connectd */
648                         sprintf(buff,"%d",tmp->port);
649                         tss2_submit(users_online, bytes_send, bytes_received, packets_send, packets_received, buff);
650
651                 }
652                 else {
653                         /*The server send us garbage? wtf???*/
654                         ERROR("tss2 plugin: Server send garbage");
655                         return -1;
656                 }
657                 tmp = tmp->next;
658         }
659
660     return 0;
661 } /* int tss2_read */
662
663
664 static int tss2_shutdown(void)
665 {
666         /*
667          * Shutdown handler
668          */
669         DEBUG("tss2 plugin: Shutdown");
670         server_t *tmp = NULL;
671         
672         /* Close our telnet socket */
673         if (telnet != INVALID_SOCKET) {
674                 do_request(TELNET_QUIT);
675                 fclose(telnet_in);
676                 telnet_in = NULL;
677                 telnet = INVALID_SOCKET;
678         }
679         
680         /* Release all allocated memory */
681         while(pserver != NULL) {
682                 tmp     = pserver;
683                 pserver = pserver->next;
684                 free(tmp);
685         }
686         
687         /* Get rid of the rest */
688         if (host != DEFAULT_HOST) {
689                 free(host);
690                 host = (char*)DEFAULT_HOST;
691         }
692         
693     return 0;
694 } /* int tss2_shutdown */
695
696
697 void module_register(void)
698 {
699         /*
700          * Module registrator
701          */
702         plugin_register_config("tss2",
703                             tss2_config,
704                             config_keys,
705                             config_keys_num);
706
707         plugin_register_init("tss2", tss2_init);
708         plugin_register_read("tss2", tss2_read);
709         plugin_register_shutdown("tss2", tss2_shutdown);
710 } /* void module_register */