No menu items!
No menu items!
More

    Sử dụng Telegraf thu thập metric đưa vào InfluxDB

    1. Tổng quan.

    Trong bài viết này, chúng ta sẽ tìm hiểu cách sử dụng Telegraf để thu thập kết quả kiểm tra ICMP từ một danh sách các địa chỉ IP và lưu trữ chúng vào InfluxDB. Chúng ta sẽ sử dụng một script Python để thực hiện kiểm tra ICMP và xuất kết quả dưới dạng JSON. Telegraf sẽ được cấu hình để chạy script này định kỳ và gửi dữ liệu thu thập được đến InfluxDB. Đây là một giải pháp mạnh mẽ và linh hoạt để giám sát tình trạng mạng và hiệu suất của các máy chủ.

    2. Ví dụ quy trình về đẩy metrics từ Telegraf sử dụng script về InfluxDB.

    2.1. Quy trình tóm tắt.

    • Viết script Python để kiểm tra ICMP:
      • Sử dụng thư viện subprocess để thực hiện lệnh ping và thu thập thời gian phản hồi.
      • Sử dụng re để trích xuất thời gian phản hồi từ kết quả ping.
      • Sử dụng ThreadPoolExecutor để thực hiện kiểm tra ICMP song song cho nhiều địa chỉ IP.
      • Xuất kết quả kiểm tra dưới dạng JSON.
    • Cấu hình Telegraf để chạy script Python:
      • Sử dụng plugin [[inputs.exec]] của Telegraf để chạy script Python định kỳ.
      • Định cấu hình Telegraf để đọc đầu ra JSON từ script và gửi dữ liệu đến InfluxDB.
      • Đảm bảo rằng Telegraf có thể chạy script với quyền cần thiết (ví dụ: sử dụng sudo nếu cần).
    • Lưu trữ dữ liệu vào InfluxDB:
      • Telegraf sẽ gửi dữ liệu thu thập được từ script Python đến InfluxDB.
      • Dữ liệu sẽ được lưu trữ trong InfluxDB và có thể được truy vấn và phân tích sau này.

    2.2. Chi tiết cấu hình.

    Tại file cấu hình cho Telegraf /etc/telegraf/telegraf.d/layer34.conf với plugin [[inputs.exec]] để chạy script icmp.py và xử lý output là JSON đúng định dạng Telegraf có thể đọc. Tuy nhiên, bạn cần đảm bảo rằng script icmp.py của bạn xuất ra JSON đúng định dạng và Telegraf có thể đọc và xử lý nó một cách chính xác.

    Cấu hình Telegraf.

    [[inputs.exec]]
        commands = ["python3 /home/icmp.py"]
        interval = "30s"
        json_name_key = "name"
        tag_keys = ["role", "ip"]
        timeout = "60s"
        data_format = "json"

    Giải thích.

    • commands: Chạy lệnh python3 /home/icmp.py để thực thi script icmp.py.
    • interval: Thực thi lệnh mỗi 30 giây.
    • json_name_key: Sử dụng trường name trong JSON làm tên của measurement.
    • tag_keys: Sử dụng trường roleip trong JSON làm tag.
    • timeout: Thời gian chờ tối đa là 60 giây.
    • data_format: Định dạng dữ liệu là JSON.

    Dưới đây là một ví dụ về script icmp.py để đảm bảo rằng nó xuất ra JSON đúng định dạng:

    import subprocess
    import re
    import json
    from concurrent.futures import ThreadPoolExecutor
    
    list_hosts = ['1.1.1.1', '8.8.8.8', '8.8.4.4', '8.8.8.7', '10.237.7.71']
    
    def icmp_response_time(target_ipaddr):
        try:
            response = subprocess.check_output(
                f"ping -c 4 -W 0.5 {target_ipaddr}",
                shell=True,
                stderr=subprocess.STDOUT,
                universal_newlines=True
            )
    
            rtt_match = re.search(r"time=([\d.]+) ms", response)
            if rtt_match:
                rtt = float(rtt_match.group(1))
                response = rtt
            else:
                response = 0
        except subprocess.CalledProcessError:
            response = 0
        return response
    
    def generate_json_output(hosts):
        output = []
        with ThreadPoolExecutor(max_workers=10) as executor:
            futures = {executor.submit(icmp_response_time, host): host for host in hosts}
            for future in futures:
                host = futures[future]
                try:
                    status = future.result()
                    output.append({
                        "name": "check-host",
                        "role": "icmp",
                        "ip": host,
                        "status": status
                    })
                except Exception as e:
                    print(f"Error checking {host}: {e}")
                    output.append({
                        "name": "check-host",
                        "role": "icmp",
                        "ip": host,
                        "status": 0
                    })
        return json.dumps(output, indent=4)
    
    # Generate JSON output and print it
    if __name__ == "__main__":
        json_output = generate_json_output(list_hosts)
        print(json_output)

    Chạy script icmp.py.

    Khi bạn chạy script icmp.py, nó sẽ xuất ra JSON đúng định dạng mà Telegraf có thể đọc và xử lý.

    shell> python3 /home/icmp.py
    [
        {
            "name": "check-host",
            "role": "icmp",
            "ip": "1.1.1.1",
            "status": 0
        },
        {
            "name": "check-host",
            "role": "icmp",
            "ip": "8.8.8.8",
            "status": 0
        },
        {
            "name": "check-host",
            "role": "icmp",
            "ip": "8.8.4.4",
            "status": 0
        },
        {
            "name": "check-host",
            "role": "icmp",
            "ip": "8.8.8.7",
            "status": 0
        },
        {
            "name": "check-host",
            "role": "icmp",
            "ip": "10.237.7.71",
            "status": 0.039
        }
    ]

    Khởi động lại Telegraf.

    systemctl restart telegraf

    Kiểm tra trạng thái Telegraf sau khi khởi động lại.

    Đảm bảo rằng Telegraf đang chạy và cấu hình của bạn đã được áp dụng. Bạn có thể kiểm tra log của Telegraf để đảm bảo rằng không có lỗi nào xảy ra khi đọc và xử lý đầu ra từ script icmp.py.

    root@ubuntu2204:/etc/telegraf/telegraf.d# systemctl status telegraf
    ● telegraf.service - Telegraf
         Loaded: loaded (/lib/systemd/system/telegraf.service; enabled; vendor preset: enabled)
         Active: active (running) since Wed 2024-09-11 08:40:26 UTC; 4s ago
           Docs: https://github.com/influxdata/telegraf
       Main PID: 5602 (telegraf)
          Tasks: 25 (limit: 9389)
         Memory: 33.2M
            CPU: 240ms
         CGroup: /system.slice/telegraf.service
                 ├─5602 /usr/bin/telegraf -config /etc/telegraf/telegraf.conf -config-directory /etc/telegraf/telegraf.d
                 ├─5613 python3 /home/icmp.py
                 ├─5615 /bin/sh -c "ping -c 4 -W 0.5 1.1.1.1"
                 ├─5618 ping -c 4 -W 0.5 1.1.1.1
                 ├─5620 /bin/sh -c "ping -c 4 -W 0.5 8.8.4.4"
                 ├─5621 /bin/sh -c "ping -c 4 -W 0.5 8.8.8.8"
                 ├─5622 ping -c 4 -W 0.5 8.8.4.4
                 ├─5624 /bin/sh -c "ping -c 4 -W 0.5 8.8.8.7"
                 ├─5625 ping -c 4 -W 0.5 8.8.8.8
                 ├─5626 /bin/sh -c "ping -c 4 -W 0.5 10.237.7.71"
                 ├─5627 ping -c 4 -W 0.5 8.8.8.7
                 └─5628 ping -c 4 -W 0.5 10.237.7.71
    
    Sep 11 08:40:26 ubuntu2204 systemd[1]: Starting Telegraf...
    Sep 11 08:40:26 ubuntu2204 telegraf[5602]: 2024-09-11T08:40:26Z I! Loading config: /etc/telegraf/telegraf.conf
    Sep 11 08:40:26 ubuntu2204 telegraf[5602]: 2024-09-11T08:40:26Z I! Loading config: /etc/telegraf/telegraf.d/layer34.conf
    Sep 11 08:40:26 ubuntu2204 systemd[1]: Started Telegraf.

    Bạn có thể check logs Telegraf tại /var/log/telegraf/telegraf.log.

    shell> tail -f /var/log/telegraf/telegraf.log
    2024-09-11T08:40:26Z I! Loaded secretstores:
    2024-09-11T08:40:26Z I! Loaded outputs: influxdb
    2024-09-11T08:40:26Z I! Tags enabled: host=ubuntu2204
    2024-09-11T08:40:26Z I! [agent] Config: Interval:1m0s, Quiet:false, Hostname:"ubuntu2204", Flush Interval:1m0s
    2024-09-11T08:40:26Z D! [agent] Initializing plugins
    2024-09-11T08:40:26Z W! DeprecationWarning: Value "false" for option "ignore_protocol_stats" of plugin "inputs.net" deprecated since version 1.27.3 and will be removed in 1.36.0: use the 'inputs.nstat' plugin instead for protocol stats
    2024-09-11T08:40:26Z D! [agent] Connecting outputs
    2024-09-11T08:40:26Z D! [agent] Attempting connection to [outputs.influxdb]
    2024-09-11T08:40:26Z D! [agent] Successfully connected to outputs.influxdb
    2024-09-11T08:40:26Z D! [agent] Starting service inputs
    2024-09-11T08:41:26Z D! [outputs.influxdb] Wrote batch of 118 metrics in 9.335129ms
    2024-09-11T08:41:26Z D! [outputs.influxdb] Buffer fullness: 0 / 100000 metrics

    3. Verify metrics trên InfluxDB.

    Như kết quả dưới, bạn đã thấy xuất hiện một measurements mới tên là check-host.

    shell> influx -precision rfc3339
    Connected to http://localhost:8086 version 1.8.10
    InfluxDB shell version: 1.8.10
    > SHOW DATABASES
    name: databases
    name
    ----
    _internal
    mydb
    database-name
    > use database-name
    Using database database-name
    > SHOW MEASUREMENTS
    name: measurements
    name
    ----
    check-host
    cpu
    disk
    diskio
    interrupts
    kernel
    linux_sysctl_fs
    mem
    net
    netstat
    nstat
    processes
    soft_interrupts
    system
    >

    Hãy thử truy vấn metrics này với câu truy vấn SELECT * FROM “check-host” và bạn có kết quả như dưới.

    > SELECT * FROM "check-host"
    name: check-host
    time                 host       ip          role status
    ----                 ----       --          ---- ------
    2024-09-11T09:44:04Z ubuntu2204 1.1.1.1     icmp 0
    2024-09-11T09:44:04Z ubuntu2204 10.237.7.71 icmp 0.04
    2024-09-11T09:44:04Z ubuntu2204 8.8.4.4     icmp 0
    2024-09-11T09:44:04Z ubuntu2204 8.8.8.7     icmp 0
    2024-09-11T09:44:04Z ubuntu2204 8.8.8.8     icmp 0
    2024-09-11T09:44:34Z ubuntu2204 1.1.1.1     icmp 0
    2024-09-11T09:44:34Z ubuntu2204 10.237.7.71 icmp 0.042
    2024-09-11T09:44:34Z ubuntu2204 8.8.4.4     icmp 0
    2024-09-11T09:44:34Z ubuntu2204 8.8.8.7     icmp 0
    2024-09-11T09:44:34Z ubuntu2204 8.8.8.8     icmp 0
    2024-09-11T09:45:04Z ubuntu2204 1.1.1.1     icmp 0
    2024-09-11T09:45:34Z ubuntu2204 10.237.7.71 icmp 0.041
    2024-09-11T09:45:34Z ubuntu2204 8.8.4.4     icmp 0
    2024-09-11T09:45:34Z ubuntu2204 8.8.8.7     icmp 0
    2024-09-11T09:45:34Z ubuntu2204 8.8.8.8     icmp 0
    >

    3. Một số lệnh giúp check lỗi file cấu hình.

    Kiểm tra file cấu hình Telegraf (/etc/telegraf/telegraf.conf) để đảm bảo không có lỗi cú pháp:

    telegraf --test --config /etc/telegraf/telegraf.conf

    Nếu có lỗi cú pháp, lệnh này sẽ báo lỗi cụ thể. Sửa lỗi nếu cần.

    Nếu Telegraf sử dụng thư mục cấu hình bổ sung (/etc/telegraf/telegraf.d), hãy kiểm tra tất cả file trong đó:

    telegraf --config /etc/telegraf/telegraf.conf --config-directory /etc/telegraf/telegraf.d --test

    Hoặc có thể chỉ định từng file, ví dụ.

    telegraf --config /etc/telegraf/telegraf.conf --test
    telegraf --config-directory /etc/telegraf/telegraf.d --test
    telegraf --config-directory /etc/telegraf/telegraf.d/test.conf --test

    Kiểm tra quyền và môi trường

    • Đảm bảo rằng Telegraf có quyền truy cập vào tất cả file cấu hình, thư mục, hoặc script mà nó sử dụng.
    • Kiểm tra biến môi trường TELEGRAF_OPTS (nếu được sử dụng trong /etc/default/telegraf hoặc /etc/environment).

    Nếu lỗi vẫn xảy ra

    Nếu lỗi vẫn xảy ra sau các bước trên, hãy:

    • Cung cấp log chi tiết từ journalctl.
    • Chạy lại Telegraf trong chế độ foreground để debug:
    telegraf --config /etc/telegraf/telegraf.conf --debug

    3. Tổng kết.

    Cấu hình của bạn cho Telegraf là đúng, và script icmp.py cần xuất ra JSON đúng định dạng để Telegraf có thể đọc và xử lý. Hãy đảm bảo rằng script của bạn hoạt động đúng và Telegraf có thể đọc đầu ra JSON mà không gặp lỗi.

    Bài viết gần đây

    spot_img

    Related Stories

    Leave A Reply

    Please enter your comment!
    Please enter your name here

    Đăng ký nhận thông tin bài viết qua email