示例#1
0
    def setup_speedtest(self, server=None):
        """
        Initializes the Speed Test client with the provided server
        :param server: Int
        :return: None
        """
        speedtest.build_user_agent()

        log.debug('Setting up SpeedTest.net client')

        if server is None:
            server = []
        else:
            server = server.split()  # Single server to list

        try:
            self.speedtest = speedtest.Speedtest()
        except speedtest.ConfigRetrievalError:
            log.critical(
                'Failed to get speedtest.net configuration.  Aborting')
            sys.exit(1)

        self.speedtest.get_servers(server)

        log.debug('Picking the closest server')

        self.speedtest.get_best_server()

        log.info('Selected Server %s in %s', self.speedtest.best['id'],
                 self.speedtest.best['name'])

        self.results = self.speedtest.results
    def write_influx_data(self, json_data):
        """
        Writes the provided JSON to the database
        :param json_data:
        :return: None
        """
        log.debug(json_data)

        try:
            if config.influx_version == 1:
                self.influx_client.write_points(json_data)
            else:
                write_api = self.influx_client.write_api(
                    write_options=SYNCHRONOUS)
                write_api.write(config.influx_bucket, config.influx_org,
                                json_data)
        except (InfluxDBClientError, ConnectionError,
                InfluxDBServerError) as e:
            if hasattr(e, 'code') and e.code == 404:
                log.error('Database %s Does Not Exist.  Attempting To Create',
                          config.influx_database)
                self.influx_client.create_database(config.influx_database)
                self.influx_client.write_points(json_data)
                return

            log.error('Failed To Write To InfluxDB')
            print(e)

        log.debug('Data written to InfluxDB')
示例#3
0
    def _get_influx_connection(self):
        """
        Create an InfluxDB connection and test to make sure it works.
        We test with the get all users command.  If the address is bad it fails
        with a 404.  If the user doesn't have permission it fails with 401
        :return:
        """

        influx = InfluxDBClient(config.influx_address,
                                config.influx_port,
                                database=config.influx_database,
                                ssl=config.influx_ssl,
                                verify_ssl=config.influx_verify_ssl,
                                username=config.influx_user,
                                password=config.influx_password,
                                timeout=5)
        try:
            log.debug(
                'Testing connection to InfluxDb using provided credentials')
            influx.get_list_users(
            )  # TODO - Find better way to test connection and permissions
            log.debug('Successful connection to InfluxDb')
        except (ConnectTimeout, InfluxDBClientError) as e:
            if isinstance(e, ConnectTimeout):
                log.critical(
                    'Unable to connect to InfluxDB at the provided address (%s)',
                    config.influx_address)
            elif e.code == 401:
                log.critical(
                    'Unable to connect to InfluxDB with provided credentials')

            sys.exit(1)

        return influx
    def __init__(self):

        # Setup configuration
        log.debug('Loading Configuration.')
        self.config_delay = int(os.getenv("DELAY", 300))

        # InfluxDB
        self.config_influx_address = os.getenv("INFLUXDB_HOST", "127.0.0.1")
        self.config_influx_port = os.getenv("INFLUXDB_PORT", 8086)
        self.config_influx_database = os.getenv("INFLUXDB_DATABASE",
                                                "speedtest")
        self.config_influx_measurement = os.getenv("INFLUXDB_MEASUREMENT",
                                                   "speedtest")
        self.config_influx_user = os.getenv("INFLUXDB_USR", "")
        self.config_influx_password = os.getenv("INFLUXDB_PWD", "")
        self.config_influx_ssl = os.getenv("INFLUXDB_SSL", False)
        self.config_influx_verify_ssl = os.getenv("INFLUXDB_VERIFYSSL", True)

        # Speedtest
        self.config_servers = []
        test_server = os.getenv("SPEEDTEST_SERVER", "")
        if test_server:
            self.config_servers = test_server.split(',')

        log.debug('Configuration Successfully Loaded')

        self.influx_client = self._get_influx_connection()
        self.speedtest = None
        self.results = None
    def send_to_ifttt(self, json_data):
        """
        Writes the provided JSON to ifttt
        :param json_data:
        :return: Non
        """
        try:
            post(
                f'https://maker.ifttt.com/trigger/speedtest/with/key/{config.ifttt_key}',
                json=json_data,
                timeout=5)
        except RequestException as e:
            log.error('Failed To Write To IFTTT')
            print(e)

        log.debug('Data written to IFTTT')
示例#6
0
    def setup_speedtest(self, servers=None, mode='select'):
        """
        Initializes the Speed Test client with the provided server
        :param server: Int
        :return: None
        """
        speedtest.build_user_agent()

        log.debug('Setting up Speedtest.net client')

        if servers:
            log.info(
                f"Selecting server {('excluding','from')[mode!='exclude']}: {servers}"
            )

        try:
            self.speedtest = speedtest.Speedtest(secure=config.secure)
        except speedtest.ConfigRetrievalError:
            log.critical(
                'Failed to get speedtest.net configuration.  Aborting')
            sys.exit(1)

        servers_in = None
        servers_ex = None

        if mode == 'select':
            servers_in = servers
        else:
            servers_ex = servers

        self.speedtest.get_servers(servers_in, servers_ex)

        # log.debug(self.speedtest.servers)

        if len(self.speedtest.servers) != 1:
            log.debug('Selecting the closest server')
            self.speedtest.get_best_server()

            log.info(
                f"Selected server {self.speedtest.best['name']} (id:{self.speedtest.best['id']})"
            )
    def write_influx_data(self, json_data):
        """
        Writes the provided JSON to the database
        :param json_data:
        :return: None
        """
        log.debug(json_data)

        try:
            self.influx_client.write_points(json_data)
        except (InfluxDBClientError, ConnectionError,
                InfluxDBServerError) as e:
            if hasattr(e, 'code') and e.code == 404:
                log.error('Database %s Does Not Exist.  Attempting To Create',
                          self.config_influx_database)
                self.influx_client.create_database(self.config_influx_database)
                self.influx_client.write_points(json_data)
                return

            log.error('Failed To Write To InfluxDB')
            print(e)

        log.debug('Data written to InfluxDB')
    def _get_influx_connection(self):
        """
        Create an InfluxDB connection and test to make sure it works.
        We test with the get all users command.  If the address is bad it fails
        with a 404.  If the user doesn't have permission it fails with 401
        :return:
        """
        if config.influx_version == 1:
            influx = InfluxDBClient(config.influx_address,
                                    config.influx_port,
                                    database=config.influx_database,
                                    ssl=config.influx_ssl,
                                    verify_ssl=config.influx_verify_ssl,
                                    username=config.influx_user,
                                    password=config.influx_password,
                                    timeout=5)
        elif config.influx_version == 2:
            log.debug('InfluxDB V2.0 is selected')
            protocol = "http://"
            if config.influx_ssl:
                protocol = "https://"
            else:
                protocol = "http://"
            influx = InfluxDBClient2(url=protocol + config.influx_address +
                                     ":" + str(config.influx_port),
                                     org=config.influx_org,
                                     token=config.influx_token,
                                     bucket=config.influx_bucket)
        try:
            log.debug(
                'Testing connection to InfluxDb using provided credentials')
            if config.influx_version == 1:
                influx.get_list_users(
                )  # TODO - Find better way to test connection and permissions
            else:
                influx.health()
            log.debug('Successful connection to InfluxDb')
        except (ConnectTimeout, InfluxDBClientError, ConnectionError) as e:
            if isinstance(e, ConnectTimeout):
                log.critical(
                    'Unable to connect to InfluxDB at the provided address (%s)',
                    config.influx_address)
            elif e.code == 401:
                log.critical(e)
                log.critical(
                    'Unable to connect to InfluxDB with provided credentials')
            else:
                log.critical(
                    'Failed to connect to InfluxDB for unknown reason')

            sys.exit(1)

        return influx