aboutsummaryrefslogtreecommitdiffstats
path: root/api/utils/influx.py
blob: 1d56c95fddefca8872899b46527d69fd43ea6028 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import logging
from urlparse import urlsplit

from influxdb import InfluxDBClient
import ConfigParser

from api import conf

logger = logging.getLogger(__name__)


def get_data_db_client():
    parser = ConfigParser.ConfigParser()
    try:
        parser.read(conf.OUTPUT_CONFIG_FILE_PATH)
        dispatcher = parser.get('DEFAULT', 'dispatcher')

        if 'influxdb' != dispatcher:
            raise RuntimeError

        ip = _get_ip(parser.get('dispatcher_influxdb', 'target'))
        username = parser.get('dispatcher_influxdb', 'username')
        password = parser.get('dispatcher_influxdb', 'password')
        db_name = parser.get('dispatcher_influxdb', 'db_name')
        return InfluxDBClient(ip, conf.PORT, username, password, db_name)
    except ConfigParser.NoOptionError:
        logger.error('can not find the key')
        raise


def _get_ip(url):
    return urlsplit(url).hostname


def _write_data(measurement, field, timestamp, tags):
    point = {
        'measurement': measurement,
        'fields': field,
        'time': timestamp,
        'tags': tags
    }

    try:
        client = get_data_db_client()

        logger.debug('Start to write data: %s', point)
        client.write_points([point])
    except RuntimeError:
        logger.debug('dispatcher is not influxdb')


def write_data_tasklist(task_id, timestamp, status, error=''):
    field = {'status': status, 'error': error}
    tags = {'task_id': task_id}
    _write_data('tasklist', field, timestamp, tags)