'elasticsearch'에 해당되는 글 420건

  1. 2020.05.25 [Filebeat] setup.ilm & setup.template 잘 쓰려면.
  2. 2020.04.08 [Elasticsearch] UTC 를 사용 하는 이유.
  3. 2020.04.07 [Kibana] Visualize Metric JSON Input 예제
  4. 2020.04.07 [Elasticsearch] Docker Compose 실행 시 permission denied
  5. 2020.04.03 [Elastic] Elasticsearch, Metricbeat, Docker Compose 삽질.
  6. 2020.04.03 [Elasticsearch] Index Lifecycle Management 실행 주기
  7. 2020.04.03 [Elasticsearch] Index 생성 시 Name Pattern
  8. 2020.04.02 [Elasticsearch] Docker Compose 구성 하기
  9. 2020.04.01 [Elasticsearch] Docker Compose 구성 시 주의 사항.
  10. 2020.03.27 [Elasticsearch] Single node 실행

[Filebeat] setup.ilm & setup.template 잘 쓰려면.

Elastic/Beats 2020. 5. 25. 17:09

가끔 설정은 yml 에 잘 했는데 안될 때가 있습니다.

이게 어디에서 뭘로 했느냐에 따라 다른데요.

 

보통 beats 를 이용할 경우 자동으로 alias 생성 및 설정이 됩니다.

이 경우 elasticsearch 에서 동일하게 사용 하기 위한 ilm 과 template 설정을 하게 되면 동작이 잘 안되는 경우가 있는데요.

 

큰 차이는 is_write_index 설정 때문 입니다.

뭐 이것도 경우에 따라 다르게 나올 수 있지만 일반적이라면 저 설정 때문이다 생각 하시면 됩니다.

 

beats 에서는 libbeat 에서 자동으로 설정을 해줍니다.

 

// CreateAlias sends request to Elasticsearch for creating alias.
func (h *ESClientHandler) CreateAlias(alias Alias) error {
	// Escaping because of date pattern
	// This always assume it's a date pattern by sourrounding it by <...>
	firstIndex := fmt.Sprintf("<%s-%s>", alias.Name, alias.Pattern)
	firstIndex = url.PathEscape(firstIndex)

	body := common.MapStr{
		"aliases": common.MapStr{
			alias.Name: common.MapStr{
				"is_write_index": true,
			},
		},
	}

	// Note: actual aliases are accessible via the index
	status, res, err := h.client.Request("PUT", "/"+firstIndex, "", nil, body)
	if status == 400 {
		// HasAlias fails if there is an index with the same name, that is
		// what we want to check here.
		_, err := h.HasAlias(alias.Name)
		if err != nil {
			return err
		}
		return errOf(ErrAliasAlreadyExists)
	} else if err != nil {
		return wrapErrf(err, ErrAliasCreateFailed, "failed to create alias: %s", res)
	}

	return nil
}

하지만, elasticsearch 에서 수동으로 설정을 한다고 하면 꼭 "is_write_index:true" 설정을 해주셔야 alias 생성 및 등록이 잘 된다는거 알고 넘어 가자고요.

 

:

[Elasticsearch] UTC 를 사용 하는 이유.

Elastic/Elasticsearch 2020. 4. 8. 12:28

분명히 어디선가 공식 문서 또는 글을 봤는데 찾지를 못하겠습니다.

 

https://www.elastic.co/guide/en/elasticsearch/reference/current/date.html

https://discuss.elastic.co/t/elastic-utc-time/191877

 

discuss 에 보면 elastic team member 가 코멘트 한 내용이 있습니다.

Elasticsearch doesn't have a native concept of a "pure" date, only of instants in time. 
Given that, I think that it is reasonable to represent a pure date as the instant of 
midnight UTC on that date. 
If you use a different timezone then you will encounter problems as some "dates" 
will not be a whole number of days apart, because of occasions 
when the clocks go forwards or back for daylight savings.

Formatting a date as an instant without an explicit timezone is probably a bad idea, 
because something somewhere will have to guess what timezone to use 
and you may get inconsistent results if those guesses are inconsistent. 
Always specify the timezone, and in this case I recommend UTC as I mentioned above.

When you run an aggregation involving times, 
you can tell Elasticsearch what timezone to use 27. 
It defaults to UTC according to those docs.

I do not, however, know how to get Kibana to interpret 
these dates as you want in a visualisation. 
It's probably best to ask on the Kibana forum for help with that.

그리고 reference 문서에는 아래와 같은 내용이 있습니다.

Internally, dates are converted to UTC (if the time-zone is specified) 
and stored as a long number representing milliseconds-since-the-epoch.

그냥 Elastic Stack 은 기본적으로 @timestamp 값을 저장 시 UTC 0 를 기준으로 저장을 한다고 이해 하시고 질의 시점에 변환을 하거나 별도 localtime 에 맞는 custum timestamp field 를 추가해서 사용하는게 정신 건강에 좋다고 생각 하십시오.

 

추가적으로,

 

Date Query 관련 질의 시 

- "time_zone" 파라미터 설정은 now 값에 영향을 주지 않습니다.

참고 하세요.

:

[Kibana] Visualize Metric JSON Input 예제

Elastic/Kibana 2020. 4. 7. 20:11

kibana 에서 visualize 중 metric 을 구성 할 때 또는 다른 visualize 이더라도 비슷 합니다.

JSON Input 은 아래와 같이 넣으 실 수 있습니다.

{
  "script": {
    "inline": "doc['system.filesystem.free'].value / 1024 / 1024 /1024",
    "lang": "painless"
  }
}

좀 더 자세한 내용이 궁금 하신 분들은 아래 문서 한번 보시면 좋습니다.

 

공식문서)

https://www.elastic.co/guide/en/elasticsearch/reference/master/modules-scripting-fields.html

 

 

:

[Elasticsearch] Docker Compose 실행 시 permission denied

Elastic/Elasticsearch 2020. 4. 7. 15:54

docker compose 실행 시  permission denied 에러 경험을 하실 수 있습니다.

아래와 같은 방법으로 문제를 해결 할 수 있으니 환경에 맞게 적용 해 보면 좋을 것 같습니다.

 

docker-compose.yml)

    volumes:
      - /elasticsearch/config/elasticsearch.yml:/usr/share/elasticsearch/config/elasticsearch.yml:ro
      - /elasticsearch/data:/usr/share/elasticsearch/data:rw
      - /elasticsearch/logs:/usr/share/elasticsearch/logs:rw

 

Case 1)

$ chmod 777 /elasticsearch/data

$ chmod 777 /elasticsearch/logs

 

Case 2)

- docker-compose.yml 안에 uid, gid 를 설정

user: "1002:0" # uid 는 host user 로 설정, gid 는 container group 으로 설정

 

Elasticsearch 의 경우 docker 로 구성 하시면 Container 내부에서 1000:0 으로 실행 됩니다.

즉, uid 1000(elasticsearch), gid 0(root) 가 됩니다.

그래서 bind mount 의 경우 host 에서의 권한과 container 에서의 권한을 잘 맞춰 주셔야 합니다.

 

$ id -u username

$ id -g username

$ docker exec -it container-name /bin/bash

 

그럼 즐거운 Elastic 되세요.

:

[Elastic] Elasticsearch, Metricbeat, Docker Compose 삽질.

Elastic 2020. 4. 3. 18:48

metricbeat 사용 시 템플릿 설정이 잘 못 되었다면 반드시 삭제 하고 다시 생성 합니다.

또는

- setup.template.overwrite: true

를 설정 합니다.

 

metricbeat 에서 데이터를 잘 보내고 있는데 데이터가 정상적으로 들어 오지 않으면, 템플릿을 리셋 하거나 아래 설정을 확인 합니다.

- setup.template.settings._source.enabled: true

 

이미 경험했던 내용이고 기록도 했었는데 바로 찾아 내지 못하고 삽질을 했네요.

반성 중입니다.

:

[Elasticsearch] Index Lifecycle Management 실행 주기

Elastic/Elasticsearch 2020. 4. 3. 14:04

설정 하고 왜 바로 동작 안하지 그랬는데, 다 이유가 있었습니다.

 

[LifecycleSettings.java]

/*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License;
 * you may not use this file except in compliance with the Elastic License.
 */
package org.elasticsearch.xpack.core.ilm;

import org.elasticsearch.common.Strings;
import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.xpack.core.scheduler.CronSchedule;

/**
 * Class encapsulating settings related to Index Lifecycle Management X-Pack Plugin
 */
public class LifecycleSettings {
    public static final String LIFECYCLE_POLL_INTERVAL = "indices.lifecycle.poll_interval";
    public static final String LIFECYCLE_NAME = "index.lifecycle.name";
    public static final String LIFECYCLE_INDEXING_COMPLETE = "index.lifecycle.indexing_complete";
    public static final String LIFECYCLE_ORIGINATION_DATE = "index.lifecycle.origination_date";
    public static final String LIFECYCLE_PARSE_ORIGINATION_DATE = "index.lifecycle.parse_origination_date";
    public static final String LIFECYCLE_HISTORY_INDEX_ENABLED = "indices.lifecycle.history_index_enabled";

    public static final String SLM_HISTORY_INDEX_ENABLED = "slm.history_index_enabled";
    public static final String SLM_RETENTION_SCHEDULE = "slm.retention_schedule";
    public static final String SLM_RETENTION_DURATION = "slm.retention_duration";


    public static final Setting<TimeValue> LIFECYCLE_POLL_INTERVAL_SETTING = Setting.positiveTimeSetting(LIFECYCLE_POLL_INTERVAL,
        TimeValue.timeValueMinutes(10), Setting.Property.Dynamic, Setting.Property.NodeScope);
    public static final Setting<String> LIFECYCLE_NAME_SETTING = Setting.simpleString(LIFECYCLE_NAME,
        Setting.Property.Dynamic, Setting.Property.IndexScope);
    public static final Setting<Boolean> LIFECYCLE_INDEXING_COMPLETE_SETTING = Setting.boolSetting(LIFECYCLE_INDEXING_COMPLETE, false,
        Setting.Property.Dynamic, Setting.Property.IndexScope);
    public static final Setting<Long> LIFECYCLE_ORIGINATION_DATE_SETTING =
        Setting.longSetting(LIFECYCLE_ORIGINATION_DATE, -1, -1, Setting.Property.Dynamic, Setting.Property.IndexScope);
    public static final Setting<Boolean> LIFECYCLE_PARSE_ORIGINATION_DATE_SETTING = Setting.boolSetting(LIFECYCLE_PARSE_ORIGINATION_DATE,
        false, Setting.Property.Dynamic, Setting.Property.IndexScope);
    public static final Setting<Boolean> LIFECYCLE_HISTORY_INDEX_ENABLED_SETTING = Setting.boolSetting(LIFECYCLE_HISTORY_INDEX_ENABLED,
        true, Setting.Property.NodeScope);


    public static final Setting<Boolean> SLM_HISTORY_INDEX_ENABLED_SETTING = Setting.boolSetting(SLM_HISTORY_INDEX_ENABLED, true,
        Setting.Property.NodeScope);
    public static final Setting<String> SLM_RETENTION_SCHEDULE_SETTING = Setting.simpleString(SLM_RETENTION_SCHEDULE,
        // Default to 1:30am every day
        "0 30 1 * * ?",
        str -> {
        try {
            if (Strings.hasText(str)) {
                // Test that the setting is a valid cron syntax
                new CronSchedule(str);
            }
        } catch (Exception e) {
            throw new IllegalArgumentException("invalid cron expression [" + str + "] for SLM retention schedule [" +
                SLM_RETENTION_SCHEDULE + "]", e);
        }
    }, Setting.Property.Dynamic, Setting.Property.NodeScope);
    public static final Setting<TimeValue> SLM_RETENTION_DURATION_SETTING = Setting.timeSetting(SLM_RETENTION_DURATION,
        TimeValue.timeValueHours(1), TimeValue.timeValueMillis(500), Setting.Property.Dynamic, Setting.Property.NodeScope);
}

설정을 하셨다면 이제는 기다리시면 됩니다. 

:

[Elasticsearch] Index 생성 시 Name Pattern

Elastic/Elasticsearch 2020. 4. 3. 11:22

Elastic Stack 을 사용하다 보면 Index 를 자동으로 생성 시켜 주는 설정들을 사용 하게 됩니다.

 

beats 에서는 output elasticsearch 사용 시 설정을 하게 되고,

logstash 에서도 output elasticsearch 사용 시 설정을 하게 됩니다.

 

보통 이 설정을 아래와 같이 하는데요.

 

Logstash)

index

- Value type is string
- Default value is "logstash-%{+YYYY.MM.dd}"

 

Beats)

index

The index name to write events to when you’re using daily indices. 
The default is "beat-%{[agent.version]}-%{+yyyy.MM.dd}" 
(for example, "beat-7.6.2-2020-04-02"). 
If you change this setting, you also need to configure the setup.
template.name and setup.template.pattern options (see Elasticsearch index template).

output.elasticsearch:
  hosts: ["https://localhost:9200"]
  index: "beats-%{[agent.version]}-%{+yyyy.MM.dd}"

- filebeat, metricbeat ...

 

보시면 아시겠지만, Daily rolling 으로 많이 사용하게 됩니다.

무조건 하루 단위로 생성이 되기 때문에 규모가 너무 작거나 너무 크거나 할 경우 효율이 떨어 질 수 밖에 없습니다.

그래서 Index Lifecycle Management 라는 기능을 Elasticsearch 에서 제공하고 있으니 활용 하시기 바랍니다.

 

여기서 문제)

그럼 output.elasticsearch.index 설정과 ilm 설정이 동시에 사용 중일 때 어떤 설정에 맞춰서 index 가 생성이 될까요?

 

정답)

ilm 설정이 우선 합니다. 

 

Elastic 의 공식 메시지는 이렇습니다.

https://www.elastic.co/guide/en/elasticsearch/reference/current/index-lifecycle-management.html

 

You can configure index lifecycle management (ILM) policies to automatically manage indices according to your performance, resiliency, and retention requirements.

 

:

[Elasticsearch] Docker Compose 구성 하기

Elastic/Elasticsearch 2020. 4. 2. 07:49

Elasticsearch 를 Single Node 로 구성 하기 위한 docker-compose.yml 내용을 살펴 봅니다.

 

참고문서)

https://www.elastic.co/guide/en/elasticsearch/reference/current/docker.html

 

docker-compose.yml)

version: '2.2'
services:
  ${ES-SERVICE-NAME}:
    image: docker.elastic.co/elasticsearch/elasticsearch:7.6.2
    container_name: ${ES-SERVICE-NAME}
    environment:
      - node.name=${NODE-NAME}
      - cluster.name=${CLUSTER-NAME}
      - discovery.type=single-node
      - discovery.seed_hosts=${NODE-NAME}
      - path.data=/usr/share/elasticsearch/data
      - path.logs=/usr/share/elasticsearch/logs
      - bootstrap.memory_lock=true
      - http.port=9200
      - transport.port=9300
      - transport.compress=true
      - network.host=0.0.0.0
      - http.cors.enabled=false
      - http.cors.allow-origin=/https?:\/\/localhost(:[0-9]+)?/
      - gateway.expected_master_nodes=1
      - gateway.expected_data_nodes=1
      - gateway.recover_after_master_nodes=1
      - gateway.recover_after_data_nodes=1
      - action.auto_create_index=true
      - action.destructive_requires_name=true
      - cluster.routing.use_adaptive_replica_selection=true
      - xpack.monitoring.enabled=false
      - xpack.ml.enabled=false
      - http.compression=true
      - http.compression_level=3
      - "ES_JAVA_OPTS=-Xms512m -Xmx512m"
    ulimits:
      memlock:
        soft: -1
        hard: -1
      nproc:
        soft: 1024000
        hard: 1024000
      nofile:
        soft: 1024000
        hard: 1024000
    sysctls:
      net.core.somaxconn: 65000
    healthcheck:
      test: ["CMD-SHELL", "curl --silent --fail localhost:9200/_cat/health || exit 1"]
      interval: 30s
      timeout: 30s
      retries: 3
    restart: always
    volumes:
      - ${NAMED-VOLUME-DATA}:/usr/share/elasticsearch/data:rw
      - ${NAMED-VOLUME-LOG}:/usr/share/elasticsearch/logs:rw
#      - ${FULL-PATH-DATA}:/usr/share/elasticsearch/data:rw
#      - ${FULL-PATH-LOG}:/usr/share/elasticsearch/logs:rw
    ports:
      - 9200:9200
      - 9300:9300
    expose:
      - 9200
      - 9300
    networks:
      - ${NETWORK-NAME}

volumes:
  ${NAMED-VOLUME-DATA}:
    driver: local
  ${NAMED-VOLUME-LOG}:
    driver: local

networks:
  ${NETWORK-NAME}:
    driver: bridge

 

Single Node 로 구성 하기 위해 중요한 설정은

- environment: 섹션에서 discovery.type=single-node 

입니다.

 

만약, Clustering 구성을 하고 싶다면 위 설정을 제거 하고 아래 세개 설정을 작성 하시면 됩니다.

- cluster.initial_master_nodes=# node 들의 private ip 를 등록 합니다.
- discovery.seed_hosts=# node 들의 private ip 를 등록 합니다.

- network.publish_host=# 컨테이너가 떠 있는 host 의 private ip 를 등록 합니다.

 

path.data 에 대한 구성을 복수로 하고 싶으실 경우

- volumes: 섹션에서 named volume 을 여러개 설정 하시거나

- bind mount 설정을 구성 하셔서 

적용 하시면 됩니다.

 

위 docker-compose.yml 을 기준으로 single node 구성과 cluster 구성을 모두 하실 수 있습니다.

 

  • ${....} 는 변수명 입니다.
    • 본인의 환경에 맞춰 작명(?) 하셔서 변경 하시면 됩니다.
:

[Elasticsearch] Docker Compose 구성 시 주의 사항.

Elastic/Elasticsearch 2020. 4. 1. 09:02

정답이라기 보다는 구성 하면서 경험한 내용을 작성 한 것입니다.

나중에 기억이 나지 않을 수도 있으니 정상 동작 했던 내용을 기록 합니다.

 

Elasticsearch Docker Compose 구성 중 주의 사항)

- volume 구성 시 bind mount 를 사용할 경우는 mount 할 storage 를 미리 생성해 두어야 합니다.
- bind mount 사용 시 absolute path 설정을 하셔야 합니다.
- single node 구성 시 network.publish_host 설정은 하지 않아도 됩니다.
- cluster 구성 시 (물리적으로 node 3개) 개별 node 에서 clustering 을 하기 
위해서는 network.publish_host 설정을 하셔야 합니다.
- cluster 구성 시 컨테이너 내부 node 설정에는 private ip 를 등록 합니다.
- sysctls 옵션 에서 vm.max_map_count 설정이 되지 않기 때문에 host 에서 
$ sudo sysctl -w vm.max_map_count=262144 를 실행 해야 합니다.

 

:

[Elasticsearch] Single node 실행

Elastic/Elasticsearch 2020. 3. 27. 16:05

Elasticsearch 버전이 올라 가면서 master node 를 최소 쿼럼 구성으로 해야 하는데요.

아마 잘 아시겠지만 Single node 구성을 원하시는 분은 아래 설정을 통해서 실행 하시면 됩니다.

 

[Single node 설정]

discovery.type=single-node

 

이 설정은 아래 설정이 포함되어 있을 경우 충돌이 납니다.

cluster.initial_master_nodes

 

본 설정을 주석 처리 하거나 삭제 하신 후 실행 시키면 정상 동작 합니다.

 

Elastic 공식 문서에 자세한 설명이 나와 있으니 참고 하시면 좋습니다.

https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-discovery-settings.html#modules-discovery-settings

: