반응형

출처: http://acc.giro.or.kr/secu_view.asp?seq=7887

 http://elven.kr/archives/361

 

윈도우 운영체제 기반의 피해시스템에서 공격자의 침투경로를 파악하기 위해서는 어떠한 정보가 필요할까요?
인터넷 기록 및 레지스트리 등을 확인 및 분석하여 악성코드에 어떻게 감염되었는지도 살펴볼 정보 중 하나이나,
가장 중요한 아티팩트는 윈도우 이벤트 로그라고 볼 수 있습니다.

이 이벤트 로그는 외부에서의 시스템  접속과 사용자 계정 설정 변경 등
침투/피해 시점 당시 발생하였던 다양한 정보를 저장하고 있으며 분석가는 이를 통해 보다 효율적인 접근이 가능합니다.

이번 포스트에서 다룰 내용은 분석 시 활용할 수 있는 로그 설명과 이벤트 ID 등 기초적인 내용이며,
실제 이벤트 로그의 내부 구조 및 활용 사례 등에 대한 심화 과정은 다음 포스팅에서 다룰 예정입니다.

그럼 이벤트 로그에 대해 하나씩 살펴보도록 하겠습니다.


 1. 윈도우 이벤트 로그?


이벤트 로그에는 윈도우에서 발생하는 하드웨어, 소프트웨어 및 시스템 문제에 대한 다양한 이벤트들이 기록됩니다.
다만 운영체제가 업그레이드 됨에 따라 버전별로 기록되는 형태와 경로가 조금씩 다른데요,

각 운영체제별 이벤트 로그 특징은 아래와 같습니다.
(운영체제를 그룹핑하여 Type으로 분류하였으며, 앞으로 설명드릴 내용 역시 역시 분류 기준으로 설명드리겠습니다)

  Type 1 (Windows 2000 / XP / 2003) Type 2 (Windows Vista / 2008 / 7)
주요 로깅 데이터 System, Security, Application System, Security, Application +
로그 저장 형태 Binary Binary , XML
로그 확장자명 .evt .evtx
저장 경로 \Windows\System32\Config \Windows\System32\winevt\Logs

바이너리 형태로 저장된 이벤트 로그를 확인하기 위해서는
데이터를 해석하고 알아볼 수 있게 해주는 별도의 프로그램이 필요한데요,
대표적으로 윈도우에서 기본으로 제공하는 ‘이벤트 뷰어’가 있습니다.

이 도구는 [제어판] → [관리도구]에 위치하고 있으며,
[실행] 창에 eventvwr.msc 를 입력하여 바로 실행할 수도 있습니다.

01
윈도우8에서는 아래와 같은 방법으로 이벤트 뷰어를 실행할 수 있습니다.
먼저 윈도우 화면에서 윈도우키와 w 키를 함께 누르게 되면 검색창이 실행되는데요,
이 검색창에 ev 를 입력 후 실행하시게 되면 이벤트 뷰어 화면이 출력되는 것을 보실수 있습니다.

06
주요 이벤트별 특징은 다음과 같습니다.

1) 응용프로그램 로그

윈도우에서 API를 사용하는 응용프로그램이 중요한 이벤트를 알리고, 활동 내역을 기록합니다.

예로 안티바이러스 제품의 경우 악성코드 탐지 및 업데이트를,
일반 응용프로그램은 활성화 또는 비활성화, 성공 여부 등의 정보를 기록합니다.

응용프로그램 로깅의 경우 응용프로그램에 의해 제어되기 때문에,
이벤트로그 역시 응용프로그램 개발자에 의해 정의됩니다.
모든 응용프로그램이 이벤트 로그를 생성하지는 않는 점 참고하시기 바랍니다.


2) 시스템 로그

윈도우의 시스템 운영과 유지에 관련된 대부분의 정보가 이 곳에 저장됩니다.
주로 하드웨어 장치나 드라이버 오류 정보 및 동작 여부 등이 기록되며,
윈도우의 시스템 진단과 문제점을 해결하기 위해 사용됩니다.

새로운 서비스의 등록, 또는 시작 및 중단 등의 기록과 장치 드라이버가 로드되는 내역 등이 저장되므로
사고 분석에서 관련 정보의 활용이 필요합니다.
여기에서 주의 깊게 살펴보셔야 할 정보는 시간 변경, 시스템 시작/종료, 서비스 시작/종료/실패 등이 있습니다.


3) 보안 로그

시스템 로그온, 파일 접근, 인증, 계정 생성, 권한 사용 등에 따른 이벤트와 보안과 관련된 항목들이 저장됩니다.
어떤 사용자 계정이 사용되었는지, 어떤 컴퓨터에 접근했는지 또한 어떤 파일에 접근했는지에 대한
관련정보가 포함되어 있어 사고 분석에 있어 가장 중요한 로그라 할 수 있습니다.


이외에도 OS 구성에 따라 디렉토리 서비스, 파일 복제 서비스, DNS 서버 로그 등이 추가될 수 있습니다.

 


2. 이벤트 로그 설정 확인


이벤트 로그의 설정을 확인하는 방법은 크게 두 가지로
레지스트리를 이용하는 방법, 이벤트 뷰어를 이용하는 방법이 있습니다.

1) 레지스트리를 통한 확인

[실행] → ‘regedit’ 입력 → ‘HKLM\System\CurrentControlSet\Services\EventLog’ 에서 설정 값을 확인 및 수정할 수 있습니다.

02

AutoBackupLogFIles 로그파일 자동 백업 여부
File 이벤트 로그 파일의 저장 경로
MaxSize 이벤트 로그 파일의 최대 크기
RestrictGuestAccess 게스트 접근 제한 여부
Retention 로그가 최대크기에 도달할 때 해당 시간보다 더 오래된 이벤트만 덮어쓰기
기본값은 604,800초 = 7일로 설정되어 있음
Source 로그 파일에 기록을 허가받은 프로그램들의 목록

2) 이벤트 뷰어를 통한 확인

이벤트뷰어에서 각 이벤트로그에 대한 속성을 변경할 수 있으며,
설정을 변경하고 싶은 이벤트에 우클릭하여 나오는 메뉴에서 ‘속성’을 클릭합니다.

03
속성에서 이벤트 로그 파일의 최대크기를 지정해 줄 수 있으며, 로그 관리에 필요한 설정을 할 수 있습니다.

04


3. 이벤트 로그 구성


이벤트 뷰어를 통해 아래와 같이 로그에 저장된 이벤트를 확인할 수 있습니다.

05
각 이벤트 엔트리의 헤더에는 다음과 같은 이벤트 정보가 포함됩니다.

 날짜  이벤트 발생 날짜
 시간  이벤트 발생 시간
 사용자  이벤트가 발생하였을 때 로그온 되어 있는 사용자의 이름
 컴퓨터  이벤트가 발생한 컴퓨터의 이름
 이벤트 ID  이벤트 ID를 통해 어떤 이벤트가 발생하였는지 식별
 원본  프로그램, 시스템 구성요소 또는 큰 프로그램의 개별 구성 요소에 대한 이름
 종류  오류, 경고, 정보, 성공감사, 실패감사 중 하나
 범주  이벤트 원본에 따른 이벤트 분류이며, 보안 로그에 주로 사용

또한 이벤트 종류는 다음과 같이 5가지로 분류됩니다.

정보 응용 프로그램, 드라이버 또는 서비스와 같은 작업의 성공적인 작동을 설명하는 이벤트
예를 들어 네트워크 드라이버가 성공적으로 로드된 경우 정보 이벤트가 기록됨
경고 매우 중요하지는 않으나 앞으로 문제가 발생할 수 있는 가능성이 있음을 나타내는 이벤트
예를 들어 디스크 공간이 부족할 경우 경고 메세지가 기록됨
오류 중요한 작업의 실패와 같이 문제를 설명하는 이벤트로 데이터 손실이나 기능 손실을 포함
예를 들어 시작하는 동안 서비스가 로드되지 않을 경우 오류 이벤트가 기록됨
성공감사 보안 이벤트의 성공적인 감사 완료를 설명하는 이벤트
예를 들어 사용자가 컴퓨터에 로그온하면 성공감사 이벤트가 기록됨
실패감사 보안 이벤트 감사가 완료되지 않았음을 설명하는 이벤트
예를 들어 사용자가 네트워크 드라이버에 액세스 할 수 없을 때 실패감사 이벤트가 기록됨


4. 이벤트 로그 감사 정책


윈도우 감사 정책은 곧 로그 정책이라고 볼 수 있습니다.
감사 설정을 구성하지 않으면 보안과 관련하여 어떠한 일이 발생하였는지 확인하기 어려운 문제가 발생합니다.

정책을 통해 개체 액세스, 로그온/로그오프, 감사 정책 설정 변경 등의 보안 로그를 기록하며,
지정한 이벤트 범주의 사용자나 시스템 동작을 기록하도록 정책 설정이 가능합니다.

로컬보안설정을 통해 감사 정책을 확인하기 위해서는
“[시작] → [제어판] → [관리도구] → [로컬 보안 정책] → [로컬 정책] → [감사 정책]” 선택 후,
각 감사를 클릭하여 ‘성공’, ‘실패’에 관한 감사를 설정할 수 있습니다.

05
레지스트리를 통해서도 감사 정책을 확인할 수가 있는데요,
저장 및 관리 되는 위치는 아래와 같습니다.

Security Hive – Policy\PolAdtEv 


아래 내용은 Windows Vista/2008/7 의 감사정책 구성과 기본 값입니다.

 

e1

출처 : http://www.kazamiya.net/files/PolAdtEv_Structure_en_rev2.pdf

e0

출처 : http://www.kazamiya.net/files/PolAdtEv_Structure_en_rev2.pdf


5.보안감사 이벤트 설명


기존 Evt 형태의 이벤트 로그에서 운영체제의 업그레이드와 함께 새로운 이벤트 로그 Evtx가 등장합니다.
실제 로그 파일의 헤더 및 구성도 다수 변경이 이루어졌는데요,
상세한 내용은 차후에 다시 설명드리기로 하며 이 포스트에서는 이벤트 ID에 대해 다루어 보겠습니다.

이벤트 로그에서는 이벤트 행위에 대해 특정 숫자 값을 지정하여 관리하고 있습니다.
이것이 이벤트 로그에 있어 가장 중요한 이벤트 ID 인데요, 이 값 역시 Vista 이전과 이후로 나뉘어 상이하게 변경됩니다.
가장 손쉽게 매칭할 수 있는 방법은 Evt 사용 이벤트 ID 값에 4096 값을 더하면 Evtx 형태의 이벤트 ID값이 되며,
실제 상당수 이벤트가 이 조건을 만족합니다.

개체 액세스 검사
파일, 폴더, 레지스트리 등 개체에 액세스 하는 사용자의 이벤트를 감시할지 여부를 결정합니다.
개체에 대한 접근 성공 여부를 감사하며, 개체 액세스 감사를 실행하면 보안 로그에 관련 로그가 기록됩니다.

 Type 1 – 이벤트 ID  Type 2 – 이벤트 ID 내용
 560 4656 개체에 대한 접근 허가
 562 4658 개체에 대한 핸들 닫힘 – 이벤트 종료
 563 4659 삭제할 목적으로 개체에 접근
 564 4660 보호된 개체의 삭제

계정 관리 감사
컴퓨터의 각 계정 관리 이벤트를 감사할지 여부를 결정합니다.
해당 이벤트의 예로는 사용자 계정 및 그룹 생성/수정/삭제, 암호 설정 및 변경 등이 해당됩니다.

 Type 1 – 이벤트 ID  Type 2 – 이벤트 ID 내용
624 4720 사용자 계정 생성
625   사용자 계정 유형 변경
626 4722 사용할 수 있는 사용자 계정
627 4723 암호 변경 시도
628 4724 사용자 계정 암호 설정
629 4725 사용하지 않는 사용자 계정
630 4726 삭제된 사용자 계정
636 4732 보안 사용 로컬 그룹 구성원 추가
637 4733 보안 사용 로컬 그룹 구성원 제거
642 4738 변경된 사용자 계정
643   변경된 도메인 정책
644 4740 사용자 계정 잠김

계정 로그온 이벤트 감사
계정 유효성을 검사하는 컴퓨터가 아닌 다른 컴퓨터에서의 로그온/로그오프 감사 여부를 결정합니다.
해당 감사 항목은 침입 감지에 유용하게 사용할 수 있습니다.

 Type 1 – 이벤트 ID  Type 2 – 이벤트 ID 내용
680 4776 로그인 성공 정보
681 4777 로그인 실패 정보

로그인 이벤트 감사
감사 이벤트를 기록하는 컴퓨터에 대해 사용자 로그온/로그오프 또는 네트워크 연결의 각 인스턴스 감사 여부를 결정합니다.
성공 감사는 로그온 시도가 성공할 때 생성되며, 이 항목은 침입 감지에 유용하게 사용할 수 있습니다.
해당 감사는 계정 로그온 이벤트 감사 보다 상제 정보를 로깅합니다.

 Type 1 – 이벤트 ID  Type 2 – 이벤트 ID 내용
528 4624 성공적인 로그인
529 4625 알 수 없는 계정이나 잘못된 암호를 이용한 로그인 시도
530   로그인 시 허용 시간 이내에 로그인 실패
531   사용지 금지된 계정을 통한 로그인 시도
532   사용 기간이 만료된 계정을 통한 로그인 시도
533   로그인이 허용되지 않은 계정을 통한 로그인 시도
534   허용되지 않은 로그인 유형을 통한 로그인 시도
535   암호 사용 기간 만료
537   위의 사항에 해당되지 않으나 로그인에 실패한 경우
538 4634 로그오프
539   로그인하려는 계정이 잠겨 있음
540   로그인 성공

프로세스 추적 감사
프로세스 활성화/종료 및 간접적 개체 액세스 등의 이벤트에 대한 자세한 추적 정보를 감사할지 여부를 결정합니다.
윈도우 XP SP2 및 서버 2003 SP1 이상에서 프로세스 추적 감사를 사용하면 윈도우 방화벽 구성 요소의 작동 모드 및 상태에 대한 정보도 기록합니다.

 Type 1 – 이벤트 ID  Type 2 – 이벤트 ID 내용
592 4688 새 프로세스 생성
593 4689 프로세스 종료
594 4690 개체에 대한 힌트의 중복
595 4691 개체에 대한 간접적인 접근

시스템 이벤트 감사
컴퓨터를 다시 시작하거나 종료할 경우 또는 컴퓨터 보안이나 보안 로그에 영향을 주는 이벤트가 발생할 경우 이를 감사할지 여부를 결정합니다.
이러한 이벤트는 매우 중요하기 때문에 조직의 모든 컴퓨터에 대하여 이 정책 설정을 [사용] 설정할 필요가 있습니다.

 Type 1 – 이벤트 ID  Type 2 – 이벤트 ID 내용
512 4608 윈도우 시동
513 4609 윈도우 종료
514 4610 LSA (Local Security Authority) 인증 패키지 로드
515 4611 신뢰할 수 있는 로그인 프로세스가 LSA로 등록
516 4612 저장 공간의 부족으로 인해 보안 이벤트 메세지 손실
517   보안 로그 삭제

로그온 유형에 따라 아래와 같이 분류할 수 있습니다.
이 중에서 “로그온 유형 10” 의 경우 원격 접속 이벤트로 사고 분석 시 가장 빈번히 활용됩니다.

로그온 유형 2 대화식 콘솔에서 키보드로 로그인 (KVM 포함)
로그온 유형 3 네트워크 네트워크를 통한 원격 로그인 (파일 공유, IIS 접속 등)
로그온 유형 4 스케쥴 스케쥴에 등록된 배치 작업 실행 시 미리 설정된 계정 정보로 로그인
로그온 유형 5 서비스 서비스가 실행될 때 미리 설정된 계정 정보로 로그인
로그온 유형 7 잠금해제 화면보호기 잠금 해제시
로그온 유형 8 네트워크 유형 3과 비슷하나 계정 정보를 평문으로 전송할 때 발생
로그온 유형 9 새자격 실행(RunAS)에서 프로그램 실행 시 /netonly 옵션을 줄 때
로그온 유형 10 원격 대화식 터미널 서비스, 원격 접속, 원격지원으로 로그인
로그온 유형 11 캐시된 캐화식 PC에 캐시로 저장된 암호로 자동 입력 로그인

 


6. 참고


Security Audit Events for Windows 7 and Windows Server 2008 R2
http://www.microsoft.com/en-us/download/details.aspx?id=21561

Description of security events in Windows 7 and in Windows Server 2008 R2
https://support.microsoft.com/ko-kr/kb/977519

윈도우 이벤트 로그 분석가이드 [비공개 자료]

Windows XP에서 이벤트 뷰어의 이벤트 로그를 보고 관리하는 방법
https://support.microsoft.com/ko-kr/kb/308427

EVTX and Windows Event Logging
http://www.sans.org/reading-room/whitepapers/logging/evtx-windows-event-logging-32949

반응형
반응형

https://www.digitalocean.com/community/tutorials/how-to-install-elasticsearch-logstash-and-kibana-4-on-ubuntu-14-04




반응형
반응형

There are a few concepts that are core to Elasticsearch. Understanding these concepts from the outset will tremendously help ease the learning process.

아래의 몇가지 개념들을 이해한다면 매우 쉽게 시작할 수 있다.

Near Realtime (NRT)

Elasticsearch is a near real time search platform. What this means is there is a slight latency (normally one second) from the time you index a document until the time it becomes searchable.

Elasticsearch는 거의 실시간 플랫폼이다. 이 말은 검색하는 시간 만큼 늦어지지만 거의 실시간 이라고 할 수 있다.

 

Cluster

A cluster is a collection of one or more nodes (servers) that together holds your entire data and provides federated indexing and search capabilities across all nodes. A cluster is identified by a unique name which by default is "elasticsearch". This name is important because a node can only be part of a cluster if the node is set up to join the cluster by its name.

Make sure that you don’t reuse the same cluster names in different environments, otherwise you might end up with nodes joining the wrong cluster. For instance you could use logging-dev, logging-stage, and logging-prod for the development, staging, and production clusters.

Note that it is valid and perfectly fine to have a cluster with only a single node in it. Furthermore, you may also have multiple independent clusters each with its own unique cluster name.

Cluster는 하나 , 더 많은 노드들로 부터 오는 데이터를 하나로 묶을 수 있도록 해준다. 그리고 인덱싱을 여러 노드들을 합쳐서 제공하므로 모든 노드들을 검색 할 수 있게 된다.  Cluster 는 default로 "elasticsearch"라고 정의 된다. 이것이 왜 중요하냐면, 노드들은 cluster이름을 통해 조인할 수 있기 때문이다. Cluster는 다른 이름으로 정의 할 수 있다. 

Node

A node is a single server that is part of your cluster, stores your data, and participates in the cluster’s indexing and search capabilities. Just like a cluster, a node is identified by a name which by default is a random Marvel character name that is assigned to the node at startup. You can define any node name you want if you do not want the default. This name is important for administration purposes where you want to identify which servers in your network correspond to which nodes in your Elasticsearch cluster.

A node can be configured to join a specific cluster by the cluster name. By default, each node is set up to join a cluster named elasticsearch which means that if you start up a number of nodes on your network and—assuming they can discover each other—they will all automatically form and join a single cluster named elasticsearch.

In a single cluster, you can have as many nodes as you want. Furthermore, if there are no other Elasticsearch nodes currently running on your network, starting a single node will by default form a new single-node cluster named elasticsearch.

노드는  cluster의 부분이며, 데이터를 저장하고, 클러스터의 인덱싱과 search 기능을 제공하는 서버이다. 클러스터 처럼 노드 역시 이름을 정할 수 있다.

Index

An index is a collection of documents that have somewhat similar characteristics. For example, you can have an index for customer data, another index for a product catalog, and yet another index for order data. An index is identified by a name (that must be all lowercase) and this name is used to refer to the index when performing indexing, search, update, and delete operations against the documents in it.

In a single cluster, you can define as many indexes as you want.

 

Type

Within an index, you can define one or more types. A type is a logical category/partition of your index whose semantics is completely up to you. In general, a type is defined for documents that have a set of common fields. For example, let’s assume you run a blogging platform and store all your data in a single index. In this index, you may define a type for user data, another type for blog data, and yet another type for comments data.

Document

A document is a basic unit of information that can be indexed. For example, you can have a document for a single customer, another document for a single product, and yet another for a single order. This document is expressed in JSON (JavaScript Object Notation) which is an ubiquitous internet data interchange format.

Within an index/type, you can store as many documents as you want. Note that although a document physically resides in an index, a document actually must be indexed/assigned to a type inside an index.

Shards & Replicas

An index can potentially store a large amount of data that can exceed the hardware limits of a single node. For example, a single index of a billion documents taking up 1TB of disk space may not fit on the disk of a single node or may be too slow to serve search requests from a single node alone.

To solve this problem, Elasticsearch provides the ability to subdivide your index into multiple pieces called shards. When you create an index, you can simply define the number of shards that you want. Each shard is in itself a fully-functional and independent "index" that can be hosted on any node in the cluster.

Sharding is important for two primary reasons:

  • It allows you to horizontally split/scale your content volume
  • It allows you to distribute and parallelize operations across shards (potentially on multiple nodes) thus increasing performance/throughput

The mechanics of how a shard is distributed and also how its documents are aggregated back into search requests are completely managed by Elasticsearch and is transparent to you as the user.

In a network/cloud environment where failures can be expected anytime, it is very useful and highly recommended to have a failover mechanism in case a shard/node somehow goes offline or disappears for whatever reason. To this end, Elasticsearch allows you to make one or more copies of your index’s shards into what are called replica shards, or replicas for short.

Replication is important for two primary reasons:

  • It provides high availability in case a shard/node fails. For this reason, it is important to note that a replica shard is never allocated on the same node as the original/primary shard that it was copied from.
  • It allows you to scale out your search volume/throughput since searches can be executed on all replicas in parallel.

To summarize, each index can be split into multiple shards. An index can also be replicated zero (meaning no replicas) or more times. Once replicated, each index will have primary shards (the original shards that were replicated from) and replica shards (the copies of the primary shards). The number of shards and replicas can be defined per index at the time the index is created. After the index is created, you may change the number of replicas dynamically anytime but you cannot change the number shards after-the-fact.

By default, each index in Elasticsearch is allocated 5 primary shards and 1 replica which means that if you have at least two nodes in your cluster, your index will have 5 primary shards and another 5 replica shards (1 complete replica) for a total of 10 shards per index.

Note

Each Elasticsearch shard is a Lucene index. There is a maximum number of documents you can have in a single Lucene index. As of LUCENE-5843, the limit is 2,147,483,519 (= Integer.MAX_VALUE - 128) documents. You can monitor shard sizes using the _cat/shards api.

반응형
반응형

출처: http://asuraiv.blogspot.kr/2015/08/elasticsearch-logstash-elasticsearch.html

 

 

Elasticsearch output Plugin

Elasticsearch의 output 플러그인은 'node', 'transport', 'http' 의 3가지 프로토콜이 있다.
여기서는 Elasticsearch 클러스터의 9200번포트로 직접 접속하여 데이터를 전송하는 방식인 'http' 프로토콜을 통해서, Logstash와 연동해보도록 한다.


1. 기초

아래와 같은 클러스터 구조가 있다.









일단 간단하게 stdin 으로 json 데이터를 입력받고, Elasticsearch에 색인하는 작업부터 해보겠다.

logstash.conf 파일은 아래와 같이 작성한다.

input {
        stdin {
                codec => json
        }
}

output {
        elasticsearch {
                host => "localhost"
                index => "school"
                index_type => "students"
                protocol => "http"
        }
        stdout {
                codec => rubydebug { }
        }
}

위와 같이 output 설정에 elasticsearch { } 를 작성하고, 중괄호 안에 각종 설정을 세팅한다. protocol은 'http' 로 작성한다. 이 protocol을 생략하게되면 default 설정인 'node'로 세팅되는데, 이 프로토콜은 로그스태쉬를 하나의 node로 실행시켜, 색인작업을 하고자 하는 elasticsearch cluster에 합류시킨다.

일단 지금은 http 프로토콜을 사용한다 host, index, index_type 등의 설정은 localhost의 elasticsearch 서버로, shcool이라는 인덱스의 students 타입에 데이터를 색인 시키는 설정이다.

입력된 값들이 제대로 인식이 되었는지 확인하기 위해서, stdout 설정도 추가하였다.

실행시켜본다.

./logstash -f logstash.test.conf
Logstash startup completed

그리고 { "class" : "A", "name" : "john" } 를 입력해보자

{ "class" : "A", "name" : "john" } ## 입력
{ ## 여기서부터 stdout rubydebug codec에 의해 출력되는 부분.
         "class" => "A",
          "name" => "john",
      "@version" => "1",
    "@timestamp" => "2015-08-07T07:11:41.975Z",
          "host" => "cweb02.ami",
     "@metadata" => {
        "retry_count" => 0
    }
}

출력을 보니 제대로 색인이 된것 같다.
head 플러그인 화면으로 가서 확인해보자.

위 logstash.conf 파일에서 설정해 준 대로, 'school' 인덱스와 'students' 타입이 동적으로 생성되며, 색인이 성공했음을 확인 할 수 있다.


2. Template 사용

템플릿을 사용하여 미리 index와 type의 스키마를 정해놓고 데이터를 색인 할 수 있다.
아래와 같이 템플릿을 정의하자.
curl -XPUT 'localhost:9200/_template/school?pretty' -d '{
    "template" : "school",
    "settings" : { "index.refresh_interval" : "5s" },
    "mappings" : {
        "students" : {
            "properties" : {
                "class" : { "type" : "string", "store" : "yes", index : "not_analyzed" },
                "name" : { "type" : "string",  "store" : "yes" },
                "address" : { "type" : "string",  "store" : "yes" }
            }
        }
    }
}'
'students' 라는 인덱스 템플릿을 하나 생성하였다. 인덱스 템플릿에 관한 자세한 내용은 아래의 doc 문서를 확인해보자

https://www.elastic.co/guide/en/elasticsearch/reference/1.6/indices-templates.htm

템플릿을 생성하였으면, Logstash가 해당 템플릿을 사용하여 색인을 할 수 있도록 설정해 놓아야 한다. 바로 아래와 같이 설정한다.
elasticsearch {
                host => "localhost"
                index => "school"
                index_type => "students"
                protocol => "http"
                template_name => "school" # 바로 여기 설정
        }
}

자, 다시 Logstash를 실행시키고 { "class" : "A", "name" : "iron man", "address" : "newyork" } 와 같은 데이터를 입력한다

{ "class" : "A", "name" : "iron man", "address" : "newyork" }
{
         "class" => "A",
          "name" => "iron man",
       "address" => "newyork",
      "@version" => "1",
    "@timestamp" => "2015-08-07T07:50:33.537Z",
          "host" => "cweb02.ami",
     "@metadata" => {
        "retry_count" => 0
    }
}

템플릿대로 document가 색인되었는지 head플러그인에서 확인해보자.

아래는 템플릿을 사용하지 않았을때와 사용했을때의 인덱스 메타데이터의 차이이다.

1) 템플릿을 미적용한 경우





















Elasticsearch의 기본 idea는 realtime 으로 document를 색인하는것이다. 따라서 동적으로 인덱스와 타입이 생성된다. 위의 경우는 정해진 스키마없이 동적으로 인덱스와 타입이 생성된 경우이며 dynamic_templates 라는 기본 템플릿이 적용된다.

2) 템플릿을 적용한 경우





















위의 경우는 템플릿을 적용한 경우이다. 위에서 생성한 템플릿의 필드설정대로, 'class' 필드는 index 설정이 'not_analyzed'로 되어있다. 템플릿이 정상적으로 적용되어 데이터가 색인되었다는 증거다.

반응형

+ Recent posts