Instantiate a connection to the InfluxDB.
514256
def main(host='localhost', port=8086):
    """"""
    user = 'root'
    password = 'root'
    dbname = 'example'
    dbuser = 'smly'
    dbuser_password = 'my_secret_password'
    query = 'select Float_value from cpu_load_short;'
    query_where = 'select Int_value from cpu_load_short where host=$host;'
    bind_params = {'host': 'server01'}
    json_body = [
        {
            "measurement": "cpu_load_short",
            "tags": {
                "host": "server01",
                "region": "us-west"
            },
            "time": "2009-11-10T23:00:00Z",
            "fields": {
                "Float_value": 0.64,
                "Int_value": 3,
                "String_value": "Text",
                "Bool_value": True
            }
        }
    ]

    client = InfluxDBClient(host, port, user, password, dbname)

    print("Create database: " + dbname)
    client.create_database(dbname)

    print("Create a retention policy")
    client.create_retention_policy('awesome_policy', '3d', 3, default=True)

    print("Switch user: " + dbuser)
    client.switch_user(dbuser, dbuser_password)

    print("Write points: {0}".format(json_body))
    client.write_points(json_body)

    print("Querying data: " + query)
    result = client.query(query)

    print("Result: {0}".format(result))

    print("Querying data: " + query_where)
    result = client.query(query_where, bind_params=bind_params)

    print("Result: {0}".format(result))

    print("Switch user: " + user)
    client.switch_user(user, password)

    print("Drop database: " + dbname)
    client.drop_database(dbname)
758309
def init(cls, conn_string=None):
        """"""
        if conn_string:
            _update_meta(conn_string)
            # We initialize the engine within the models module because models'
            # schema can depend on which data types are supported by the engine
            Meta.Session = new_sessionmaker()
            Meta.engine = Meta.Session.kw["bind"]
            logger.info(
                f"Connecting user:{Meta.DBUSER} "
                f"to {Meta.DBHOST}:{Meta.DBPORT}/{Meta.DBNAME}"
            )
            Meta._init_db()

        if not Meta.log_path:
            init_logging()

        return cls
907778
def request(self, url, method='GET', params=None, data=None,
                expected_response_code=200):
        """"""
        url = "{0}/{1}".format(self._baseurl, url)

        if params is None:
            params = {}

        auth = {
            'u': self._username,
            'p': self._password
        }

        params.update(auth)

        if data is not None and not isinstance(data, str):
            data = json.dumps(data)

        retry = True
        _try = 0
        # Try to send the request more than once by default (see #103)
        while retry:
            try:
                response = session.request(
                    method=method,
                    url=url,
                    params=params,
                    data=data,
                    headers=self._headers,
                    verify=self._verify_ssl,
                    timeout=self._timeout
                )
                break
            except (requests.exceptions.ConnectionError,
                    requests.exceptions.Timeout):
                _try += 1
                if self._retries != 0:
                    retry = _try < self._retries
        else:
            raise requests.exceptions.ConnectionError

        if response.status_code == expected_response_code:
            return response
        else:
            raise InfluxDBClientError(response.content, response.status_code)
1055251
async def connect(self):
        
        self.pool = await aiomysql.create_pool(
            loop=self.loop,
            db=self.database,
            connect_timeout=self.timeout,
            **self.connect_params)
1165236
def _connect(self):
        """"""
        if not self._db:
            import boto
            sdb = boto.connect_sdb()
            if not self.domain_name:
                self.domain_name = boto.config.get("DB", "sequence_db", boto.config.get("DB", "db_name", "default"))
            try:
                self._db = sdb.get_domain(self.domain_name)
            except SDBResponseError, e:
                if e.status == 400:
                    self._db = sdb.create_domain(self.domain_name)
                else:
                    raise
        return self._db
1027054
async def init():
    """"""
    global redis_conn  # pylint: disable=global-statement,invalid-name
    conn = await aioredis.create_connection(
        'redis://{}:{}'.format(
            SETTINGS.get('FLOW_EXECUTOR', {}).get('REDIS_CONNECTION', {}).get('host', 'localhost'),
            SETTINGS.get('FLOW_EXECUTOR', {}).get('REDIS_CONNECTION', {}).get('port', 56379)
        ),
        db=int(SETTINGS.get('FLOW_EXECUTOR', {}).get('REDIS_CONNECTION', {}).get('db', 1))
    )
    redis_conn = aioredis.Redis(conn)
491653
def init(self):
        """"""
        if not self.export_enable:
            return None

        # if username and/or password are not set the connection will try to connect with no auth
        auth_provider = PlainTextAuthProvider(
            username=self.username, password=self.password)

        # Cluster
        try:
            cluster = Cluster([self.host],
                              port=int(self.port),
                              protocol_version=int(self.protocol_version),
                              auth_provider=auth_provider)
            session = cluster.connect()
        except Exception as e:
            logger.critical("Cannot connect to Cassandra cluster '%s:%s' (%s)" % (self.host, self.port, e))
            sys.exit(2)

        # Keyspace
        try:
            session.set_keyspace(self.keyspace)
        except InvalidRequest as e:
            logger.info("Create keyspace {} on the Cassandra cluster".format(self.keyspace))
            c = "CREATE KEYSPACE %s WITH replication = { 'class': 'SimpleStrategy', 'replication_factor': '%s' }" % (self.keyspace, self.replication_factor)
            session.execute(c)
            session.set_keyspace(self.keyspace)

        logger.info(
            "Stats will be exported to Cassandra cluster {} ({}) in keyspace {}".format(
                cluster.metadata.cluster_name, cluster.metadata.all_hosts(), self.keyspace))

        # Table
        try:
            session.execute("CREATE TABLE %s (plugin text, time timeuuid, stat map<text,float>, PRIMARY KEY (plugin, time)) WITH CLUSTERING ORDER BY (time DESC)" % self.table)
        except Exception:
            logger.debug("Cassandra table %s already exist" % self.table)

        return cluster, session
486259
def init(self):
        """"""
        if not self.export_enable:
            return None

        try:
            db = potsdb.Client(self.host,
                               port=int(self.port),
                               check_host=True)
        except Exception as e:
            logger.critical("Cannot connect to OpenTSDB server %s:%s (%s)" % (self.host, self.port, e))
            sys.exit(2)

        return db
1063730
def _spawn_redis_connection_thread(self):
        """"""
        self.logger.debug("Spawn redis connection thread")
        self.redis_connected = False
        self._redis_thread = Thread(target=self._setup_redis)
        self._redis_thread.setDaemon(True)
        self._redis_thread.start()
550998
def init_db_conn(connection_name, connection_string, scopefunc=None):
    
    engine = create_engine(connection_string)
    session = scoped_session(sessionmaker(), scopefunc=scopefunc)
    session.configure(bind=engine)
    pool.connections[connection_name] = Connection(engine, session)
240227
async def connect(self):
        
        self.pool = await aiopg.create_pool(
            loop=self.loop,
            timeout=self.timeout,
            database=self.database,
            **self.connect_params)
490112
def main(host='localhost', port=8086, nb_day=15):
    """"""
    nb_day = 15  # number of day to generate time series
    timeinterval_min = 5  # create an event every x minutes
    total_minutes = 1440 * nb_day
    total_records = int(total_minutes / timeinterval_min)
    now = datetime.datetime.today()
    metric = "server_data.cpu_idle"
    series = []

    for i in range(0, total_records):
        past_date = now - datetime.timedelta(minutes=i * timeinterval_min)
        value = random.randint(0, 200)
        hostName = "server-%d" % random.randint(1, 5)
        # pointValues = [int(past_date.strftime('%s')), value, hostName]
        pointValues = {
            "time": int(past_date.strftime('%s')),
            "measurement": metric,
            "fields": {
                "value": value,
            },
            "tags": {
                "hostName": hostName,
            },
        }
        series.append(pointValues)

    print(series)

    client = InfluxDBClient(host, port, USER, PASSWORD, DBNAME)

    print("Create database: " + DBNAME)
    try:
        client.create_database(DBNAME)
    except InfluxDBClientError:
        # Drop and create
        client.drop_database(DBNAME)
        client.create_database(DBNAME)

    print("Create a retention policy")
    retention_policy = 'server_data'
    client.create_retention_policy(retention_policy, '3d', 3, default=True)

    print("Write points #: {0}".format(total_records))
    client.write_points(series, retention_policy=retention_policy)

    time.sleep(2)

    query = "SELECT MEAN(value) FROM {} WHERE \
            time > now() - 10d GROUP BY time(500m)".format(metric)
    result = client.query(query, database=DBNAME)
    print(result)
    print("Result: {0}".format(result))

    print("Drop database: {}".format(DBNAME))
    client.drop_database(DBNAME)
651082
def setup_influxdb(self, config):
        
        base_tags = {
            'version': self.consumer_version
        }
        measurement = self.config.get('influxdb_measurement',
                                      os.environ.get('SERVICE'))
        if measurement != self.consumer_name:
            base_tags['consumer'] = self.consumer_name
        for key in {'ENVIRONMENT', 'SERVICE'}:
            if key in os.environ:
                base_tags[key.lower()] = os.environ[key]
        influxdb.install(
            '{}://{}:{}/write'.format(
                config.get('scheme',
                           os.environ.get('INFLUXDB_SCHEME', 'http')),
                config.get('host',
                           os.environ.get('INFLUXDB_HOST', 'localhost')),
                config.get('port', os.environ.get('INFLUXDB_PORT', '8086'))
            ),
            config.get('user', os.environ.get('INFLUXDB_USER')),
            config.get('password', os.environ.get('INFLUXDB_PASSWORD')),
            base_tags=base_tags)
        return config.get('database', 'rejected'), measurement
601303
def create_connection(self):
        """"""
        err = None
        try:
            for res in socket.getaddrinfo(self._server, self._port, 0, self._sock_type):
                af, socktype, proto, canonname, sa = res
                sock = None
                try:
                    sock = socket.socket(af, socktype, proto)
                    sock.settimeout(self._timeout)
                    sock.connect(sa)
                    # Break explicitly a reference cycle
                    err = None
                    return sock

                except socket.error as _:
                    err = _
                    if sock is not None:
                        sock.close()

            if err is not None:
                raise err
            else:
                raise socket.error('No valid addresses found, try checking your IPv6 connectivity')
        except socket.gaierror as e:
            err_code, message = e.args
            if err_code == socket.EAI_NODATA or err_code == socket.EAI_NONAME:
                raise socket.error('Unable to resolve host, check your DNS: {}'.format(message))

            raise
60707
async def prepare_conn(self, conn):
        """"""

        client_id = str(uuid.uuid4())
        monitor = functools.partial(self.send_event, client_id)

        self._logger.info("New client connection: %s", client_id)

        self.service_manager.add_monitor(monitor)

        self.clients[client_id] = dict(connection=conn, monitor=monitor)
        return client_id
998510
def connect(*args, **kwargs):
    """"""
    global __CONNECTION
    if __CONNECTION is None:
        __CONNECTION = Connection(*args, **kwargs)

    return __CONNECTION
766763
def connect(self, **kwargs):
        ''' 
        '''
        if 'database' not in kwargs:
            kwargs['database'] = 'ait'

        self._conn = self._backend.connect(kwargs['database'])