Guest User

Untitled

a guest
Jun 16th, 2018
168
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.42 KB | None | 0 0
  1. import configparser
  2. import os
  3. import sys
  4. import argparse
  5. from influxdb import InfluxDBClient
  6. from influxdb.exceptions import InfluxDBClientError, InfluxDBServerError
  7. import speedtest
  8. import time
  9.  
  10. class configManager():
  11.  
  12. def __init__(self, config):
  13. print('Loading Configuration File {}'.format(config))
  14. self.test_server = []
  15. config_file = os.path.join(os.getcwd(), config)
  16. if os.path.isfile(config_file):
  17. self.config = configparser.ConfigParser()
  18. self.config.read(config_file)
  19. else:
  20. print('ERROR: Unable To Load Config File: {}'.format(config_file))
  21. sys.exit(1)
  22.  
  23. self._load_config_values()
  24. print('Configuration Successfully Loaded')
  25.  
  26. def _load_config_values(self):
  27.  
  28. # General
  29. self.delay = self.config['GENERAL'].getint('Delay', fallback=2)
  30. self.output = self.config['GENERAL'].getboolean('Output', fallback=True)
  31.  
  32. # InfluxDB
  33. self.influx_address = self.config['INFLUXDB']['Address']
  34. self.influx_port = self.config['INFLUXDB'].getint('Port', fallback=8086)
  35. self.influx_database = self.config['INFLUXDB'].get('Database', fallback='speedtests')
  36. self.influx_user = self.config['INFLUXDB'].get('Username', fallback='')
  37. self.influx_password = self.config['INFLUXDB'].get('Password', fallback='')
  38. self.influx_ssl = self.config['INFLUXDB'].getboolean('SSL', fallback=False)
  39. self.influx_verify_ssl = self.config['INFLUXDB'].getboolean('Verify_SSL', fallback=True)
  40.  
  41. # Speedtest
  42. test_server = self.config['SPEEDTEST'].get('Server', fallback=None)
  43. if test_server:
  44. self.test_server.append(test_server)
  45.  
  46.  
  47. class InfluxdbSpeedtest():
  48.  
  49. def __init__(self, config=None):
  50.  
  51. self.config = configManager(config=config)
  52. self.output = self.config.output
  53. self.influx_client = InfluxDBClient(
  54. self.config.influx_address,
  55. self.config.influx_port,
  56. username=self.config.influx_user,
  57. password=self.config.influx_password,
  58. database=self.config.influx_database,
  59. ssl=self.config.influx_ssl,
  60. verify_ssl=self.config.influx_verify_ssl
  61. )
  62.  
  63. self.speedtest = None
  64. self.results = None
  65. self.setup_speedtest()
  66.  
  67. def setup_speedtest(self):
  68.  
  69. speedtest.build_user_agent()
  70.  
  71. print('Getting speedtest.net Configuration')
  72. try:
  73. self.speedtest = speedtest.Speedtest()
  74. except speedtest.ConfigRetrievalError:
  75. print('ERROR: Failed to get speedtest.net configuration. Aborting')
  76. sys.exit(1)
  77.  
  78. try:
  79. self.speedtest.get_servers(self.config.test_server)
  80. except speedtest.NoMatchedServers:
  81. print('ERROR: No matched servers: {}'.format(self.config.test_server[0]))
  82. sys.exit(1)
  83. except speedtest.ServersRetrievalError:
  84. print('ERROR: Cannot retrieve speedtest server list')
  85. sys.exit(1)
  86. except speedtest.InvalidServerIDType:
  87. print('{} is an invalid server type, must be int'.format(self.config.test_server[0]))
  88. sys.exit(1)
  89.  
  90. print('Picking the closest server')
  91. self.speedtest.get_best_server()
  92.  
  93. self.results = self.speedtest.results
  94.  
  95. def send_results(self):
  96.  
  97. result_dict = self.results.dict()
  98.  
  99. input_points = [
  100. {
  101. 'measurement': 'speed_test_results',
  102. 'fields': {
  103. 'download': result_dict['download'],
  104. 'upload': result_dict['upload'],
  105. 'ping': result_dict['server']['latency']
  106. },
  107. 'tags': {
  108. 'server': result_dict['server']['sponsor']
  109. }
  110. }
  111. ]
  112.  
  113. if self.output:
  114. print('Download: {}'.format(str(result_dict['download'])))
  115. print('Upload: {}'.format(str(result_dict['upload'])))
  116.  
  117. self.write_influx_data(input_points)
  118.  
  119. def run(self):
  120.  
  121. while True:
  122.  
  123. self.speedtest.download()
  124. self.speedtest.upload()
  125.  
  126. self.send_results()
  127.  
  128. time.sleep(self.config.delay)
  129.  
  130. def write_influx_data(self, json_data):
  131. """
  132. Writes the provided JSON to the database
  133. :param json_data:
  134. :return:
  135. """
  136. if self.output:
  137. print(json_data)
  138.  
  139. try:
  140. self.influx_client.write_points(json_data)
  141. except (InfluxDBClientError, ConnectionError, InfluxDBServerError) as e:
  142. if hasattr(e, 'code') and e.code == 404:
  143.  
  144. print('Database {} Does Not Exist. Attempting To Create'.format(self.config.influx_database))
  145.  
  146. # TODO Grab exception here
  147. self.influx_client.create_database(self.config.influx_database)
  148. self.influx_client.write_points(json_data)
  149.  
  150. return
  151.  
  152. print('ERROR: Failed To Write To InfluxDB')
  153. print(e)
  154.  
  155. if self.output:
  156. print('Written To Influx: {}'.format(json_data))
  157.  
  158.  
  159. def main():
  160.  
  161. parser = argparse.ArgumentParser(description="A tool to send Plex statistics to InfluxDB")
  162. parser.add_argument('--config', default='config.ini', dest='config', help='Specify a custom location for the config file')
  163. args = parser.parse_args()
  164. collector = InfluxdbSpeedtest(config=args.config)
  165. collector.run()
  166.  
  167.  
  168. if __name__ == '__main__':
  169. main()
Add Comment
Please, Sign In to add comment