'2020/04'에 해당되는 글 29건

  1. 2020.04.17 [Gradle] Task Zip
  2. 2020.04.16 [Logstash] Docker Compose 구성 하기.
  3. 2020.04.09 [Slack] Incoming WebHooks 사용하기.
  4. 2020.04.09 [Spring] WebClient 사용 예제
  5. 2020.04.09 [Spring] Scheduler + WebClient Hello ~
  6. 2020.04.08 [Elasticsearch] UTC 를 사용 하는 이유.
  7. 2020.04.08 [Docker] Docker Compose TZ 설정
  8. 2020.04.07 [Kibana] Visualize Metric JSON Input 예제
  9. 2020.04.07 [Shell] Bash read, if then fi
  10. 2020.04.07 [Elasticsearch] Docker Compose 실행 시 permission denied

[Gradle] Task Zip

ITWeb/개발일반 2020. 4. 17. 10:13

참고문서)

https://docs.gradle.org/current/userguide/working_with_files.html#sec:creating_archives_examplel

 

예제) build.gradle

plugins {
  id 'base'
}

def buildNumber = System.getenv('BUILD_NUMBER')
version = "0.0.${buildNumber}"

task packageDistribution(type: Zip) {
  archiveFileName = "${project.name}-${project.version}.zip"
  destinationDirectory = file("$buildDir/dist")

  from 'docker-compose', 'scripts'
}

 

:

[Logstash] Docker Compose 구성 하기.

Elastic/Logstash 2020. 4. 16. 17:08

Elastic 공식 문서로는 아직 못본 것 같습니다.

기본 Docker 문서는 아래 문서를 참고 하시기 바랍니다.

 

[공식문서]

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

 

그러나 아예 예제가 없는 건 아닙니다.

Elastic 사의 github 에 들어가 보시면 참고 하실 수 있는 template 파일이 있습니다.

 

[github logstash-docker]

https://github.com/elastic/logstash-docker/tree/master/templates

 

위 템플릿 기반으로 logstash 만 설정해서 구성 하시면 쉽게 할 수 있습니다.

그 이외는 on premise 방식의 logstash 사용 방법과 크게 다른게 없습니다.

 

[실행방법]

$ docker-compose up -d

 

이와 같이 실행 하시면 background 로 자동 실행 됩니다.

 

[docker-compose.yml 예제]

version: '3.7'
services:
  logstash:
    image: docker.elastic.co/logstash/logstash:7.6.2
    volumes:
      - ./examples/logstash.conf/:/usr/share/logstash/pipeline/logstash.conf
    network_mode: bridge
:

[Slack] Incoming WebHooks 사용하기.

ITWeb/개발일반 2020. 4. 9. 17:59

개발 하면서 Slack API 와 연동해서 메시지 보내는 경우가 많이 있습니다.

예전에는 그냥 개인 계정으로 API Token 만들어서 사용했던 기억이 있었는데, 이제는 아닌가 봅니다.

 

회사에서 특정 Workspace 를 만들고 이를 통해서 Notification  구현을 하려고 보니 엄한데서 API 만들고 있었습니다.

 

- 개인 계정으로 App 개발을 위해서 사용 하세요.

http://api.slack.com 

 

- 특정 Workspace 내 에서 App 개발을 위해서 사용 하세요.

http://WORKSPACE.slack.com/apps 

 

담부터는 실수 하지 말아야 겠습니다.

:

[Spring] WebClient 사용 예제

ITWeb/개발일반 2020. 4. 9. 17:01

https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/reactive/function/client/WebClient.RequestHeadersSpec.html#retrieve--

- retrieve()
Perform the HTTP request and retrieve the response body.
This method is a shortcut to using exchange() and decoding the response body through ClientResponse.

- exchange()
Perform the HTTP request and return a ClientResponse with the response status and headers. You can then use methods of the response to consume the body

 

https://spring.io/guides/gs/reactive-rest-service/

 

[Non Blocking]

// retrieve() 예제
  @Override
  public void runner() {
    Mono<String> response = WebClient
        .create(watcherEndpointHost)
        .method(HttpMethod.POST)
        .uri(watcherEndpointUri)
        .contentType(MediaType.APPLICATION_JSON)
        .accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML)
        .acceptCharset(Charset.forName("UTF-8"))
        .body(BodyInserters.fromValue(getCheckQuery()))
        .retrieve()
        .bodyToMono(String.class);

    response.subscribe(result -> {
      logger.debug("{}", result);
    }, e -> {
      logger.debug("{}", e.getMessage());
    });
  }
  
// exchange() 예제  
  @Override
  public void runner() {
    Mono<String> response = WebClient
        .create(watcherEndpointHost)
        .method(HttpMethod.POST)
        .uri(watcherEndpointUri)
        .contentType(MediaType.APPLICATION_JSON)
        .accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML)
        .acceptCharset(Charset.forName("UTF-8"))
        .body(BodyInserters.fromValue(getCheckQuery()))
        .exchange()
        .flatMap(clientResponse -> clientResponse.bodyToMono(String.class));

    response.subscribe(result -> {
      logger.debug("{}", result);
    }, e -> {
      logger.debug("{}", e.getMessage());
    });
  }

 

[Blocking]

  @Override
  public void runner() {
    String response = WebClient
        .create(watcherEndpointHost)
        .method(HttpMethod.POST)
        .uri(watcherEndpointUri)
        .contentType(MediaType.APPLICATION_JSON)
        .accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML)
        .acceptCharset(Charset.forName("UTF-8"))
        .body(BodyInserters.fromValue(getCheckQuery()))
        .exchange()
        .block()
        .bodyToMono(String.class)
        .block();

    logger.debug("{}", response);
  }
  
  @Override
  public void runner() {
    Mono<String> response = WebClient
        .create(watcherEndpointHost)
        .method(HttpMethod.POST)
        .uri(watcherEndpointUri)
        .contentType(MediaType.APPLICATION_JSON)
        .accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML)
        .acceptCharset(Charset.forName("UTF-8"))
        .body(BodyInserters.fromValue(getCheckQuery()))
        .retrieve()
        .bodyToMono(String.class);

    String result = response.block();
    
    logger.debug("{}", result);
  }

 

WebClient  는 기본 async 방식으로 동작 합니다.

그리고 어디선가 문서에서 봤는데 Connection Pool 관련 고민을 하지 않고 사용해도 된다고 했던 것으로 기억 합니다.

구글링 하다 걸린 코드 걸어 둡니다.

 

[Timeout 설정]

// TcpClient 이용
TcpClient tcpClient = TcpClient.create()
                 .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000) // Connection Timeout
                 .doOnConnected(connection ->
                         connection.addHandlerLast(new ReadTimeoutHandler(10)) // Read Timeout
                                   .addHandlerLast(new WriteTimeoutHandler(10))); // Write Timeout
WebClient webClient = WebClient.builder()
    .clientConnector(new ReactorClientHttpConnector(HttpClient.from(tcpClient)))
    .build();


// ReactorClientHttpConnector 이용
ReactorClientHttpConnector connector =
            new ReactorClientHttpConnector(options ->
                    options.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 2000));
WebClient webClient = WebClient.builder().clientConnector(connector).build();

 

보시면 아시겠지만 방법은 다양하게 많이 있습니다.

직관적이고 이해 하기 쉬운 방법을 찾아서 사용하시면 될 것 같습니다.

 

:

[Spring] Scheduler + WebClient Hello ~

ITWeb/개발일반 2020. 4. 9. 15:09

필요한 Dependency)

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-quartz'
	implementation 'org.springframework.boot:spring-boot-starter-web'
	implementation 'org.springframework.boot:spring-boot-starter-webflux'
}

 

Main Application 에서 @EnableScheduling 을 작성 해 주시면 아주 쉽게 Annotation 설정 만으로 사용 하실 수 있습니다.

예제는 아래 문서 보시면 너무 쉽게 되어 있습니다.

https://spring.io/guides/gs/scheduling-tasks/

 

추가적인 내용을 조금 더 작성 하자면,

- fixedDelay

실행 시간을 포함해서 완료 된 이후 타이머가 동작 하는 방식 입니다.

 

- fixedRate

실행 시간 상관 없이 그냥 지정된 타이머 주기로 동작 하는 방식 입니다.

결국, 실행 시간이 길 경우 중복 실행이 될 수 있습니다.

 

- PeriodicTrigger

특정 주기에 맞춰서 실행 됩니다.

fixedRate 과 유사한 방식 이라고 보시면 됩니다.

 

- CronTrigger

cron 설정 주기에 맞춰서 실행 됩니다.

 

저는 그냥 Web Service 형태로 해서 구성을 해서 아래와 같이 적용했습니다.

 

Scheduler 에 대한 Abstract 를 만들어서 사용했습니다. (구글링 해보면 예제 코드 많이 나옵니다.)

  @PostConstruct
  public void init() {
    this.startScheduler();
  }

  @Override
  public void runner() {
    String response = WebClient
        .create(watcherEndpointHost)
        .method(HttpMethod.POST)
        .uri(watcherEndpointUri)
        .contentType(MediaType.APPLICATION_JSON)
        .accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML)
        .acceptCharset(Charset.forName("UTF-8"))
        .body(BodyInserters.fromValue(getCheckQuery()))
        .exchange()
        .block()
        .bodyToMono(String.class)
        .block();

    logger.debug("{}", response);
  }

  @Override
  public Trigger getTrigger() {
    return new PeriodicTrigger(10, TimeUnit.SECONDS);
  }

  @Override
  public String getCheckQuery() {
    ...중략...
    return checkQuery;
  }

GenericScheduler 를 Singleton 으로 만들어서 Abstract 를 하나 구성했습니다.

  public void startScheduler() {
    GenericScheduler.getInstance()
        .schedule(getRunnable(), getTrigger());
  }

  public void stopScheduler() {
    GenericScheduler.getInstance().shutdown();
  }

  private Runnable getRunnable(){
    return new Runnable(){
      @Override
      public void run() {
        runner();
      }
    };
  }

  public abstract void runner();

  public abstract Trigger getTrigger();

  public abstract String getCheckQuery();

대략적인 구성은 아래 처럼 나옵니다.

@SpringBootApplication
@EnableScheduling
public class MegatoiMonitorWatcherApplication { ... }

public class GenericScheduler { ... }

public abstract class AbstractGenericScheduler { ... }

@Component
public class WatcherCpuChecker extends AbstractGenericScheduler { ... }

 

:

[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 값에 영향을 주지 않습니다.

참고 하세요.

:

[Docker] Docker Compose TZ 설정

Cloud&Container/IaC 2020. 4. 8. 09:14

docker-compose tz 설정

 

Case 1)

volumes:
  - "/etc/localtime:/etc/localtime:ro"
  - "/etc/timezone:/etc/timezone:ro"


Case 2)

environment:
  - TZ=Asia/Seoul

 

:

[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

 

 

:

[Shell] Bash read, if then fi

ITWeb/개발일반 2020. 4. 7. 20:07
#!/usr/bin/env bash

pwd

echo "Are you sure current directory? (Y/N)"
read answer

if [ "$answer" == "y" ] || [ "$answer" == "Y" ]
then
  echo "Yes!!"
fi

echo "done!!"
#!/usr/bin/env bash

pwd

echo "Are you sure current directory? (Y/N)"
read ans
answer=`echo $ans| tr a-z A-Z`

if [ "$answer" == "Y" ]
then
  echo "Yes!!"
fi

echo "done!!"

 

:

[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 되세요.

: