1. Server

서버는 ap-southeast-1(singapore)에서 t3a.nano, ubuntu 20.04 이미지로 생성하였습니다.

X-Ray에 필요한 서버 1대를 생성합니다.

생성한 서버에 SSH로 접속합니다.

Ubuntu comes with ABSOLUTELY NO WARRANTY, to the extent permitted by
applicable law.

To run a command as administrator (user "root"), use "sudo <command>".
See "man sudo_root" for details.

ubuntu@ip-172-31-18-253:~$

EC2 서버에 Instance Profile을 추가하여 X-Ray 서비스 권한을 부여합니다.

서비스에 모든 권한을 주는 것은 바람직하지 않지만, 테스트를 위하여 AWSXrayFullAccess 정책을 EC2InstanceRole 역할에 연결하였습니다.

2. Nodejs App

2.1 Nodejs 설치

Nodejs v15.14 설치를 합니다.

# Using Ubuntu
curl -fsSL https://deb.nodesource.com/setup_15.x | sudo -E bash -
sudo apt-get install -y nodejs
2.2 Sample App 설치

X-Ray SDK for Node.js Sample App

필요한 샘플 코드는 아래의 링크에서 받을 수 있습니다.

링크

Nodejs 샘플 코드를 서버로 내려받습니다.

ubuntu@ip-172-31-18-253:~$ git clone https://github.com/aws-samples/aws-xray-sdk-node-sample.git
Cloning into 'aws-xray-sdk-node-sample'...
remote: Enumerating objects: 13, done.
remote: Counting objects: 100% (13/13), done.
remote: Compressing objects: 100% (13/13), done.
remote: Total 13 (delta 1), reused 7 (delta 0), pack-reused 0
Unpacking objects: 100% (13/13), 5.79 KiB | 1.45 MiB/s, done.

내려받은 폴더로 이동하여 패키지를 설치합니다.

ubuntu@ip-172-31-18-253:~$ cd aws-xray-sdk-node-sample/
ubuntu@ip-172-31-18-253:~/aws-xray-sdk-node-sample$ npm install
2.3 어플리케이션 테스트

배포 전 index.js 파일을 수정합니다.

vi index.js
// index.js
// 'us-west-2' -> 'ap-southeast-1'으로 변경
AWS.config.update({region: process.env.DEFAULT_AWS_REGION || 'ap-southeast-1'});

수정이 끝나면, 정상적으로 동작하는지 테스트를 진행합니다

ubuntu@ip-172-31-18-253:~/aws-xray-sdk-node-sample$ node index.js
Example app listening on port 3000!

로컬에서 <Your Public IP>:3000으로 접속하여 페이지가 정상적으로 나오는지 확인합니다.

3. X-Ray

3.1 X-Ray daemon 설치

Ubuntu 20.04 기준으로 작성하였으며, X-Ray는 기본적으로 UDP 2000포트와 통신합니다.

서버에 X-Ray daemon을 설치합니다.

curl https://s3.us-east-2.amazonaws.com/aws-xray-assets.us-east-2/xray-daemon/aws-xray-daemon-3.x.deb -o xray.deb
sudo apt-get install -y xray.deb

Selecting previously unselected package xray.
(Reading database ... 63728 files and directories currently installed.)
Preparing to unpack xray.deb ...
Preparing for install
Failed to stop xray.service: Unit xray.service not loaded.
Unpacking xray (3.3.1) ...
Setting up xray (3.3.1) ...
Starting xray daemon
3.2 활동 생성

<Your Public IP>:3000에 접속하여 첫번째, 두번째 here을 여러번 눌러줍니다. 

(세번째 here은 추가 설정이 필요하여 아직 동작하지 않습니다.)

3.3 X-Ray 확인

AWS console로 돌아와 X-Ray 서비스 맵을 확인합니다.

이어서 X-Ray Trace를 확인합니다.

4. X-Ray Code

4.1 Sample App Code

X-Ray와 관련된 코드를 먼저 걷어내고 살펴봅니다.  

Nodejs 웹 프레임워크인 express로 웹 서버를 생성하는 코드입니다. 최상위 페이지(/)로 접속하면 2.3 마지막 사진에서 봤던 것과 같은 index.html을 보여주게 됩니다. 

const express = require('express');

const app = express();
const port = 3000;

app.get('/', (req, res) => {
 res.sendFile(`${process.cwd()}/index.html`);
});

여기에 X-Ray 코드를 어떻게 추가하는지 알아봅니다.

X-Ray는 어플리케이션이 AWS 서비스를 호출하는 것을 추적(Trace)합니다.

모든 AWS SDK client를 추적(instrument)할 때는 AWSXRay.captureAWS를 사용합니다.

마이크로서비스 또는 외부 HTTP API를 호출하는 것을 추적합니다. 

Express로 들어오는(Incoming) 호출을 추적합니다. Express 미들웨어를 사용하여 각 요청마다 Segment를 생성할 수 있습니다.

Segment 이름은 서비스 맵에서 어플리케이션 식별자입니다. 고정된 이름을 사용하여도 되며, 요청에 따라 변하는 이름을 사용할 수도 있습니다.

현재 Segment 또는 subsegment를 참조합니다.

Segment는 작업 단위로 데이터를 나눌 수 있습니다. 각각 나눠진 Segment는 Subsgment라고 부릅니다.

Subsgment는 요청에 대한 자세한 내용과 함께 세분화된 시간 정보를 포함합니다.

앞서 참조한 Segment에 새로운 Subsegment를 추가합니다.

비동기 요청이 완료되면, Callback 함수 내에서 반드시 Subsegment를 close합니다.

const AWSXRay = require('aws-xray-sdk');
const XRayExpress = AWSXRay.express;
const express = require('express');

// Capture all AWS clients we create
const AWS = AWSXRay.captureAWS(require('aws-sdk'));
AWS.config.update({region: process.env.DEFAULT_AWS_REGION || 'ap-southeast-1'});

// Capture all outgoing https requests
AWSXRay.captureHTTPsGlobal(require('https'));
const https = require('https');

const app = express();
const port = 3000;

app.use(XRayExpress.openSegment('SampleSite'));

app.get('/', (req, res) => {
  const seg = AWSXRay.getSegment();
  const sub = seg.addNewSubsegment('customSubsegment');
  setTimeout(() => {
    sub.close();
    res.sendFile(`${process.cwd()}/index.html`);
  }, 500);
});
[AWS] X-Ray 첫걸음