Skip to content

Latest commit

 

History

History
243 lines (200 loc) · 6.58 KB

013.Create_Kibana_Custom_Plugin.md

File metadata and controls

243 lines (200 loc) · 6.58 KB

013. Kibana Custom Plugin 만들기

Kibana에서 발생하는 Error Message에 상세한 내용이 보이지 않게 변경해달라는 요청을 받았다. 회사 PC (Windows)로 할 때는 비슷한 코드였는데 실행이 안됐던 것 같은데 퇴근 후 코코아 한 잔 하면서 차분한 마음으로 하니까 적용 성공해서 내용 남기는 중 ㅎㅎ 참고로 집 PC는 MacOS

docker-compose로 환경 세팅

하위 docker-compose.yml 파일 사용.

version: '3.7'
services:
  elasticsearch:
    image: docker.elastic.co/elasticsearch/elasticsearch:7.17.23
    container_name: elasticsearch
    environment:
      - discovery.type=single-node
      - bootstrap.memory_lock=true
      - "ES_JAVA_OPTS=-Xms1g -Xmx1g"
    ulimits:
      memlock:
        soft: -1
        hard: -1
    ports:
      - "9200:9200"
    volumes:
      - es_data:/usr/share/elasticsearch/data
    networks:
      - elastic

  kibana:
    image: docker.elastic.co/kibana/kibana:7.17.23
    container_name: kibana
    environment:
      - ELASTICSEARCH_HOSTS=http://elasticsearch:9200
    ports:
      - "5601:5601"
    networks:
      - elastic

volumes:
  es_data:
    driver: local

networks:
  elastic:
    driver: bridge
  • 실행 : docker-compose up -d
  • 종료 : docker-compose down

기존 API 에러 응답 확인

  • 요청 : GET http://localhost:5601/api/saved_objects/_find?
  • 응답
{
    "statusCode": 400,
    "error": "Bad Request",
    "message": "[request query.type]: expected at least one defined value but got [undefined]"
}
  • 요청 : POST http://localhost:5601/internal/session/_find
{
    "page": 12222222,
    "perPage": 10000
}
  • 응답
{
    "statusCode": 500,
    "error": "Internal Server Error",
    "message": "Numeric value (122222210000) out of range of int (-2147483648 - 2147483647)\n at [Source: (org.elasticsearch.common.io.stream.ByteBufferStreamInput); line: 1, column: 61]: input_coercion_exception: [input_coercion_exception] Reason: Numeric value (122222210000) out of range of int (-2147483648 - 2147483647)\n at [Source: (org.elasticsearch.common.io.stream.ByteBufferStreamInput); line: 1, column: 61]"
}

Custom Plugin 만들기

Directory 구조

kibana.json
server/
  └── index.js
public/
  └── index.js

kibana.json

{
  "id": "customErrorMessage",
  "version": "1.0.0",
  "kibanaVersion": "7.17.23",
  "server": true,
  "ui": false,
  "requiredPlugins": [],
  "optionalPlugins": [],
  "owner": {
    "name": "subin"
  }
}
  • id는 무조건 camel case로 작성해야 함. camel case가 아닌 다른 형식으로 쓰면 Plugin "id" must be camelCase, but found: custom_error_message. 에러 발생
  • owner.name 도 필수 값. 미작성 시 Plugin manifest for "customErrorMessage" must contain an "owner" property, which includes a nested "name" property. 에러 발생
  • ui 관련 설정은 없으므로 false 설정 => public/index.js는 빈 파일로 생성하면 됨

server/index.js

  • statusCode가 400 이상일 때만 적용되도록 구성
  • 400 미만일 때는 기존 값 그대로 반환 (toolkit.next())
const { schema } = require('@kbn/config-schema');

class CustomErrorMessagePlugin {
    constructor(initializerContext) {
        this.initializerContext = initializerContext;
    }

    setup(core) {
        core.http.registerOnPreResponse((request, response, toolkit) => {
            if (response && response.statusCode >= 400) {

                let customMessage = '';

                if (response.statusCode >= 400 && response.statusCode < 500) {
                    customMessage = 'Bad Request: The request contains invalid data.';
                } else if (response.statusCode >= 500) {
                    customMessage = 'Internal Server Error: Something went wrong on the server.';
                }

                // Modify the response body
                const newResponseBody = {
                    statusCode: response.statusCode,
                    message: customMessage,
                    originalError: response.result, // Optionally include original error details
                };

                return toolkit.render({ body: newResponseBody });

            }

            return toolkit.next(); // Return without change
        });
    }

    start(core) {
        return {};
    }
    stop() {}
}

module.exports = {
    plugin: (initializerContext) => new CustomErrorMessagePlugin(initializerContext)
};

변경된 docker-compose 적용

docker-compose.yml

version: '3.7'
services:
  elasticsearch:
    image: docker.elastic.co/elasticsearch/elasticsearch:7.17.23
    container_name: elasticsearch
    environment:
      - discovery.type=single-node
      - bootstrap.memory_lock=true
      - "ES_JAVA_OPTS=-Xms1g -Xmx1g"
    ulimits:
      memlock:
        soft: -1
        hard: -1
    ports:
      - "9200:9200"
    volumes:
      - es_data:/usr/share/elasticsearch/data
    networks:
      - elastic

  kibana:
    image: docker.elastic.co/kibana/kibana:7.17.23
    container_name: kibana
    environment:
      - ELASTICSEARCH_HOSTS=http://elasticsearch:9200
    ports:
      - "5601:5601"
    volumes:
      - ./custom_kibana_plugin/custom_error_message:/usr/share/kibana/plugins
    networks:
      - elastic

volumes:
  es_data:
    driver: local

networks:
  elastic:
    driver: bridge
  • 추가된 부분은 volumes

실행 결과

400 응답

{
    "statusCode": 400,
    "message": "Bad Request: The request contains invalid data."
}

500 응답

{
    "statusCode": 500,
    "message": "Internal Server Error: Something went wrong on the server."
}

참고