데보션앱 소개페이지 바로가기
로그인 선택

신고하기

CLOSE
신고사유 (대표 사유 1개)
상세내용 (선택)
0/200
  • 신고한 게시글은 더 이상 보이지 않습니다.
  • 이용약관과 운영정책에 따라 신고사유에 해당하는지 검토 후 조치됩니다.
  • 허위 신고인 경우, 신고자의 서비스 이용이 제한될 수 있으니 유의하시어 신중하게 신고해 주세요.
(이 회원이 작성한 모든 댓글과 커뮤니티 게시물이 보이지 않고, 알림도 오지 않습니다.)

미리보기

커뮤니티

      1,234

      badge 23.06.15

      글 등록

      카테고리를 선택해주세요.

      DEVOTEE를 활성화 시키면
      지금 작성한 커뮤니티 글에 대해 1개의 댓글을 달아줍니다.

      버튼을 누르면 글 수정 시 ChatGPT가 작성한 댓글이 수정됩니다.

      임시저장함에 저장되었습니다. 저장일시 : 2022.5.17 14:29:08

      임시저장함

      제목을 선택하시면 이어서 작성이 가능하며,
      최대 20건까지 저장합니다.
      컨텐츠 유형, 제목, 저장일시, 삭제로 이뤄진 임시저장 목록
      컨텐츠 유형 제목 저장일 삭제

      데보션 블로그 게재 요청

      CLOSE
      • *
      • *

      본인인증

      효율적인 데보션 서비스 이용 및
      고객님의 소중한 개인정보보호를 위해
      본인인증을 진행해주세요. 본인인증 미 진행 시 로그인이 제한됩니다.
      본인인증 실패

      본인인증 로그인에 실패하였습니다.
      회원이 아니시거나 본인인증 등록이
      완료되지 않은 사용자입니다.

      회원정보 연결

      curl을 이용해 k8s에서 구동중인 prometheus에 query하기

      sungil 23.01.31
      3,679 15 0

      TACO LMA는 kubernetes상에 다양한 오픈소스를 사용하여 구성된다.

      필요에 따라 이러한 오픈소스를 활용하면 다양한 구성이 가능하지만 간결하게 내부의 데이터를 확인해야 하는 경우가 있다.

      고객의 요청으로 확인하는 방법에 대한 가이드를 정리하면서 이 글을 쓴다.

      여기에는 kubenetes 내부 네트워크에 띄워진 서비스에 대해 접근하는 방법과 thano에 curl을 사용하여 질의하는 방법을 포함하고 있다.


      Prometheus에 질의하기

      Prometheus에 질의는 Http API를 사용하며 공식페이지에 잘 정리되어 있다. Prometheus가 제공하는 웹 UI를 활용하면 더 간단하게 질의할 수 있다.

      (아래 그림참조) Thanos 또한 Prometheus와 동일한 인터페이스를 제공하므로 동일한 방법으로 접근할 수 있다.

      prometheusweb.png


      kubernetes 내부의 서비스에 접근하기

      하지만 kubernetes 상에 배포되어 있는 TACO LMA의 특성상 추가적인 지식이 필요하다.

      • 다음과 같이 서비스가 있다고 하면 그중 ‘thanos-query’를 대상으로 질의해야 함을 알수 있다. (이름으로 판단)

        siim@adm:~$ kubectl get svc -n lma
        NAME                                      TYPE           CLUSTER-IP       EXTERNAL-IP  PORT(S)                           AGE
        alerted-log-exporter                      ClusterIP      10.99.248.229    <none>       2112/TCP                          5d18h
        alertmanager-operated                     ClusterIP      None             <none>       9093/TCP,9094/TCP,9094/UDP        5d20h
        grafana                                   LoadBalancer   10.106.234.60    a9409f.com   80:30662/TCP                      5d18h
        kube-state-metrics                        ClusterIP      10.106.81.11     <none>       8080/TCP                          5d20h
        ...
        prometheus-operated                       ClusterIP      None             <none>       9090/TCP,10901/TCP                5d20h
        prometheus-operator-operator              ClusterIP      10.107.101.81    <none>       443/TCP                           5d20h
        prometheus-pushgateway                    NodePort       10.97.67.179     <none>       9091:30010/TCP                    5d20h
        thanos-bucketweb                          ClusterIP      10.98.72.177     <none>       8080/TCP                          5d20h
        thanos-compactor                          ClusterIP      10.105.12.18     <none>       9090/TCP                          5d20h
        thanos-query                              ClusterIP      10.100.96.18     <none>       9090/TCP,10901/TCP                5d20h
        thanos-ruler                              ClusterIP      10.97.206.189    <none>       9090/TCP,10901/TCP                5d20h
        thanos-storegateway                       ClusterIP      10.98.150.149    <none>       9090/TCP,10901/TCP                5d20h

      kubernetes 내부의 네트워크에서 동작하므로 여기에 접근하기 위한 방법이 필요한데 kubectl은 내부 명령으로 내부 네트워크로 포워딩해주는 기능을 제공하고 있다.(port-forward) 앞에서 확인한 thanos-query로 포트포워딩하자.

      • -h 옵션을 사용하면 사용방법을 확인할 수 있다.

        siim@adm:~$ kubectl port-forward -h
        Forward one or more local ports to a pod. This command requires the node to have 'socat' installed.
        
         Use resource type/name such as deployment/mydeployment to select a pod. Resource type defaults to 'pod' if omitted.
        
         If there are multiple pods matching the criteria, a pod will be selected automatically. The forwarding session ends
        when the selected pod terminates, and rerun of the command is needed to resume forwarding.
        
        Examples:
          # Listen on ports 5000 and 6000 locally, forwarding data to/from ports 5000 and 6000 in the pod
          kubectl port-forward pod/mypod 5000 6000
        
          # Listen on ports 5000 and 6000 locally, forwarding data to/from ports 5000 and 6000 in a pod selected by the
        deployment
          kubectl port-forward deployment/mydeployment 5000 6000
        
          # Listen on port 8443 locally, forwarding to the targetPort of the service's port named "https" in a pod selected by
        the service
          kubectl port-forward service/myservice 8443:https
        
          # Listen on port 8888 locally, forwarding to 5000 in the pod
          kubectl port-forward pod/mypod 8888:5000
        
          # Listen on port 8888 on all addresses, forwarding to 5000 in the pod
          kubectl port-forward --address 0.0.0.0 pod/mypod 8888:5000
        
          # Listen on port 8888 on localhost and selected IP, forwarding to 5000 in the pod
          kubectl port-forward --address localhost,10.19.21.23 pod/mypod 8888:5000
        
          # Listen on a random port locally, forwarding to 5000 in the pod
          kubectl port-forward pod/mypod :5000
        
        Options:
              --address=[localhost]: Addresses to listen on (comma separated). Only accepts IP addresses or localhost as a
        value. When localhost is supplied, kubectl will try to bind on both 127.0.0.1 and ::1 and will fail if neither of these
        addresses are available to bind.
              --pod-running-timeout=1m0s: The length of time (like 5s, 2m, or 3h, higher than zero) to wait until at least one
        pod is running
        
        Usage:
          kubectl port-forward TYPE/NAME [options] [LOCAL_PORT:]REMOTE_PORT [...[LOCAL_PORT_N:]REMOTE_PORT_N]
        
        Use "kubectl options" for a list of global command-line options (applies to all commands).

        Pod, Service, Deployment 등의 자원으로 포트포워딩이 가능하며 포트를 지정할 수 있다.

      • thanos-query로 포워딩해야 하므로 다음의 명령으로 포워딩을 실행할 수 있다. 포트포워딩 명령 수행시 해당 콘솔은 잠기므로 백그라운드 실행하거나 추가적인 콘솔을 통해 다음작업을 수행해야 한다.

        siim@adm:~$ kubectl port-forward -n lma service/thanos-query 9090:9090
        Forwarding from 127.0.0.1:9090 -> 10902
        Forwarding from [::1]:9090 -> 10902


      Thanos에 접근하여 질의하는 실 예

      • 이제 thanos 서버에 접근할수 있으므로 공식 방법을 통해 질의하자. (앞에서 9090으로 포워딩했으므로 localhost:9090은 thanos-query와 연동된다.)

        siim@adm:~$ curl 'http://localhost:9090/api/v1/query?query=up&time=2023-01-12T02:10:51.781Z'                                                                                                                           
        {"status":"success","data":{"resultType":"vector","result":[{"metric":{"__name__":"up","container":"alertmanager","endpoint":"web","instance":"192.168.150.93:9093","job":"lma-alertmanager","namespace":"lma","pod":"a
        lertmanager-lma-alertmanager-0","prometheus":"lma/lma-prometheus","prometheus_replica":"prometheus-lma-prometheus-0","service":"lma-alertmanager","taco_cluster":"cluster.local"},"value":[1673489451.781,"1"]},{"metri
        c":{"__name__":"up","container":"alertmanager","endpoint":"web","instance":"192.168.238.78:9093","job":"lma-alertmanager","namespace":"lma","pod":"alertmanager-lma-alertmanager-0","prometheus":"lma/lma-prometheus","
        prometheus_replica":"prometheus-lma-prometheus-0","service":"lma-alertmanager","taco_cluster":"cluster.local"},"value":[1673489451.781,"1"]},{"metric":{"__name__":"up","container":"coredns","endpoint":"http-metrics"
        ,"instance":"192.168.23.1:9153","job":"coredns","namespace":"kube-system","pod":"coredns-78fcd69978-2jf79","prometheus":"lma/lma-prometheus","prometheus_replica":"prometheus-lma-prometheus-0","service":"lma-coredns"
        ,"taco_cluster":"cluster.local"},"value":[1673489451.781,"1"]},{"metric":{"__name__":"up","container":"coredns","endpoint":"http-metrics","instance":"192.168.23.4:9153","job":"coredns","namespace":"kube-system","pod
        ":"coredns-78fcd69978-4m4p5","prometheus":"lma/lma-prometheus","prometheus_replica":"prometheus-lma-prometheus-0","service":"lma-coredns","taco_cluster":"cluster.local"},"value":[1673489451.781,"1"]},{"metric":{"__n
        ame__":"up","container":"coredns","endpoint":"http-metrics","instance":"192.168.238.67:9153","job":"coredns","namespace":"kube-system","pod":"coredns-78fcd69978-fs68f","prometheus":"lma/lma-prometheus","prometheus_r
        eplica":"prometheus-lma-prometheus-0","service":"lma-coredns","taco_cluster":"cluster.local"},"value":[1673489451.781,"1"]},{"metric":{"__name__":"up","container":"coredns","endpoint":"http-metrics","instance":"192.
        1.....

      클러스터에 배포된 pod수를 클러스터별로 세기

      • PromQL: sum(kube_pod_info) by (namespace)

        • ‘kube_pod_info’는 kubernetes-exporter를 통해 수집되는 metric

      • curl을 통해 보내기

        siim@adm:~$ curl 'http://localhost:9090/api/v1/query?query=sum%28kube_pod_info%29%20by%20%28namespace%29' | python -m json.tool                                                                                                                                                                                                                                             
          % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current                                                                                                                                                                                                                                                                                             
                                         Dload  Upload   Total   Spent    Left  Speed                                                                                                                                                                                                                                                                                               
        100   811  100   811    0     0  23171      0 --:--:-- --:--:-- --:--:-- 23171                                                                                                                                                                                                                                                                                              
        {                                                                                                                                                                                                                                                                                                                                                                           
            "status": "success",                                                                                                                                                                                                                                                                                                                                                    
            "data": {                                                                                                                                                                                                                                                                                                                                                               
                "resultType": "vector",                                                                                                                                                                                                                                                                                                                                             
                "result": [                                                                                                                                                                                                                                                                                                                                                         
                    {                                                                                                                                                                                                                                                                                                                                                               
                        "metric": {                                                                                                                                                                                                                                                                                                                                                 
                            "namespace": "tekton-pipelines-resolvers"                                                                                                                                                                                                                                                                                                               
                        },                                                                                                                                                                                                                                                                                                                                                          
                        "value": [
                            1673503989.423,                                                        
                            "1"                                                                         ]                                                                           },                                                                             
        ...
                    {
                        "metric": {
                            "namespace": "taco-system"
                        },
                        "value": [
                            1673503989.423,
                            "9"
                        ]
                    }
                ]
            }
        }
        • 앞의 예시에서 query 부분에 위 query를 URL-encoding을 수행한 값으로 넣어주면 된다.

        • 추가적으로 보기 편하도록 파이썬 모듈인 json.tool을 사용할 수 있다.

      • 수집된 데이터를 활용하기

        • jsonpath를 사용하면 필요한 값을 통해 shell에서도 활용가능하다.

          siim@adm:~$ curl 'http://locahost:9090/api/v1/query?query=sum%28kube_pod_info%29%20by%20%28namespace%29' | jq -r '.data.result[].value[1]'
            % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                           Dload  Upload   Total   Spent    Left  Speed
          100   811  100   811    0     0  23171      0 --:--:-- --:--:-- --:--:-- 23852
          87
          9
          1
          1
          1
          3
          1
          1
          1
          2
          106
          siim@adm:~$ for cnd in `curl 'http://localhost:9090/api/v1/query?query=sum%28kube_pod_info%29%20by%20%28namespace%29' | jq -r '.data.result[].value[1]'`
          > do
          >   if [ $cnd -gt 10 ]
          >   then
          >     echo 'too much pods in the namespace'
          >   fi
          > done
            % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                           Dload  Upload   Total   Spent    Left  Speed
          100   811  100   811    0     0  27965      0 --:--:-- --:--:-- --:--:-- 27965
          too much pods in the namespace
          too much pods in the namespace


      마치며

      이 글을 통해 kubernetes 상에서 동작하고 있는 Thanos에 curl을 사용하여 질의하는 방법에 대해 구체적으로 알아보았다.

      일반적으로 질의를 위해서는 prometheus에서 제공하는 웹UI를 활용하는 것이 더 쉽고, 활용을 위해서는 grafana의 대시보드로 구성해서 사용하는 것이 더 좋다.

      하지만 폐쇄환경에서는 이러한 접근이 쉽지 않은 경우들이 종종있고, 그 외 간단하게 데이터를 가져와 쉘로 처리해야 하는 경우들이 있는데 이 경우 소개한 방법을 참조하도록 하자.

      댓글 0

      DEVOTEE를 활성화 시키면
      지금 작성한 댓글에 AI가 댓글을 달아줍니다.

      sungil 님의 최신 블로그

      더보기
      동영상 기고하기