5.7 Create a maintenance endpoint

고준영·2021년 11월 22일
0

Nodebestpractices

목록 보기
1/16
post-thumbnail

Create a maintenance endpoint



One Paragraph Explainer

A maintenance endpoint is a highly secure HTTP API that is part of the app code and its purpose is to be used by the ops/production team to monitor and expose maintenance functionality. For example, it can return a heap dump (memory snapshot) of the process, report whether there are some memory leaks and even allow to execute REPL commands directly. This endpoint is needed where the conventional DevOps tools (monitoring products, logs, etc) fail to gather some specific type of information or you choose not to buy/install such tools. The golden rule is using professional and external tools for monitoring and maintaining the production, these are usually more robust and accurate. That said, there are likely to be cases where the generic tools will fail to extract information that is specific to Node or to your app – for example, should you wish to generate a memory snapshot at the moment GC completed a cycle – few npm libraries will be glad to perform this for you but popular monitoring tools will likely miss this functionality. It is important to keep this endpoint private and accessibly only by admins because it can become a target of a DDOS attack.



Code example: generating a heap dump via code

const heapdump = require('heapdump');

// Check if request is authorized 
function isAuthorized(req) {
    // ...
}

router.get('/ops/heapdump', (req, res, next) => {
    if (!isAuthorized(req)) {
        return res.status(403).send('You are not authorized!');
    }

    logger.info('About to generate heapdump');

    heapdump.writeSnapshot((err, filename) => {
        console.log('heapdump file is ready to be sent to the caller', filename);
        fs.readFile(filename, 'utf-8', (err, data) => {
            res.end(data);
        });
    });
});



Getting your Node.js app production ready (Slides)

Getting your Node.js app production ready (Video)


‘유지 관리용 엔드 포인트’를 따로 만들어라



한문단 설명

유지관리용 엔트포인트는 앱 코드의 일부분이며 매우 안전한 HTTP API이며, 이것의 목적은 운영/프로적션 팀에서 유지 관리 기능을 모니터링하고 노출하는데 있다.
예를 들어 프로세스의 heap dump (memory snapshot)를 반환하고 메모리 누수가 있는지 보고하며, REPL 명령을 직접 실행할 수 있다.
* heap dump -> nodejs 확장 모듈이며, 서버 메모리 스냅샷을 추출할 수 있는 기능 제공하며 이 스냅샷을 heapdump라고 한다. heapdump는 어떤 객체들이 메로리를 반복적으로 사용하는지 확인 가능
* REPL Read, Eval, Print, Loop(읽고, 평가하고, 출력하고, 반복하고)
이러한 엔드포인트는 기존 DevOps tools(모니터링 제품, 로드 등)이 특정 유형의 정보를 수집하지 못하거나 당신이 이러한 도구를 사용하지 않는 것으로 결정한 경우에 필요하다.
황금률은 모니터링과 제품유지에 전문적이고 외부적인 도구를 사용하는 것이며, 이것은 일반적으로 정확하고 강력하다.
즉, 일반적인 도구가 노드 또는 앱의 특정한 정보를 추촐하지 못하는 경우가 있을 수 있다. - 예를들어 당신이 GC(가비지 컬렉션) 사이클을 완료하는 순간 메모리 스냅샷을 생성하기를 원한다면, 소수의 npm 라이브러리는 이러한 작업을 수행하지만 인기있는 모니터링 도구는 이 기능을 놓칠 가능성이 높다.
유지관리용 엔드포인트가 DDOS 공격의 대상이 될 수 있으므로 관리자만 접근할 수 있도록 유지하는것이 중요하다.
* 유지관리용 endpoint는 파일을 생성하고 로그를 남기는 등의 작업을 하고 많은 요청이 있으면 과부화에 취약할 수 있다. 따라서 권한을 설절 및 확인해주어야 한다.



코드 예시: 코드를 통한 heap dump 생성

const heapdump = require('heapdump');

// 인가된 사용자 확인/
function isAuthorized(req) {
    /// .../
}

router.get('/ops/heapdump', (req, res, next) => {
    /if/ (!isAuthorized(req)) {
        /return/ res.status(403).send('You are not authorized!');
    }

    logger.info('About to generate heapdump');

    heapdump.writeSnapshot((err, filename) => {
        console.log('heapdump file is ready to be sent to the caller', filename);
        fs.readFile(filename, "utf-8", (err, data) => {
            res.end(data);
        });
    });
});



권장 리소스

Node.js 앱 프로덕션 준비하기 (슬라이드)

Node.js 앱 프로덕션 준비하기 (비디오)

profile
코드짜는귤🍊 풀스택을 지향하는 주니어 개발자 입니다🧡

0개의 댓글