[카테고리:] Prometheus

  • Prometheus Node Exporter 설치가이드

    Prometheus Node Exporter 설치가이드

    node exporter 설치

    wget https://github.com/prometheus/node_exporter/releases/download/v1.7.0/node_exporter-1.7.0.linux-amd64.tar.gz

    파일 압축 풀기

    tar xzvf node_exporter-1.7.0.linux-amd64.tar.gz

    Node exporter 실행

    node_exporter를 이용해서 서버의 리소스를 메트릭으로 전달한다. 서버 모니터링을 할 서버에 설치해야 한다.

    설치하는 서버 방화벽 9100 해제해야 한다.

    ./node_exporter
    ./node_exporter & # 백그라운드 실행.

    Prometheus — node_exporter 사이에 metric 전송 방식은 prometheus가 node_exporter가 설치된 서버에 정보를 당겨오는 방식(Pull방식.)

    ✅ 따라서, node_exporter가 설치된 서버에서 Prometheus 서버에 대해 9100 포트를 열어야 한다.

    📌 systemd 서비스 등록

    [Unit]
    Description=Node Exporter
    Wants=network-online.target
    After=network-online.target
    
    [Service]
    User=root
    Group=root
    Type=simple
    ExecStart=/usr/local/bin/node_exporter
    Restart=always
    RestartSec=5s
    
    [Install]
    WantedBy=multi-user.target
  • Prometheus Alertmanager Curl로 Silence 요청하는 법

    Prometheus Alertmanager Curl로 Silence 요청하는 법

    • 해당 기능: Jenkins 사용해서 shell schedule로 돌림.

    먼저, 프로메테우스 — alertmanager 서버 방화벽이 뚫려 있어야 함.

    curl -XPOST -H "Content-Type: application/json" \
      -d '{
            "matchers": [
              {
                "name": "instance",
                "value": "서버_IP:9100",
                "isRegex": false
              },
              {
                "name": "job",
                "value": "서버JOB이름",
                "isRegex": false
              }
            ],
            "startsAt": "'$(date -u -d "16:00 tomorrow" +"%Y-%m-%dT%H:%M:%SZ")'",
            "endsAt": "'$(date -u -d "21:00 tomorrow" +"%Y-%m-%dT%H:%M:%SZ")'",
            "createdBy": "Jenkins",
            "comment": "Scheduled silence from Jenkins for SS-API-03"
          }' \
      http://alertmanager서버_IP:9093/api/v2/silences

    해당 명령어를 실행하면 alertmanager에 내가 설정한 시간에 Silence가 생김

  • Prometheus 설치가이드

    Prometheus 설치가이드

    prometheus 설치

    Prometheus wget으로 설치

    wget https://github.com/prometheus/prometheus/releases/download/v2.42.0/prometheus-2.42.0.linux-amd64.tar.gz

    Prometheus 압축풀기

    tar -xzvf prometheus-2.42.0.linux-amd64.tar.gz

    prometheus 실행

    ./prometheus--config.file=/파일경로/prometheus.yml

    Prometheus 접속하는 법

    프로메테우스 default 포트 : 9090
    http://localhost:9090

    접속이 된다면, 정상.

    prometheus.yml 파일설정

    # my global config
    global:
      scrape_interval: 15s # Set the scrape interval to every 15 seconds. Default is every 1 minute.
      evaluation_interval: 15s # Evaluate rules every 15 seconds. The default is every 1 minute.
      # scrape_timeout is set to the global default (10s).
    
    # Alertmanager configuration
    alerting:
      alertmanagers:
        - static_configs:
            - targets: ["localhost:9093"]
              # - alertmanager:9093
    # Load rules once and periodically evaluate them according to the global 'evaluation_interval'.
    rule_files: ["alert.rules.yml"]
      # - "first_rules.yml"
      # - "second_rules.yml"
    # A scrape configuration containing exactly one endpoint to scrape:
    # Here it's Prometheus itself.
    scrape_configs:
      # The job name is added as a label `job=<job_name>` to any timeseries scraped from this config.
      - job_name: "node"
        # metrics_path defaults to '/metrics'
        # scheme defaults to 'http'.
        static_configs:
         - targets: ["ip:9100"]
  • Prometheus Blackbox Exporter 사용기

    Prometheus Blackbox Exporter 사용기

    Prometheus Blackbox Exporter 사용기

    사용목적 : process — UP,DOWN 체크

    리눅스 서버 안에 Process UP, DOWN 체크를 하기 위해 사용하였다.

    wget https://github.com/prometheus/blackbox_exporter/releases/download/v0.25.0/blackbox_exporter-0.25.0.linux-amd64.tar.gz

    감시할 Process가 있는 서버에 blackbox exporter를 설치

    tar -xzvf blackbox_exporter-0.25.0.linux-amd64.tar.gz

    압축을 풀고, 폴더 안에 blackbox.yml 파일 열기

    • vi blackbox.yml
    modules:
      http_2xx:
        prober: http
        http:
          preferred_ip_protocol: "ip4"
      http_post_2xx:
        prober: http
        http:
          method: POST
      tcp_connect:
        prober: tcp
        timeout: 15s
      pop3s_banner:
        prober: tcp
        tcp:
          query_response:
          - expect: "^+OK"
          tls: true
          tls_config:
            insecure_skip_verify: false
      grpc:
        prober: grpc
        grpc:
          tls: true
          preferred_ip_protocol: "ip4"
      grpc_plain:
        prober: grpc
        grpc:
          tls: false
          service: "service1"
      ssh_banner:
        prober: tcp
        tcp:
          query_response:
          - expect: "^SSH-2.0-"
          - send: "SSH-2.0-blackbox-ssh-check"
      irc_banner:
        prober: tcp
        tcp:
          query_response:
          - send: "NICK prober"
          - send: "USER prober prober prober :prober"
          - expect: "PING :([^ ]+)"
            send: "PONG ${1}"
          - expect: "^:[^ ]+ 001"
      icmp:
        prober: icmp
      icmp_ttl5:
        prober: icmp
        timeout: 5s
        icmp:
          ttl: 5

    해당 내용으로 고쳐야 한다. 달라진 부분은,

    tcp_connect:
        prober: tcp
        timeout: 15s

    timeout을 15초로 설정했다. 그리고, blackbox 파일을 실행시켜주면 된다.

    ./blackbox_exporter &

    blackbox_Exporter 포트는 9115. 실행이 되었으면 Prometheus 수집기 yml 파일로 간다.

    - job_name: "mariadb"
        scrape_interval: 15s
        metrics_path: /probe
        params:
          module: [tcp_connect]
        static_configs:
          - targets: ["ip:port"]
        relabel_configs:
          - source_labels: [__address__]
            target_label: __param_target
          - source_labels: [__param_target]
            target_label: instance
          - target_label: __address__
            replacement: localhost:9115

    이렇게 수집되는 대상을 yml파일에 수정해주면 된다.

  • Prometheus alertmanager 오류 대처법

    Prometheus alertmanager 오류 대처법

    level=warn component=cluster err="couldn't deduce an advertise address: no private IP found, explicit advertise addr not provided"
    ts=2024-06-05T03:36:10.082Z caller=main.go:278 level=error msg="unable to initialize gossip mesh" err="create memberlist: Failed to get final advertise address: No private IP address found, and explicit IP not provided"

    해당 오류는 클러스터 모드에서 사용할 광고 주소(advertise address)를 설정하지 않았기 때문

    solution

    /usr/local/bin/alertmanager --config.file=/etc/alertmanager/alertmanager.yml --cluster.advertise-address=192.168.1.10:9093

  • Prometheus로 python HTTP서버로 프로세스 헬스체크

    Prometheus로 python HTTP서버로 프로세스 헬스체크

    /usr/local/bin 경로에 sh 파일 생성

    • 프로세스 체크 sh 파일

    filename: crawler_check.sh

    #!/bin/bash
    
    # 체크할 프로세스의 경로를 변수에 저장합니다.
    PROCESS_PATH="./venv/bin/python tool/checkup_crawler.py --prod -d"
    # 프로세스가 실행 중인지 확인합니다.
    if pgrep -f "$PROCESS_PATH" > /dev/null
    then
        PROCESS_STATUS=1  # 프로세스가 실행 중이면 1
    else
        PROCESS_STATUS=0  # 프로세스가 실행 중이지 않으면 0
    fi
    # Prometheus 메트릭 포맷으로 출력합니다.
    echo "# HELP process_up Is the process running (1 for yes, 0 for no)"
    echo "# TYPE process_up gauge"
    echo "process_up $PROCESS_STATUS"
    • metric_server.sh — 반복적으로 메트릭 체크
    #!/bin/bash
    
    while true; do
        /usr/local/bin/crawler_check.sh > /var/www/html/metrics
        sleep 60
    done

    sh 파일을 생성 후, 서비스 등록을 해줘야 터미널 종료 후에도 prometheus scrap 가능

    • metric_server.service 파일
    [Unit]
    Description=Metric Server Script
    After=network.target
    
    [Service]
    ExecStart=/usr/local/bin/metric_server.sh
    User=root
    Restart=on-failure
    RestartSec=5s
    
    [Install]
    WantedBy=multi-user.target
    • crawler_http.service 파일

    파이썬으로 http 서버 여는 서비스 파일

    [Unit]
    Description=crawler_check
    After=network.target
    
    [Service]
    WorkingDirectory=/var/www/html
    ExecStart=/bin/python3 -m http.server 8080
    User=root
    Restart=always
    
    [Install]
    WantedBy=multi-user.target

    잘 정상동작 하는지 확인

    curl localhost:8080/metrics
  • Prometheus로 Python HTTP 서버와 프로세스 체크

    Prometheus로 Python HTTP 서버와 프로세스 체크

    먼저, http 서버를 돌려야 하기 때문에 python3 설치 여부 확인

    which python3

    내가 체크하고자 하는 프로세스가 돌고 있는지 체크하는 sh 파일

    # cd /usr/local/bin 에
    ### crawler_check.sh
    #!/bin/bash
    # 체크할 프로세스의 경로를 변수에 저장합니다.
    PROCESS_PATH="./venv/bin/python tool/checkup_crawler.py --prod -d"
    # 프로세스가 실행 중인지 확인합니다.
    if pgrep -f "$PROCESS_PATH" > /dev/null
    then
        PROCESS_STATUS=1  # 프로세스가 실행 중이면 1
    else
        PROCESS_STATUS=0  # 프로세스가 실행 중이지 않으면 0
    fi
    # Prometheus 메트릭 포맷으로 출력합니다.
    echo "# HELP process_up Is the process running (1 for yes, 0 for no)"
    echo "# TYPE process_up gauge"
    echo "process_up $PROCESS_STATUS"
    # 이렇게 작성 함.

    위의 파일이 정기적으로 돌면서 http에 update하는 sh파일

    #!/bin/bash
    
    while true; do
        /usr/local/bin/crawler_check.sh > /var/www/html/metrics
        sleep 60
    done

    혹시 모르니, /var/www/html => 디렉토리 생성.

    작성했던 sh 파일을 기반으로 systemd에 등록해주자.

    ### python-http 서버 데몬으로 실행.
    ### crawler_http.service
    
    [Unit]
    Description=crawler_check
    After=network.target
    [Service]
    WorkingDirectory=/var/www/html
    ExecStart=/bin/python3 -m http.server 8080
    User=root
    Restart=always
    [Install]
    WantedBy=multi-user.target
    
    만들었던 sh 파일 실행.
    ### metric_server.service
    
    [Unit]
    Description=Metric Server Script
    After=network.target
    [Service]
    ExecStart=/usr/local/bin/metric_server.sh
    User=root
    Restart=on-failure
    RestartSec=5s
    [Install]
    WantedBy=multi-user.target