ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 서버 핑 테스트해서 슬랙으로 메시지 보내기 with Shell Script 2부
    Shell Script 2023. 5. 8. 23:02

    https://xodns.tistory.com/117

     

    서버 핑 테스트해서 슬랙으로 메시지 보내기 with Shell Script 1부

    https://slack.com/intl/ko-kr/ Slack은 생산성 플랫폼입니다 Slack은 여러분의 팀과 소통할 새로운 방법입니다. 이메일보다 빠르고, 더 조직적이며, 훨씬 안전합니다. slack.com 에 가서 로그인을 한다. https://

    xodns.tistory.com

     

    1부에 이어서 한다.

     

    스프링 jar를 하나 얻어온다.

    https://github.com/TaeWoonJeong/spring-feign-kafka-multimodule/releases/tag/1.0.0

     

    Release 1.0.0 · TaeWoonJeong/spring-feign-kafka-multimodule

    release V 1.0.0

    github.com

    에서 module1.jar를 다운받는다.

    module2.jar는 db연결을 해야하고 consumer는 kafka에서 메시지를 받아서 DB에 넣어야하므로, db연결을 해야하고, producer은 kafka와 연결을 실패하면 에러메시지가 계속 나오기 때문에, module1을 다운받아서 해준다.

    server:
      port: ${SERVER_PORT}
      module2:
        url: ${MODULE2_SERVER_URL}
    spring:
      mvc:
        pathmatch:
          matching-strategy: ant_path_matcher
    springdoc:
      swagger-ui:
        path: /module1/swagger-ui.html
      api-docs:
        path: /module1

    module1의 application.yml 이다. server_port는 아무 숫자 넣으면 되고 url에는 적당히 url 형식을 맞춰서 넣어주자. ping 테스트만 할거가 때문에 작동만 된다면, swagger페이지로 ping 테스트를 할 것이다.

     

    aws에가서 ec2하나 빌린다. 내 노트북이 인텔 amd 아키텍처여서(즉 jar파일이 amd 아키텍처 기반에서 작동합니다.) aws에서 arm아키텍처기반인 t4g.small을 사용할 수 없다. 그래서 t2.micro를 사용하겠다.

    AMI 보다는 Ubuntu 20.04 를 사용하겠다.

     

    잘 들어왔으니, 다운받은 module1.jar를 넣어주자.

     

    자바 17로 만들었으니, 자바 17을 다운받아주자.

    https://xodns.tistory.com/102

     

    EC2 java 17,18 설치

    https://techviewleo.com/install-java-openjdk-on-ubuntu-linux sudo apt update sudo apt install openjdk-17-jdk 이렇게 설치하거나, 아래처럼 설치하면 된다. https://docs.aws.amazon.com/corretto/latest/corretto-17-ug/generic-linux-install.html

    xodns.tistory.com

     

    module1.yml을 내부에서 만들고, 위에 yml 값들을 복사해서 적당한 값을 넣어서 만들어준다.

    적당히 만들어주고 jar파일을 실행시켜보자.

     nohup java -jar -Duser.timezone="Asia/Seoul" -Dspring.config.location=/home/ubuntu/module1.yml /home/ubuntu/module1-1.0.0.jar &

    실행하면 nohup.out 파일에 로그가 써진다.

    정상실행이 됬다면 브라우저에 EC2 IP주소:포트번호/module1/swagger-ui.html 을 입력해보자.

    정상실행인데 접근이 안된다면, EC2에서 해당 포트번호 보안규칙을 풀어줘야한다.

     

    이렇게 나오면 성공이다.

     

    스크립트를 만들어보겠다.

    로직은 간단하다.

    1. 일정시간마다 위의 주소로 요청을 보낸다.

    2. response code를 보고 500이라면 1부에서 했던것처럼 curl을 보내주면 된다.

     

    이렇게 만들고 스크립트를 실행권한을 chmod 로 주고 실행시키면 200이 나오면 슬랙메시지를 보내준다.

    #!/bin/bash
    STATUS=$(curl -o /dev/null -w "%{http_code}" "http://13.209.66.44:8080/module1/swagger-ui/index.html")
    
    if [ $STATUS -eq 200 ]; then
    	1부에서 봤던 curl 값을 넣어주세요.
    fi

    대부분은 reverse-proxy를 사용해서 스프링 앞에 nginx를 둔다. 일단 nginx를 설치한다.

    sudp apt install nginx

    nginx 설치하고 IP입력하면 이렇게 나온다.

    흠.. 점점 복잡해지는데, 왜이렇게 하냐면, 지금 jar파일만 가지고는 해당 프로세스를 종료시켜주면, 아무 응답을 받지 못하기 때문에, curl을 보내줄 수 없다.. 그래서 최대한 실제상황과 비슷하게 만들어본다.

     

    우리가 원하는것은 해당 IP를 입력하면 스프링의 8080포트로 연결시켜주는 것이다.

    nginx 설정파일은

    /etc/nginx/sites-available

    의 default파일에 써져있다.

    ##
    # You should look at the following URL's in order to grasp a solid understanding
    # of Nginx configuration files in order to fully unleash the power of Nginx.
    # https://www.nginx.com/resources/wiki/start/
    # https://www.nginx.com/resources/wiki/start/topics/tutorials/config_pitfalls/
    # https://wiki.debian.org/Nginx/DirectoryStructure
    #
    # In most cases, administrators will remove this file from sites-enabled/ and
    # leave it as reference inside of sites-available where it will continue to be
    # updated by the nginx packaging team.
    #
    # This file will automatically load configuration files provided by other
    # applications, such as Drupal or Wordpress. These applications will be made
    # available underneath a path with that package name, such as /drupal8.
    #
    # Please see /usr/share/doc/nginx-doc/examples/ for more detailed examples.
    ##
    
    # Default server configuration
    #
    server {
            listen 80 default_server;
            listen [::]:80 default_server;
    
            # SSL configuration
            #
            # listen 443 ssl default_server;
            # listen [::]:443 ssl default_server;
            #
            # Note: You should disable gzip for SSL traffic.
            # See: https://bugs.debian.org/773332
            #
            # Read up on ssl_ciphers to ensure a secure configuration.
            # See: https://bugs.debian.org/765782
            #
            # Self signed certs generated by the ssl-cert package
            # Don't use them in a production server!
            #
            # include snippets/snakeoil.conf;
    
            root /var/www/html;
    
            # Add index.php to the list if you are using PHP
            index index.html index.htm index.nginx-debian.html;
    
            server_name _;
    
            location / {
                    # First attempt to serve request as file, then
                    # as directory, then fall back to displaying a 404.
                    try_files $uri $uri/ =404;
            }
    
            # pass PHP scripts to FastCGI server
            #
            #location ~ \.php$ {
            #       include snippets/fastcgi-php.conf;
            #
            #       # With php-fpm (or other unix sockets):
            #       fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
            #       # With php-cgi (or other tcp sockets):
            #       fastcgi_pass 127.0.0.1:9000;
            #}
    
            # deny access to .htaccess files, if Apache's document root
            # concurs with nginx's one
            #
            #location ~ /\.ht {
            #       deny all;
            #}
    }
    
    
    # Virtual Host configuration for example.com
    #
    # You can move that to a different file under sites-available/ and symlink that
    # to sites-enabled/ to enable it.
    #
    #server {
    #       listen 80;
    #       listen [::]:80;
    #
    #       server_name example.com;
    #
    #       root /var/www/example.com;
    #       index index.html;
    #
    #       location / {
    #               try_files $uri $uri/ =404;
    #       }
    #}

     

    기본값으로 이렇게 써져있다.

    간단히 보자면 80번(브라우저 기본 http) 으로 들어오면 /var/www/html에 있는 문서를 보여주는건데, 그래서 Welcome nginx! 가 나온것이다.

    이제 80번으로 들어오면 8080번으로 바꾸겠다.

    https://velog.io/@jjonggang/Spring-Boot-Nginx%EB%A5%BC-%EC%9D%B4%EC%9A%A9%ED%95%98%EC%97%AC-Spring-Boot%EB%A5%BC-80%EB%B2%88-%ED%8F%AC%ED%8A%B8%EB%A1%9C-%ED%94%84%EB%A1%9D%EC%8B%9C%ED%95%98%EA%B8%B0

     

    [Spring Boot] Nginx를 이용하여 Spring Boot를 80번 포트로 프록시하기

    스프링 부트는 기본적으로 8080번 포트에서 서비스 됩니다. 하지만, 대부분의 서비스가 HTTP의 기본 포트인 80번 포트에서 제공되는 만큼, 결국은 80번 포트로 변경을 해줘야 합니다. 이를 위해서는

    velog.io

    위에 블로그 처럼 해주면 된다.

        location / {
                proxy_pass http://localhost:8080;
                proxy_set_header X-Real_IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header Host $http_host;
        }

    를 추가해주자.

    default 파일을 수정해주는게 좋다.

    ##
    # You should look at the following URL's in order to grasp a solid understanding
    # of Nginx configuration files in order to fully unleash the power of Nginx.
    # https://www.nginx.com/resources/wiki/start/
    # https://www.nginx.com/resources/wiki/start/topics/tutorials/config_pitfalls/
    # https://wiki.debian.org/Nginx/DirectoryStructure
    #
    # In most cases, administrators will remove this file from sites-enabled/ and
    # leave it as reference inside of sites-available where it will continue to be
    # updated by the nginx packaging team.
    #
    # This file will automatically load configuration files provided by other
    # applications, such as Drupal or Wordpress. These applications will be made
    # available underneath a path with that package name, such as /drupal8.
    #
    # Please see /usr/share/doc/nginx-doc/examples/ for more detailed examples.
    ##
    
    # Default server configuration
    #
    server {
            listen 80 default_server;
            listen [::]:80 default_server;
    
            # SSL configuration
            #
            # listen 443 ssl default_server;
            # listen [::]:443 ssl default_server;
            #
            # Note: You should disable gzip for SSL traffic.
            # See: https://bugs.debian.org/773332
            #
            # Read up on ssl_ciphers to ensure a secure configuration.
            # See: https://bugs.debian.org/765782
            #
            # Self signed certs generated by the ssl-cert package
            # Don't use them in a production server!
            #
            # include snippets/snakeoil.conf;
    
            root /var/www/html;
    
            # Add index.php to the list if you are using PHP
            index index.html index.htm index.nginx-debian.html;
    
            server_name _;
    
            location / {
                proxy_pass http://localhost:8080;
                proxy_set_header X-Real_IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header Host $http_host;
            }
    
            error_page 404 /404.html;
                location = /40x.html {
            }
    
            error_page 500 502 503 504 /50x.html;
                location = /50x.html {
            }
    
            # pass PHP scripts to FastCGI server
            #
            #location ~ \.php$ {
            #       include snippets/fastcgi-php.conf;
            #
            #       # With php-fpm (or other unix sockets):
            #       fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
            #       # With php-cgi (or other tcp sockets):
            #       fastcgi_pass 127.0.0.1:9000;
            #}
    
            # deny access to .htaccess files, if Apache's document root
            # concurs with nginx's one
            #
            #location ~ /\.ht {
            #       deny all;
            #}
    }
    
    
    # Virtual Host configuration for example.com
    #
    # You can move that to a different file under sites-available/ and symlink that
    # to sites-enabled/ to enable it.
    #
    #server {
    #       listen 80;
    #       listen [::]:80;
    #
    #       server_name example.com;
    #
    #       root /var/www/example.com;
    #       index index.html;
    #
    #       location / {
    #               try_files $uri $uri/ =404;
    #       }
    #}

    블로그에는 nginx.conf를 만지는데, 그러지말고 default파일을 수정하자.

    포트 없이도 성공했다.

    이제 실행중인 jar를 꺼보겠다. 프로세스 아이디 찾는 방법은 nohup.out에 가면 프로세스 아이디를 얻을 수 있고, 또는 

    ps -ef | grep java

    로 찾아도 된다.

     

    jar를 끄면 404에러가 나온다.

     

    스프링이 실행중이지 않는다면 404 에러를 보낼것이므로, 핑테스트를 계속 하다가 404에러를 받게된다면, 그때 슬랙으로 알려주면 된다.

    vi script.sh

    로 vi 편집기 열어서 아래 내용을 적어준다.

    #!/bin/bash
    CNT=0
    ZERO=0
    ONE=1
    while true
    do
      #200이 아니면 나머지는 전부 에러로 간주한다.
      STATUS=$(curl -s -o /dev/null -w "%{http_code}" "http://54.180.126.161/module1/swagger-ui/index.html")
      if [ $STATUS -eq 200 ]; then
         CNT=$ZERO
       else
         if [ $CNT -eq 2 ]; then
            1부에서 본 incomming webhook curl 넣기
            echo "서버가 종료됨을 확인한 시간 $(date) PID: $$"
         fi
         CNT=$(($CNT+$ONE))
      fi
      echo "CNT: $CNT $(date) PID: $$ STATUS: $STATUS"
      sleep 30s
    done

    간단히 설명하자면, swagger 문서로 요청을 보냈는데, 200이 아닌 경우, CNT를 올려준다. 만약 2번연속 아닌경우(1분소요) 슬랙으로 알림을 준다. 그리고 언젠가 관리자가 다시 해당 jar파일을 켜는 경우, 그때는 200응답이 올것이므로 CNT는 0이 된다.

     

    실행해보면, UTC시간으로 되는데 KST로 바꾸겠다.

    sudo ln -sf /usr/share/zoneinfo/Asia/Seoul /etc/localtime

    스크립트 실행 명령어

    nohup sh script.sh 1>> /home/ubuntu/ping.log 2>> /home/ubuntu/ping-error.log &

    stdout은 ping.log로 보내고 stderr은 ping-error.log로 보내준다.(기본적으로 0 이 stdin이고, 1이 stdout 이고, 2가 stderr이다. C언어 공부하면 나온다.)

     

    만약 실행되지 않는 경우

    chmod 777 script.sh

    로 rwxrwxrwx를 주자.

     

    처음에는 jar를 끈 상태로 진행했다.

    그리고 슬랙으로 메시지를 받고 관리자가 다시 jar파일을 실행시켰다고 하자.

    이때의 로그파일과 slack메시지를 첨부하고 끝내겠다.

     

    이상태에서 다시 jar를 끄면 1분정도 기다려보면 다시 메시지가 오는걸 볼 수 있다.

    이렇게 잘 작동하는것을 확인했다.

    -끝-

Designed by Tistory.