Over the limit

[Datadog] Create an Agent Integration 실습 본문

Devops/Datadog

[Datadog] Create an Agent Integration 실습

ellapk 2024. 7. 13. 00:15

데이터독 통합은 아래와 같이 크게 세가지 구조로 이루어져 있다.

 

 

1. Agent-based : 데이터독 에이전트와 파이썬 클래스 'check'로 수집할 메트릭을 정의함

2. Authentication(crawler) based : Integrations은 Datadog에 셋업 되고, 그 안에서 API로 메트릭을 얻을 수 있는 권한을 얻는다. 흔한 예로는 Slack, AWS, Azure 등이 있음

3. Library : Datadog API를 사용해서 개발 당시 사용한 언어로 앱을 모니터링 할 수 있도록 한다. 예를 들어 node.js, python이 있음 - 750개 이상이 존재하며, 웬만한 소프트웨어들은 다 있다.. 

 

 

 

통합 설정을 하면 시스템, 앱, 서비스를 모니터링 할 수 있다. 하지만 모니터링 하는 정보가 부족한 경우가 생길 수도 있다.

그럴 땐 Custom Checks를 활용해서 부족한 데이터를 기능적으로 추가하면 된다.

Integration 설정 이후, 커뮤니티 레파지토리에 제출하고, 이것이 승인되면 메트릭은 더이상 Custom 이 아닌 형태로 카운팅 된다. 

 

 

 

 

궁극적인 목표는 코드를 통해 수집하고 싶은 메트릭을 합리적인 방식으로 수집하고, general integration framework를 구축하는 것이다. 

 

최종 Integration package가 포함할 것은 다음과 같다.

  • 메트릭 수집 코드
  • 유닛 테스트
  • 통합 테스트 ( software + datadog + everything + .. )
  • 보조 파일

 

 


 

실습

 

 

Integration의 3가지 형태

 

1. Core integration : 데이터독에 의해 개발되고 유지됨

2. Extra integration : 커뮤니티(사용자)에 의해 개발되고 유지됨

3. Marketplace integration : 마켓플레이스 파트너에 의해 개발되고 유지됨

 

 

실습은 Extra integration에 관해 진행한다.

 

 

[환경 설정]

 

 

git clone 진행 후

git clone https://github.com/DataDog/integrations-extras.git

 

 

 

 

Datadog 개발자 도구 혹은 ddev를 다운 받는다.

 

ddev 사용시 >

pipx install ddev==6.0.0
ddev --version
ddev config set repo extras

 

 

 

Integration 설치

 

드라이런 실행을 통해 소프트웨어 구조를 살펴본 후, 이상이 없으면 그 다음 명령어를 통해 create시킨다.

ddev create -n Awesome
ddev create Awesome

 

 

 

 

 

에이전트 검사 작성

 

에이전트 기반 통합의 핵심은 정보 수집 후 Datadog으로 전송하는 "에이전트 검사" 다.

Check 클래스를 만들어서, 주기적으로 정보를 수집하고 이를 데이터독에 보고할 수 있도록 해보자.

 

  • Datadog 에이전트 v7 이상에서 실행되는 통합은 Python 3과 호환되어야 하지만, 에이전트 v5 및 v6에서 실행되는 통합은 여전히 Python 2.7을 사용합니다.
  • 검사는 반드시 AgentCheck에서 파생되어야 합니다.
  • 검사는 서명 check(self, instance)이 포함된 방식을 제공해야 합니다.
  • 검사는 datadog_checks 네임스페이스 아래의 일반 Python 패키지에 구성됩니다. 예를 들어, Awesome의 코드는 awesome/datadog_checks/awesome/ 디렉토리에 있습니다.
  • 패키지 이름은 검사 이름과 동일해야 합니다.
  • 해당 패키지 내의 Python 모듈 이름이나 검사를 구현하는 클래스 이름에는 제한이 없습니다.

 

#check.py

import requests

from datadog_checks.base import AgentCheck, ConfigurationError


class AwesomeCheck(AgentCheck):
    """AwesomeCheck derives from AgentCheck, and provides the required check method."""

    def check(self, instance):
        url = instance.get('url')
        search_string = instance.get('search_string')

        # It's a very good idea to do some basic sanity checking.
        # Try to be as specific as possible with the exceptions.
        if not url or not search_string:
            raise ConfigurationError('Configuration error, please fix awesome.yaml')

        try:
            response = requests.get(url)
            response.raise_for_status()
        # Something went horribly wrong
        except Exception as e:
            # Ideally we'd use a more specific message...
            self.service_check('awesome.search', self.CRITICAL, message=str(e))
        # Page is accessible
        else:
            # search_string is present
            if search_string in response.text:
                self.service_check('awesome.search', self.OK)
            # search_string was not found
            else:
                self.service_check('awesome.search', self.WARNING)

 

 

 

 

유효성 테스트 작성

테스트엔 두가지 유형이 있다.

1. 특정 기능에 대한 단위 테스트

2. check 방식을 실행하고 적절한 메트릭 수집을 확인하는 통합 테스트

 

 

단위 테스트 작성

#test_awesome.py
import pytest

    # Don't forget to import your integration

from datadog_checks.awesome import AwesomeCheck
from datadog_checks.base import ConfigurationError


@pytest.mark.unit
def test_config():
    instance = {}
    c = AwesomeCheck('awesome', {}, [instance])

    # empty instance
    with pytest.raises(ConfigurationError):
        c.check(instance)

    # only the url
    with pytest.raises(ConfigurationError):
        c.check({'url': 'http://foobar'})

    # only the search string
    with pytest.raises(ConfigurationError):
        c.check({'search_string': 'foo'})

    # this should not fail
    c.check({'url': 'http://foobar', 'search_string': 'foo'})

 

test_config이 unit 테스트로 표시되었다.

 

 

 

이제 awesome 이름의 test를 실행시켜보자.

 

unit test 구축을 완료했다. 이건 integration test에 대한 이해였다.

 

 

 

 

 

 

 

 

 

 

 

 

참고)

 

https://docs.datadoghq.com/ko/developers/integrations/agent_integration/?tab=%EC%A6%89%EC%8B%9C%EC%82%AC%EC%9A%A9%EA%B0%80%EB%8A%A5%ED%95%9C%ED%86%B5%ED%95%A9%EA%B5%AC%EC%B6%95#?tab=%EC%A6%89%EC%8B%9C%EC%82%AC%EC%9A%A9%EA%B0%80%EB%8A%A5%ED%95%9C%ED%86%B5%ED%95%A9%EA%B5%AC%EC%B6%95

https://learn.datadoghq.com/courses/take/intro-to-integrations/texts/39144576-lab-creating-an-agent-check-integration