Python influxdb.InfluxDBClient() Examples

The following are 30 code examples of influxdb.InfluxDBClient(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module influxdb , or try the search function .
Example #1
Source File: cloud_region.py    From openstacksdk with Apache License 2.0 7 votes vote down vote up
def get_influxdb_client(self):
        influx_args = {}
        if not self._influxdb_config:
            return None
        use_udp = bool(self._influxdb_config.get('use_udp', False))
        port = self._influxdb_config.get('port')
        if use_udp:
            influx_args['use_udp'] = True
        if 'port' in self._influxdb_config:
            if use_udp:
                influx_args['udp_port'] = port
            else:
                influx_args['port'] = port
        for key in ['host', 'username', 'password', 'database', 'timeout']:
            if key in self._influxdb_config:
                influx_args[key] = self._influxdb_config[key]
        if influxdb and influx_args:
            try:
                return influxdb.InfluxDBClient(**influx_args)
            except Exception:
                self.log.warning('Cannot establish connection to InfluxDB')
        else:
            self.log.warning('InfluxDB configuration is present, '
                             'but no client library is found.')
        return None 
Example #2
Source File: gauge_influx.py    From faucet with Apache License 2.0 7 votes vote down vote up
def ship_points(self, points):
        """Make a connection to InfluxDB and ship points."""

        if self.conf is not None:
            try:
                client = InfluxDBClient(
                    host=self.conf.influx_host,
                    port=self.conf.influx_port,
                    username=self.conf.influx_user,
                    password=self.conf.influx_pwd,
                    database=self.conf.influx_db,
                    timeout=self.conf.influx_timeout)
                if client:
                    if client.write_points(points=points, time_precision='s'):
                        return True
                    self.logger.warning(
                        '%s failed to update InfluxDB' % self.ship_error_prefix)
                else:
                    self.logger.warning(
                        '%s error connecting to InfluxDB' % self.ship_error_prefix)
            except (requests.exceptions.ConnectionError, requests.exceptions.ReadTimeout,
                    InfluxDBClientError, InfluxDBServerError) as err:
                self.logger.warning('%s %s' % (self.ship_error_prefix, err))
        return False 
Example #3
Source File: manage.py    From listenbrainz-server with GNU General Public License v2.0 7 votes vote down vote up
def init_influx():
    """ Initializes influx database. """
    from listenbrainz import config
    print("Connecting to Influx...")
    influx_client = InfluxDBClient(
        host=config.INFLUX_HOST,
        port=config.INFLUX_PORT,
        database=config.INFLUX_DB_NAME,
    )
    print("Connected to Influx!")

    print("Creating influx database...")
    influx_client.create_database(config.INFLUX_DB_NAME)
    influx_client.create_retention_policy("one_week", "1w", 1, "listenbrainz")

    print("Done!")


# Add other commands here 
Example #4
Source File: influx.py    From cloudkitty with Apache License 2.0 7 votes vote down vote up
def _get_influx_client():
        verify = CONF.storage_influxdb.use_ssl and not \
            CONF.storage_influxdb.insecure

        if verify and CONF.storage_influxdb.cafile:
            verify = CONF.storage_influxdb.cafile

        return influxdb.InfluxDBClient(
            username=CONF.storage_influxdb.username,
            password=CONF.storage_influxdb.password,
            host=CONF.storage_influxdb.host,
            port=CONF.storage_influxdb.port,
            database=CONF.storage_influxdb.database,
            ssl=CONF.storage_influxdb.use_ssl,
            verify_ssl=verify,
        ) 
Example #5
Source File: influxdb.py    From powerapi with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def connect(self):
        """
        Override from BaseDB.

        Create the connection to the influxdb database with the current
        configuration (hostname/port/db_name), then check if the connection has
        been created without failure.

        """

        # close connection if reload
        if self.client is not None:
            self.client.close()

        self.client = InfluxDBClient(host=self.uri, port=self.port, database=self.db_name)
        try:
            self.client.ping()
        except ConnectionError:
            raise CantConnectToInfluxDBException('connexion error')

        for db in self.client.get_list_database():
            if db['name'] == self.db_name:
                return

        self.client.create_database(self.db_name) 
Example #6
Source File: flask_influxdb.py    From flask-influxdb with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def connect() -> influxdb.InfluxDBClient:
        """
        Connect to InfluxDB using configuration parameters
        :return: InfluxDBClient object
        """
        return influxdb.InfluxDBClient(
            host=current_app.config["INFLUXDB_HOST"],
            port=current_app.config["INFLUXDB_PORT"],
            username=current_app.config["INFLUXDB_USER"],
            password=current_app.config["INFLUXDB_PASSWORD"],
            database=current_app.config["INFLUXDB_DATABASE"],
            ssl=current_app.config["INFLUXDB_SSL"],
            verify_ssl=current_app.config["INFLUXDB_VERIFY_SSL"],
            timeout=current_app.config["INFLUXDB_TIMEOUT"],
            retries=current_app.config["INFLUXDB_RETRIES"],
            use_udp=current_app.config["INFLUXDB_USE_UDP"],
            udp_port=current_app.config["INFLUXDB_UDP_PORT"],
            proxies=current_app.config["INFLUXDB_PROXIES"],
            pool_size=current_app.config["INFLUXDB_POOL_SIZE"],
        ) 
Example #7
Source File: influxdb.py    From thingflow-python with Apache License 2.0 7 votes vote down vote up
def __init__(self, query, host="127.0.0.1", port=8086, database="thingflow", 
                 username="root", password="root", 
                 ssl=False, verify_ssl=False, timeout=None, 
                 use_udp=False, udp_port=4444, proxies=None,
                 bulk_size=10):
        super().__init__()
        self.dbname = database
        self.client = InfluxDBClient(host=host, port=port, 
                                     username=username, password=password, 
                                     database=database,
                                     ssl=ssl, verify_ssl=verify_ssl, 
                                     timeout=timeout, 
                                     use_udp=use_udp, udp_port=udp_port, 
                                     proxies=proxies)
        self.query = query
        self.points = self.client.query(query).get_points() 
Example #8
Source File: flask_influxdb.py    From flask-influxdb with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def connection(self) -> influxdb.InfluxDBClient:
        """
        InfluxDBClient object
        :return:
        """
        ctx = _app_ctx_stack.top
        if ctx is None:
            raise RuntimeError(_app_ctx_err_msg)

        if not hasattr(ctx, "influxdb_db"):
            ctx.influxdb_db = self.connect()

        if ctx.influxdb_db is None:
            raise RuntimeError(_no_influx_msg)

        return ctx.influxdb_db 
Example #9
Source File: test_influxdb_integration.py    From graphite-influxdb with Apache License 2.0 7 votes vote down vote up
def setUp(self):
        self.step, self.num_datapoints, self.db_name = 60, 2, 'integration_test'
        self.start_time, self.end_time = (datetime.datetime.utcnow() - datetime.timedelta(hours=1)), \
          datetime.datetime.utcnow()
        self.steps = int(round((int(self.end_time.strftime("%s")) - \
                                int(self.start_time.strftime("%s"))) * 1.0 / self.step)) + 1
        self.client = InfluxDBClient(database=self.db_name)
        self.config = { 'influxdb' : { 'host' : 'localhost',
                                       'port' : 8086,
                                       'user' : 'root',
                                       'pass' : 'root',
                                       'db' : self.db_name,
                                       'schema' : [('', 60)],
                                       'log_level' : 'debug',
                                       },}
        self.finder = graphite_influxdb.InfluxdbFinder(self.config)
        self.metric_prefix = "integration_test"
        self.nodes = ["leaf_node1", "leaf_node2"]
        self.series1, self.series2 = ".".join([self.metric_prefix, self.nodes[0]]), \
          ".".join([self.metric_prefix, self.nodes[1]])
        self.series = [self.series1, self.series2]
        self.setup_db() 
Example #10
Source File: graphite_influxdb.py    From graphite-influxdb with Apache License 2.0 7 votes vote down vote up
def __init__(self, config=None):
        # Shouldn't be trying imports in __init__.
        # It turns what should be a load error into a runtime error
        config = normalize_config(config)
        self.config = config
        self.client = InfluxDBClient(config['host'], config['port'], config['user'], config['passw'], config['db'], config['ssl'])
        self.schemas = [(re.compile(patt), step) for (patt, step) in config['schema']]
        try:
            self.statsd_client = statsd.StatsClient(config['statsd'].get('host'),
                                                    config['statsd'].get('port', 8125)) \
                                                    if 'statsd' in config and config['statsd'].get('host') else NullStatsd()
        except NameError:
            logger.warning("Statsd client configuration present but 'statsd' module"
                           "not installed - ignoring statsd configuration..")
            self.statsd_client = NullStatsd()
        self._setup_logger(config['log_level'], config['log_file'])
        self.es = None
        if config['es_enabled']:
            try:
                from elasticsearch import Elasticsearch
            except ImportError:
                logger.warning("Elasticsearch configuration present but 'elasticsearch'"
                               "module not installed - ignoring elasticsearch configuration..")
            else:
                self.es = Elasticsearch(config['es_hosts']) 
Example #11
Source File: test_influxdb_integration.py    From influxgraph with Apache License 2.0 7 votes vote down vote up
def test_multi_fetch_non_existant_series(self):
        """Test single fetch data for a series by name"""
        path1, path2 = 'fake_path1', 'fake_path2'
        reader1 = influxgraph.InfluxDBReader(InfluxDBClient(
            database=self.db_name), path1)
        reader2 = influxgraph.InfluxDBReader(InfluxDBClient(
            database=self.db_name), path2)
        nodes = [influxgraph.classes.leaf.InfluxDBLeafNode(path1, reader1),
                 influxgraph.classes.leaf.InfluxDBLeafNode(path2, reader2)]
        time_info, data = self.finder.fetch_multi(nodes,
                                                  int(self.start_time.strftime("%s")),
                                                  int(self.end_time.strftime("%s")))
        for metric_name in data:
            self.assertFalse(data[metric_name],
                             msg="Expected no data for non-existant series %s - got %s" % (
                                 metric_name, data,))
        fake_nodes = list(self.finder.find_nodes(Query('fake_pathy_path')))
        time_info, data = self.finder.fetch_multi(fake_nodes,
                                                  int(self.start_time.strftime("%s")),
                                                  int(self.end_time.strftime("%s")))
        self.assertFalse(data) 
Example #12
Source File: influxdbclient.py    From munin-influxdb with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def connect(self, silent=False):
        try:
            client = influxdb.InfluxDBClient(self.settings.influxdb['host'],
                                             self.settings.influxdb['port'],
                                             self.settings.influxdb['user'],
                                             self.settings.influxdb['password']
                                             )

            # dummy request to test connection
            client.get_list_database()
        except influxdb.client.InfluxDBClientError as e:
            self.client, self.valid = None, False
            if not silent:
                print("  {0} Could not connect to database: {1}".format(Symbol.WARN_YELLOW, e))
        except Exception as e:
            print("Error: %s" % e)
            self.client, self.valid = None, False
        else:
            self.client, self.valid = client, True

        if self.settings.influxdb['database']:
            self.client.switch_database(self.settings.influxdb['database'])

        return self.valid 
Example #13
Source File: connector.py    From OpenMTC with Eclipse Public License 1.0 6 votes vote down vote up
def __init__(
            self,
            host='localhost',
            port=8086,
            user='root',
            password='root',
            dbname='example',
            dbuser='test',
            dbuser_pw='test'):

        self.host = host
        self.port = port
        self.user = user
        self.password = password
        self.dbname = dbname
        self.dbuser = dbuser
        self.dbuser_pw = dbuser_pw
        self.client = InfluxDBClient(host, port, user, password, dbname)
        self.client.create_database(dbname) 
Example #14
Source File: aux.py    From algotrading with MIT License 6 votes vote down vote up
def connect_db():
    '''
    Connects to Infludb.
    '''

    # returning InfluxDBClient object.
    try:
        conn = InfluxDBClient(var.db_host,
                              var.db_port,
                              var.db_user,
                              var.db_password,
                              var.db_name)

    except Exception as err:
        log("[ERROR] " + str(err), 0)
        sys.exit(1)

    return conn 
Example #15
Source File: influx.py    From ngsi-timeseries-api with MIT License 6 votes vote down vote up
def __init__(self, host, port=8086, db_name="ngsi-tsdb"):
        super(InfluxTranslator, self).__init__(host, port, db_name)
        self.client = InfluxDBClient(host, port, 'root', 'root') 
Example #16
Source File: client_test.py    From influxalchemy with MIT License 5 votes vote down vote up
def test_fields(mock_flux):
    mock_res = mock.MagicMock()
    mock_res.get_points.return_value = [
        {'fieldKey': 'humidity', 'fieldType': 'float'},
        {'fieldKey': 'temperature', 'fieldType': 'float'}
    ]
    mock_flux.return_value = mock_res
    db = influxdb.InfluxDBClient(database="fizz")
    client = InfluxAlchemy(db)
    exp = ["humidity", "temperature"]
    assert client.fields(Measurement.new("environment")) == exp 
Example #17
Source File: influx_utils.py    From powerapi with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def create_empty_db(url, port):
    client = InfluxDBClient(host=url, port=port)
    client.ping()

    return client 
Example #18
Source File: query_test.py    From influxalchemy with MIT License 5 votes vote down vote up
def test_limit_2(mock_limit):
    db = influxdb.InfluxDBClient(database="example")
    client = InfluxAlchemy(db)
    fizz = Measurement.new("fuzz")
    query = client.query(fizz).filter_by(vendor='quandl', market='XCME')
    assert str(query) == \
        "SELECT * FROM fuzz WHERE (market = 'XCME') AND (vendor = 'quandl');" 
Example #19
Source File: influx.py    From oncall with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, config, appname):
        try:
            self.client = InfluxDBClient(**config['influxdb']['connect'])
            self.enable_metrics = True
        except KeyError:
            logger.warning('Missing connect arguments for influxdb. Running with no metrics.')
            self.enable_metrics = False
            return
        try:
            self.extra_tags = config['influxdb']['tags']
        except KeyError:
            self.extra_tags = {}
        self.appname = appname 
Example #20
Source File: test_api.py    From listenbrainz-server with GNU General Public License v2.0 5 votes vote down vote up
def reset_influx_db(self):
        """ Resets the entire influx db """
        influx = InfluxDBClient(
            host=config.INFLUX_HOST,
            port=config.INFLUX_PORT,
            database=config.INFLUX_DB_NAME
        )
        influx.query('DROP DATABASE %s' % config.INFLUX_DB_NAME)
        influx.query('CREATE DATABASE %s' % config.INFLUX_DB_NAME) 
Example #21
Source File: test_user.py    From listenbrainz-server with GNU General Public License v2.0 5 votes vote down vote up
def setUp(self):
        ServerTestCase.setUp(self)
        DatabaseTestCase.setUp(self)

        self.log = logging.getLogger(__name__)
        self.influx = InfluxDBClient(
            host=current_app.config['INFLUX_HOST'],
            port=current_app.config['INFLUX_PORT'],
            database=current_app.config['INFLUX_DB_NAME'],
        )

        self.influx.query('''create database %s''' % current_app.config['INFLUX_DB_NAME'])

        self.logstore = init_influx_connection(self.log, {
            'REDIS_HOST': current_app.config['REDIS_HOST'],
            'REDIS_PORT': current_app.config['REDIS_PORT'],
            'REDIS_NAMESPACE': current_app.config['REDIS_NAMESPACE'],
            'INFLUX_HOST': current_app.config['INFLUX_HOST'],
            'INFLUX_PORT': current_app.config['INFLUX_PORT'],
            'INFLUX_DB_NAME': current_app.config['INFLUX_DB_NAME'],
        })

        user = db_user.get_or_create(1, 'iliekcomputers')
        db_user.agree_to_gdpr(user['musicbrainz_id'])
        self.user = User.from_dbrow(user)

        weirduser = db_user.get_or_create(2, 'weird\\user name')
        self.weirduser = User.from_dbrow(weirduser) 
Example #22
Source File: query_test.py    From influxalchemy with MIT License 5 votes vote down vote up
def test_filter_time_aware(mock_qry):
    mock_qry.side_effect = influxdb.exceptions.InfluxDBClientError(None)
    db = influxdb.InfluxDBClient(database="example")
    client = InfluxAlchemy(db)
    meas = Measurement.new("fizz")
    if sys.version_info.major >= 3:
        tz_vietnam = timezone(timedelta(hours=7, minutes=7))
    else:
        tz_vietnam = timezone('Asia/Ho_Chi_Minh')
    d_low = datetime(2016, 9, 1, tzinfo=tz_vietnam)
    d_high = datetime(2016, 10, 2, 8)
    query = client.query(meas).filter(meas.time.between(d_low, d_high))
    assert repr(query) == \
        "SELECT * FROM fizz WHERE (time >= '2016-09-01T00:00:00+07:07' "\
        "AND time <= '2016-10-02T08:00:00+00:00');" 
Example #23
Source File: influx_listenstore.py    From listenbrainz-server with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, conf, logger):
        super(InfluxListenStore, self).__init__(logger)
        self.influx = InfluxDBClient(host=conf['INFLUX_HOST'], port=conf['INFLUX_PORT'], database=conf['INFLUX_DB_NAME'])
        # Initialize brainzutils cache
        init_cache(host=conf['REDIS_HOST'], port=conf['REDIS_PORT'], namespace=conf['REDIS_NAMESPACE'])
        self.dump_temp_dir_root = conf.get('LISTEN_DUMP_TEMP_DIR_ROOT', tempfile.mkdtemp()) 
Example #24
Source File: test_influxlistenstore.py    From listenbrainz-server with GNU General Public License v2.0 5 votes vote down vote up
def reset_influx_db(self):
        """ Resets the entire influx db """
        influx = InfluxDBClient(
            host=config.INFLUX_HOST,
            port=config.INFLUX_PORT,
            database=config.INFLUX_DB_NAME
        )
        influx.query('DROP DATABASE %s' % config.INFLUX_DB_NAME)
        influx.query('CREATE DATABASE %s' % config.INFLUX_DB_NAME) 
Example #25
Source File: influxdb_events.py    From enos with GNU General Public License v3.0 5 votes vote down vote up
def v2_playbook_on_stats(self, stats):
        """Connect to InfluxDB and commit events"""
        # Get external tags if any
        enos_tags = self.vm.get_vars().get('enos_tags', '')
        fields = {
            'tags': 'playbook {} {}'.format(
               self.playbook_name, enos_tags),
            'text': 'playbook finished',
            'type': 'playbook',
            'title': self.playbook_name
        }
        self.report_event(fields)

        # Set InfluxDB host from an environment variable if provided
        _host = os.getenv('INFLUX_VIP') or self.vm.get_vars().get('influx_vip')
        if not _host:
            return
        _port = "8086"
        _user = "None"
        _pass = "None"
        _dbname = "events"
        influxdb = InfluxDBClient(_host, _port, _user, _pass, _dbname)
        try:
            version = influxdb.ping()                        
        except (InfluxDBServerError,
                exceptions.HTTPError,
                exceptions.ConnectionError,
                exceptions.Timeout,
                exceptions.RequestException) as error:

                return

        try:
            influxdb.write_points(self.events, time_precision='u')
        except Exception:
            # Disable the plugin if writes fail
            self.disabled = True
            self._display.warning(
                "Cannot write to InfluxDB, check the service state "
                "on %s." % _host)
            return 
Example #26
Source File: metrics.py    From openSUSE-release-tools with GNU General Public License v2.0 5 votes vote down vote up
def main(args):
    global client
    client = InfluxDBClient(args.host, args.port, args.user, args.password, args.project)

    osc.conf.get_config(override_apiurl=args.apiurl)
    apiurl = osc.conf.config['apiurl']
    osc.conf.config['debug'] = args.debug

    # Ensure database exists.
    client.create_database(client._database)

    metrics_release.ingest(client)
    if args.release_only:
        return

    # Use separate cache since it is persistent.
    _, package = project_pseudometa_package(apiurl, args.project)
    if args.wipe_cache:
        Cache.delete_all()
    if args.heavy_cache:
        Cache.PATTERNS[r'/search/request'] = sys.maxint
        Cache.PATTERNS[r'/source/[^/]+/{}/_history'.format(package)] = sys.maxint
    Cache.PATTERNS[r'/source/[^/]+/{}/[^/]+\?rev=.*'.format(package)] = sys.maxint
    Cache.init('metrics')

    Config(apiurl, args.project)
    api = StagingAPI(apiurl, args.project)

    print('dashboard: wrote {:,} points'.format(ingest_dashboard(api)))

    global who_workaround_swap, who_workaround_miss
    who_workaround_swap = who_workaround_miss = 0

    points_requests = ingest_requests(api, args.project)
    points_schedule = ingest_release_schedule(args.project)

    print('who_workaround_swap', who_workaround_swap)
    print('who_workaround_miss', who_workaround_miss)

    print('wrote {:,} points and {:,} annotation points to db'.format(
        points_requests, points_schedule)) 
Example #27
Source File: module.py    From mod-influxdb with GNU Affero General Public License v3.0 5 votes vote down vote up
def init(self):
        logger.info(
            "[influxdb broker] I init the %s server connection to %s:%d" %
            (self.get_name(), str(self.host), self.port)
        )

        self.db = InfluxDBClient(
            self.host, self.port, self.user, self.password, self.database,
            ssl=self.use_https, use_udp=self.use_udp,
            udp_port=self.udp_port, timeout=None
        ) 
Example #28
Source File: influx.py    From iris with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, config, appname):
        try:
            self.client = InfluxDBClient(**config['influxdb']['connect'])
            self.enable_metrics = True
        except KeyError:
            logger.warning('Missing connect arguments for influxdb. Running with no metrics.')
            self.enable_metrics = False
            return
        try:
            self.extra_tags = config['influxdb']['tags']
        except KeyError:
            self.extra_tags = {}
        self.appname = appname 
Example #29
Source File: forwarder.py    From mqtt-to-influxdb-forwarder with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, host, port, username, password_file, database):
        password = open(password_file).read().strip()
        self.influx_client = InfluxDBClient(
            host=host, port=port, username=username, password=password, database=database)
        # influx_client.create_database('sensors') 
Example #30
Source File: query_test.py    From influxalchemy with MIT License 5 votes vote down vote up
def test_get_empty_tags_fields(mock_fields, mock_tags):
    mock_tags.return_value = []
    mock_fields.return_value = []
    db = influxdb.InfluxDBClient(database="example")
    client = InfluxAlchemy(db)
    fizz = Measurement.new("fuzz")
    query = client.query(fizz)
    assert str(query) == "SELECT * FROM fuzz;"