Category: InfluxDB

  • Telegraf

    InfluxDB와 같은 회사 제품으로 추정되는 Telegraf를 설치했다.

    sudo apt install telegraf

    InfluxDB에서 시스템 별로 구분하기 위하여 tag을 지정해 준다. [agent]에서 hostname부분을 설정해 주면 시스템 상의 hostname이 아닌 이 이름으로 저장이 돈다.

    [agent]
    hostname = "server"

    저장할 DB를 다음과 같이 설정해 준다.

    [[outputs.influxdb_v2]]
    urls = ["http://sweet.home:8086"]
    token = ""
    organization = ""
    bucket = ""

    난 단순한 네트웍 I/O를 확인하는 것이 필요했다. 그래서 다음을 추가해 주었다.

    [[inputs.net]]
    interfaces = ["eno*", "enp0s[0-1]", "lo"]
    ignore_protocol_stats = false
  • Python에서 InfluxDB 자료 불러오기

    Python 에서 InfluxDB의 자료를 불러와서 plot을 그려보기로 했다. 첫 번째 단계는 자료를 불러오는 것, 그리고 2번째 단계는 불러온 자료를 가공하는 것이다.

    PIP로 influxdb_client를 설치한다. 여러 종류가 있는 듯 한데, 불러오는 부분에 있어서 큰 차이는 없는 것 같다.

    import influxdb_client
    
    url = "http://www.welovedoctor.com:8086"
    token = "my_token"
    org = 'my_org'
    
    client = influxdb_client.InfluxDBClient(url=url, token=token, org=org)
    query_api = client.query_api()
    query = 'from(bucket:"measurement") |> range(start: -1h) |> filter(fn: (r) => r["_measurement"] == "location=home") |> filter(fn: (r) => r["_field"] == "temperature")'
    tables = query_api.query(org=org, query=query)

    query는 Flux 문법의 스크립트를 그대로 이용할 수 있다. 이렇게 하면 tables에 결과를 저장할 수 있다.

    그 다음은 json 으로 포맷을 변환하는 것이다. 구조가 복합하기 때문에 실제로 불러서 확인해 본 후 분석 방법을 결정해야 한다.

    from influxdb_client.client.flux_table import FluxStructureEncoder
    
    dt = json.loads(json.dumps(tables, cls=FluxStructureEncoder))
  • Flux 작성하기

    InfluxDB v2.0 부터 Flux 라는 형식으로 데이터를 추출하도록 해야 한다고 한다.

    ICU03번으로 입력된 SpO2 1일치 자료는 다음과 같이 입력하면 깔끔하게 출력된다. map 부분을 저렇게 해주지 않으면 예쁘지 않은 label로 보인다.

    from(bucket: "measurements")
    |> range(start:-1d)
    |> filter(fn: (r) => r._measurement == "vital" and r.bed  == "ICU03" and r._field == "spo2")
    |>  map(fn: (r) => ({ _value:r._value, _time:r._time, _field:"SpO2" }))
  • API로 결과 입력하기

    InfluxDB의 경우 ns 단위로 시간 결과를 입력할 수 있다고 한다. 나의 경우에는 ms도 과할 정도고 s 단위 정도면 충분하다.

    기본적으로 다음과 같은 식으로 데이터를 준비해야 한다.

    빈 칸(white space)는 두 번 들어갈 수 있다. 첫 번째는 tag와 field 사이이고 두 번째는 field와 timestamp 사이이다.

    꼭 필요한 값은 measurement 와 field 이다. timestamp 의 경우 입력하지 않으면 host 시간을 기준으로 입력된다.

    curl --request POST \
    "http://localhost:8086/api/v2/write?org=rcc&bucket=measurements&precision=s" \
      --header "Authorization: Token MY_TOKEN_HERE" \
      --header "Content-Type: text/plain; charset=utf-8" \
      --header "Accept: application/json" \
      --data-binary '
        vital,bed=ICU01 spo2=99
        '

    curl 로 입력하려면 위와 같은 식으로 준비하면 된다.

    Python의 Requests로 입력하려면 다음과 같이 하면 된다. 준비 과정에서 따옴표가 지나치게 많이 들어가기 때문에 최대한 dictionary 타입으로 준비하는 것이 좋다. 위에서 언급했지만 precision은 second로 하도록 한다.

    headers = {
        "Authorization": "Token My_TOKEN_HERE",  
        "Content-Type": "text/plain; charset=utf-8",
        "Accept": "application/json"
    }
    
    requests.post(
    "http://rcc.work:8086/api/v2/write?org=rcc&bucket=measurements&precision=s",
    headers=headers,
    data=data_influx_3
    )