본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

이벤트 훅

원문 보기 위키 갱신

이벤트 훅 (Event Hooks)

이벤트 훅은 Kong Gateway 엔티티에서 발생하는 특정 이벤트를 리스닝하고, 그 정보를 로그나 웹훅, 서드파티 애플리케이션으로 전달할 수 있게 해주는 Kong Gateway 엔티티예요

출처: 문서

본문

이벤트 훅(Event Hook)이란 무엇인가요?

이벤트 훅은 Kong Gateway 엔티티에서 발생하는 특정 이벤트를 리스닝하도록 설정할 수 있는 Kong Gateway 엔티티예요. 이벤트 훅은 로그, 웹훅, 서드파티 애플리케이션에 정보를 보내도록 설정할 수 있어요.

이벤트 훅은 어떻게 동작하나요?

Kong Gateway 이벤트 훅은 다음 세 가지 요소를 설정하는 방식으로 동작해요:

  • Sources: 이벤트 훅을 트리거하는 동작 또는 작업이에요.
  • Events: 이벤트 훅이 동작을 모니터링하는 대상인 Kong Gateway 엔티티예요.
  • Handlers: 이벤트가 트리거됐을 때 어떤 동작을 수행할지 정의하는 메커니즘이에요. 웹훅 전송, 로깅, 커스텀 코드 실행 같은 것들이 여기에 해당해요.
 
flowchart LR
    subgraph events [Kong Gateway Events]
        A(Gateway Service
Create
Delete
Modify) B(Admins
Create
Delete
Modify) end subgraph handlers [Handlers] C(Webhook) D(logs
) E(webhook-custom) F(Lambda) end subgraph output [Output] W( POST to third party application) X( Log to /usr/local/kong/logs/error.log) Y( POST to third party application
Fully customizable) Z( Custom Code Lua code ) end A --> handlers B --> handlers C --> W D --> X E --> Y F --> Z

핸들러(Handlers)

이벤트 훅에서 사용할 수 있는 핸들러는 네 가지 유형이 있어요:

  • webhook: 지정된 URL로 이벤트 데이터를 페이로드로 담아 POST 요청을 보내요.
  • log: 이벤트와 페이로드 내용을 Kong Gateway 로그로 기록해요.
  • webhook-custom: 완전히 설정 가능한 요청이에요. 템플릿을 지원하며, body, payload, 헤더를 설정할 수 있어요.
  • lambda: 이 핸들러는 이벤트가 트리거된 후 Lua 코드를 실행해요.

기본적으로 lambda 핸들러는 "샌드박스(sandboxed)" 상태예요. 샌드박싱이란 Kong Gateway가 로드할 수 있는 Lua 함수의 유형과, 이런 커스텀 함수에 허용되는 Kong Gateway 접근 수준을 제한한다는 뜻이에요. 예를 들어 sandbox 모드에서는 lambda 이벤트 훅이 kong.configuration.pg_password 같은 전역 값이나 os.execute(rm -rf /*) 같은 OS 수준 함수에 접근할 수 없지만, local foo = 1 + 1 같은 Lua 코드는 여전히 실행할 수 있어요. sandbox를 제거하려면 kong.conf의 untrusted_lua 값을 수정해야 해요. 자세한 내용은 kong.conf 문서를 참고하세요.

소스(Sources)

Kong Gateway는 /event-hooks/sources 엔드포인트를 제공해요. 여기서 이벤트 훅 템플릿을 만들 때 사용할 수 있는 모든 소스, 이벤트, 필드를 확인할 수 있어요. 소스는 이벤트 훅을 트리거하는 동작이에요.

엔드포인트의 응답 본문은 소스를 설명하고 있으며, 다음 패턴으로 해석할 수 있어요:

  1. Level 1: 소스, 즉 이벤트 훅을 트리거하는 동작이에요.
  2. Level 2: 이벤트, 즉 이벤트 훅이 이벤트를 리스닝하는 Kong Gateway 엔티티예요.
  3. Level 3: webhook-custom 페이로드를 구성할 때 사용할 수 있는 템플릿 파라미터예요.

응답 본문 예시는 다음과 같아요:

{
	"data": {
		"balancer": {
			"health": {
				"fields": [
					"upstream_id",
					"ip",
					"port",
					"hostname",
					"health"
				]
			}
		}
  }
}

이 패턴을 응답 본문에 적용하면 다음 정보를 추출할 수 있어요:

  • source: balancer
  • event: health
  • handler: webhook-custom

fields 배열의 값들은 페이로드를 구성할 때 사용할 수 있는 템플릿 파라미터를 나타내요.

  • upstream_id
  • ip
  • port
  • hostname
  • health

이 파라미터들을 사용하면 애플리케이션의 업스트림에 도달할 수 없을 때마다 알림을 보내도록 설정할 수 있어요.

사용 가능한 소스

  • dao:crud: dao:crud 클러스터링 이벤트를 처리해요.
  • balancer: upstream_id, ip, port, hostname, health 같은 로드 밸런서 정보예요.
  • ai-rate-limiting-advanced: 레이트 리밋이 초과됐을 때 이벤트를 실행해요.
  • service-protection: 레이트 리밋이 초과됐을 때 이벤트를 실행해요.
  • rate-limiting-advanced: 레이트 리밋이 초과됐을 때 이벤트를 실행해요.
  • crud: Consumers 같은 Kong Gateway 엔티티의 생성, 읽기, 업데이트 이벤트를 다뤄요.
  • oas-validation: OAS validation 플러그인이 실패했을 때 이벤트를 실행해요.

특정 소스와 관련된 이벤트 정보를 보려면 /event-hooks/sources/{source} 엔드포인트로 GET 요청을 보내세요. 그러면 API가 소스에 연결된 모든 이벤트 목록을 balancer: health 형식으로 반환해요.

이벤트 훅 설정하기

이벤트 훅을 만들려면 Admin API의 /event-hooks 엔드포인트를 호출하세요.

curl -i -X POST http://localhost:8001/event-hooks/ \
    --header "Accept: application/json" \
    --header "Content-Type: application/json" \
    --data '
    {
      "source": "crud",
      "event": "consumers",
      "handler": "webhook",
      "on_change": true,
      "config": {
        "url": "'$WEBHOOK_URL'"
      }
    }
    '

스키마

{
  "description": "Event Hooks schema",
  "example": {
    "data": [
      {
        "config": {
          "body": null,
          "body_format": true,
          "headers": {
            "content-type": "application/json"
          },
          "headers_format": false,
          "method": "POST",
          "payload": {
            "text": "payload_text"
          },
          "payload_format": true,
          "secret": null,
          "ssl_verify": false,
          "url": "https://hooks.slack.com/services/foo/bar/baz"
        },
        "created_at": 1627588552.0,
        "event": "admins",
        "handler": "webhook-custom",
        "id": "937df175-3db2-4e6d-8aa1-d95c94a76089",
        "on_change": null,
        "snooze": null,
        "source": "crud"
      },
      {
        "config": {
          "headers": {},
          "secret": null,
          "ssl_verify": false,
          "url": "https://webhook.site/a1b2c3-d4e5-g6h7-i8j9-k1l2m3n4o5p6"
        },
        "created_at": 1627581575.0,
        "event": "consumers",
        "handler": "webhook",
        "id": "c57340ab-9fed-40fd-bb7e-1cef8d37c2df",
        "on_change": null,
        "snooze": null,
        "source": "crud"
      },
      {
        "config": {
          "functions": [
            "return function (data, event, source, pid)\n  local user = data.entity.username\n  error(\"Event hook on consumer \" .. user .. \"\")\nend\n"
          ]
        },
        "created_at": 1627595513.0,
        "event": "consumers",
        "handler": "lambda",
        "id": "c9fdd58d-5416-4d3a-9467-51e5cfe4ca0e",
        "on_change": null,
        "snooze": null,
        "source": "crud"
      }
    ],
    "next": null
  },
  "properties": {
    "data": {
      "description": "List of event hooks",
      "items": {
        "properties": {
          "config": {
            "description": "Configuration for the event hook",
            "properties": {
              "body": {
                "nullable": true,
                "type": "string"
              },
              "body_format": {
                "type": "boolean"
              },
              "functions": {
                "items": {
                  "type": "string"
                },
                "nullable": true,
                "type": "array"
              },
              "headers": {
                "nullable": true,
                "properties": {
                  "content-type": {
                    "type": "string"
                  }
                },
                "type": "object"
              },
              "headers_format": {
                "type": "boolean"
              },
              "method": {
                "type": "string"
              },
              "payload": {
                "nullable": true,
                "properties": {
                  "text": {
                    "type": "string"
                  }
                },
                "type": "object"
              },
              "payload_format": {
                "type": "boolean"
              },
              "secret": {
                "nullable": true,
                "type": "string"
              },
              "ssl_verify": {
                "type": "boolean"
              },
              "url": {
                "type": "string"
              }
            },
            "type": "object"
          },
          "created_at": {
            "type": "integer"
          },
          "event": {
            "type": "string"
          },
          "handler": {
            "type": "string"
          },
          "id": {
            "type": "string"
          },
          "on_change": {
            "nullable": true,
            "type": "string"
          },
          "snooze": {
            "nullable": true,
            "type": "integer"
          },
          "source": {
            "type": "string"
          }
        },
        "type": "object"
      },
      "type": "array"
    },
    "next": {
      "nullable": true,
      "type": "string"
    }
  },
  "type": "object"
}

관련 리소스

더 알아보기 (Learn more)