• 파일 설치 경로 생성 : /home/apps
    mkdir /home/apps
    cd /home/apps
  • redis 설치
    참고 : https://redis.io/download
    wget http://download.redis.io/releases/redis-6.2.3.tar.gz
    tar xzf redis-6.2.3.tar.gz
    mv redis-6.2.3 redis62
    
    cd redis62/
    make & make install
  • 설정 변경
    vi redis.conf
    
    # redis 데몬으로 띄우기
    daemonize yes
    
    # logfile 위치 변경
    logfile "/home/apps/redis62/var/redis.log"
    
    # password 변경
    requirepass ***********
  • 디렉토리 생성
    mkdir /home/apps/redis62/var
  • 기동
    /home/apps/redis62/src/redis-server /home/apps/redis62/redis.conf
  • 확인
    # netstat -nlp | grep redis
    tcp        0      0 127.0.0.1:6379          0.0.0.0:*               LISTEN      21216/redis-server
    
    # /home/apps/redis62/src/redis-cli
    127.0.0.1:6379> set foo var
    (error) NOAUTH Authentication required.
    127.0.0.1:6379>
    127.0.0.1:6379> AUTH ***********
    OK
    127.0.0.1:6379> set foo var
    OK
    127.0.0.1:6379> get foo
    "var"
  • 부팅시 기동 설정
    vi /etc/rc.d/rc.local
    
    # redis start
    /home/apps/redis62/src/redis-server /home/apps/redis62/redis.conf

[시스템 환경]

VirtualBox

CentOS 7

192.168.56.102 node01

192.168.56.103 node02

Pacemaker

Corosync

 

가상환경 설정

: [호스트-게스트], [게스트-게스트] 통신 을 위한 설정

 

VirtualBox 네트워크 설정

[어댑터 1] NAT 설정 및 포트 포워딩

 

포트 포워딩 설정

node 1 - ssh port 9001

node 2 - ssh port 9002

 

 

[어댑터 2] 호스트 전용 어댑터

 

● 각 서버 hosts 설정

: 각 서버 노드 ip 를 확인하여 설정해 준다.

 

vi /etc/hosts 아래 내용 추가

192.168.56.102 node01

192.168.56.103 node02

Pacemaker / Corosync 설치

● pacemaker 설치 :::: 모든 호스트

# yum install -y pcs fence-agents-all

 

● pcs 데몬 시작 및 서비스 활성화

# systemctl start pcsd.service

 

● 패스워드 적용

: 패키지 설치 후, 시스템에 hacluster 사용자가 자동으로 생성됩니다. 관리의 편의성을 위해 hacluster 사용자에 대한 동일한 패스워드를 적용합니다.

# passwd hacluster

 

● Pacemaker 설정

: 호스트간 통신을 위해 Firewall에서 클러스터 트래픽을 허용.

TCP : Ports 2224, 3121, 21064

UDP: Ports 5405

 

# firewall-cmd --permanent --add-service=high-availability

# firewall-cmd --add-service=high-availability

# firewall-cmd --reload

 

● 두 노드의 통신을 위한 설정

# pcs cluster auth node01 node02

[패스워드 입력]
Username: hacluster

[입력 후 화면]
node01: Authorized
node02: Authorized

 

● Corosync 구성 동기화

: --name 옵션은 원하는데로 지정. corosync 설정 파일이 생성되고 모든 노드에 배포된다.

설정 파일 위치: /etc/corosync/corosync.conf

# pcs cluster setup --name hacluster node01 node02

[명령 실행 후 화면]
Shutting down pacemaker/corosync services...
Redirecting to /bin/systemctl stop pacemaker.service
Redirecting to /bin/systemctl stop corosync.service
Killing any remaining services...
Removing all cluster configuration files...
node01: Succeeded
node02: Succeeded

[참고] To initialize the corosync config file, execute the following pcs command on both nodes, filling in the information in <> with your nodes' information. # pcs cluster setup --force --local --name mycluster

 

● 클러스트 시작하기

: node01에서 다음의 명령을 실행.

# pcs cluster start --all

 

● 부팅 시 pacemaker와 corosync 시작을 위해 두 호스트의 서비스를 활성화.

# systemctl enable corosync.service

# systemctl enable pacemaker.service

 

● 클러스터 상태 확인

# pcs status

[결과]

2 nodes configured
0 resources configured

Online: [ node01 node02 ]

No resources

Daemon Status:
corosync: active/enabled
pacemaker: active/enabled
pcsd: inactive/disabled

 

● STONITH 비활성 및 Quorum 무시

# pcs property set stonith-enabled=false

# pcs property set no-quorum-policy=ignore

 

● 가상 IP 주소 설정

# pcs resource create Cluster_VIP ocf:heartbeat:IPaddr2 ip=192.168.56.104 cidr_netmask=24 op monitor interval=20s

 

[확인] pcs status

Cluster_VIP (ocf:heartbeat:IPaddr2): Started node01

 

python 테스트 코드 작성

● python 테스트 코드 작성

# mkdir /usr/local/cafe24

# vi /usr/local/cafe24/python_demo_service.py

if __name__ == '__main__':
  import time

  while True:
      print('Hello from the Python Demo Service')
      time.sleep(5)

실행 테스트,

# python /usr/local/cafe24/python_demo_service.py

권한 설정,

# chmod 755 /usr/local/cafe24/python_demo_service.py

 

● 서비스 등록

vi /etc/systemd/system/python_demo_service.service

# systemd unit file for the Python Demo Service


[Unit]

# Human readable name of the unit
Description=Python Demo Service


[Service]

# Command to execute when the service is started
ExecStart=/usr/bin/python /usr/local/cafe24/python_demo_service.py

- 서비스 실행 및 확인

systemctl start python_demo_service

systemctl status python_demo_service

[실행중 상태 확인]
● python_demo_service.service - Cluster Controlled python_demo_service
  Loaded: loaded (/etc/systemd/system/python_demo_service.service; static; vendor preset: disabled)
Drop-In: /run/systemd/system/python_demo_service.service.d
          └─50-pacemaker.conf
  Active: active (running) since 금 2019-09-06 14:04:36 KST; 42min ago
Main PID: 1560 (python)
  CGroup: /system.slice/python_demo_service.service
          └─1560 /usr/bin/python /usr/local/cafe24/python_demo_service.py

 

- 부팅시 서비스 실행되도록 설정,

systemctl enable python_demo_service

 

● 사용할 수 있는 모든 리소스 리스트 출력

: systemd에 등록하면, 해당 서비스를 리소스로서 사용할 수 있게 된다.

(아래 명령어 결과 리스트에 서비스명이 나옴)

# pcs resource list

 

● 리소스 등록

# pcs resource create python_demo_service systemd:python_demo_service

 

● 리소스 등록 확인

# pcs status

 

● Colocation 제약 구성

: 리소스 Cluster_VIP 와 python_demo_service 는 묶음으로 같은 node에서 이루어 지도록 제약을 설정.

# pcs constraint colocation add Cluster_VIP python_demo_service INFINITY

 

[참고] 개별 리소스 수동으로 시작 및 중지 방법
# pcs resource enable [resource_id]
# pcs resource disable [resource_id]
ex. # pcs resource disable python_demo_service

 

테스트

  1. 설정된 가상 IP 설정이 제대로 이루어 지는지 확인.(VIP=192.168.56.104)

    node01 실행 중, secureCRT로 192.168.56.104:22로 접속시 node01로 접속됨. node01 시스템 종료 후 node02 실행 중일때 192.168.56.104:22로 다시 접속시 node02 시스템으로 접속됨.

  2. 서버 장애에 대한 가상 IP와 리소스 전환이 잘 이루어지 지는지 확인.

    2-1. node01에서 실행중인 상태에서, node01에 대한 시스템 종료시 node02로 전환을 pcs status를 통해 확인함.

  3. 장애에 대한 데몬 리소스의 노드 전환이 잘 이루어 지는지 확인.

  4. Colocation 제약 조건 확인.

    4.1. 리소스 Cluster_VIP 와 python_demo_service 가 node02인 곳에서 실행되고 있을때, python_demo_service 리소스만 stop 시켰을 경우, 조금 시간이 지난뒤 다시 start 됨. node01과 node02 끼리 주고받는 heartbeat interval 에 따라 다시 실행되는 시간이 달라지는 것을 추정됨.

  5. node01 실행중, node01를 재부팅 했을때 다시 node01에서 실행됨.

 

유의사항

  1. 문제가 발생하여 노드 전환이 발생했을 때 작업에 영향이 있을지 확인이 필요

 

참고 사이트

● 공식 문서

: 세부 옵션은 공식 문서 참고를 추천

https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/7/html/high_availability_add-on_reference/index

 

● 가상환경 설정 참고 블로그 https://dbrang.tistory.com/1279

 

● 기본 설치 가이드 참고 블로그 https://m.blog.naver.com/PostView.nhn?blogId=bokmail83&logNo=220569260474&proxyReferer=https%3A%2F%2Fwww.google.com%2F

 

 

Spring Security


Authorization(권한) + Authentication(인증)

Cookie & Session Based

 

● 보안 기본 용어

Pricipal : 기본 정보(no, name, email)

Credential : password

Authority: 권한 role

● 보안은 개념적으로 application 외부에서 막아야 한다.

● 스프링 Filter Layer 에서 동작한다.(필터는 스프링 외부에서, 인터셉터는 내부에서 동작)

 

동작 플로우

tomcat -> tomcat filter -> spring filter (springSecurityFilterchain) -> Servlet

| proxy

| delegate

16가지 Filterchain 실행

1) (권한+인증) Web Based

2) oAuth Client

tomcat <- tomcat filter <- spring filter (springSecurityFilterchain) <- Servlet

 

시스템 구조

Client: 인증 토큰을 요청시마다 함께 전달

MSA : 클라이언트로 부터 요청받을시 OAuth Server에서 인증

OAuth Server

 

16가지 Security Filter Chain

 1. ChannelProcessingFilter
 2. SecurityContextPersistenceFilter		( auto-config default )
 3. ConcurrentSessionFilter
 4. LogoutFilter							( auto-config default )
 5. UsernamePasswordAuthenticationFilter	( auto-config default )
 6. DefaultLoginPageGeneratingFilter		( auto-config default )
 7. CasAuthenticationFilter
 8. BasicAuthenticationFilter				( auto-config default )
 9. RequestCacheAwareFilter					( auto-config default )
10. SecurityContextHolderAwareRequestFilter	( auto-config default )
11. JaasApiIntegrationFilter
12. RememberMeAuthenticationFilter
13. AnonymousAuthenticationFilter			( auto-config default )
14. SessionManagementFilter					( auto-config default )
15. ExceptionTranslationFilter				( auto-config default )
16. FilterSecurityInterceptor				( auto-config default )

 

설정

  1. 의존성 추가

    1-1. 기본 스프링

<!-- Spring Security -->
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-core</artifactId>
    <version>4.1.3.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-config</artifactId>
    <version>4.1.3.RELEASE</version>
</dependency>

<dependency>
	<groupId>org.springframework.security</groupId>
	<artifactId>spring-security-taglibs</artifactId>
    <version>4.1.3.RELEASE</version>
</dependency>

<dependency>
	<groupId>org.springframework.security</groupId>
	<artifactId>spring-security-acl</artifactId>
    <version>4.1.3.RELEASE</version>
</dependency>

 

1-2. 스프링 부트

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-security -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
    <version>2.1.6.RELEASE</version>
</dependency>

 

 

-- 3버젼 --
<filter>
	<filter-name>springSecurityFilterChain</filter-name>
	<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
      <filter-name>springSecurityFilterChain</filter-name>
      <url-pattern>/*</url-pattern>
</filter-mapping>

-- 4버젼 --

AbstractSecurityWebApplicationInitializer를 상속받는 클래스 생성
-- 5버젼 --
관례로 이미 설정되어 있다.

 

ACL이란?

● 참고 URL

https://github.com/cafe24-bitacademy/hmo/blob/master/src/main/resources/common/security-context.xml#L27

 

메모

  1. UserDao

    role 필드 추가. 암호화(BCrypt Based

  • 단방향 BCrypt** Scrypt SHA-512
  1. SS TagLib

    • access expression <sec:authorize />

    • Authentication Tag <sec:authentication property="name" /> <sec:authentication property="principal.name" />

      <sec:authorized access="hasRole('ADMIN')" />

    • csrf tag

  2. @AuthUser 기존 Security(Spring Interceptor & Annotation) 버리기

  3. Denial Handler

  4. password Encoder (BCrypt Based)

  5. rememberme: 다음 자동 로그인 할때 사용.

  6. SS support AJAX(JSON + WEB response)

  7. filter 최적화

  8. oAuth2

postgresql 확장 모듈 설치

# 현재 설치 가능한 모듈 확인
select * from pg_catalog.pg_available_extensions;

---- 없을 경우 아래와 같이 진행

# 파일 찾기
# [모듈명].control은 해당 모듈 설치를 위한 설정 파일입니다.
find / -name "pgcrypto.control"

# cd /root/postgresql-10.x/contrib/pgcrypto
# (makefile configure 설정이 되어있다고 가정)
# make -f makefile
# make install

위의 과정을 거치면 다음과 같은 파일이 복사 됩니다.

/usr/local/pgsql/share/contrib/pgcrypto.sql
/usr/local/pgsql/share/contrib/uninstall_pgcrypto.sql
/usr/local/pgsql/lib/pgcrypto.so

# 모듈 설치
# [중요]해당 DB 관리자로 접속하여 설치.
# \l 명령어를 통해 해당 DB의 소유자가 누구인지 확인.
# 기본적으로 옵션값을 지정해 주지 않는다면 public 스키마 함수들이 만들어짐.
create extension pgcrypto;

# 현재 설치된 모듈 확인
select * from pg_catalog.pg_extension;

# 함수 사용 TEST
select encode(encrypt(convert_to('jgseo', 'utf-8'), 'utf-8', 'AES'), 'hex');

 

참고


# make 옵션
-f file
file 에 해당하는 파일을 Makefile로써 취급한다.
# pgcrypto--1.3.sql
# DB 함수 구조 GitHub
https://github.com/postgres/postgres/blob/master/contrib/pgcrypto/pgcrypto--1.3.sql
# 참조 사이트
http://tkderm.sourceforge.net/tkdman-1_5_0/node24.html

 

node.js 설치


# yum install npm
# npm --version
# yum install node.js
# node --version
# vi hello.js

	console.log("hello world")
	
# node hello.js

 

● 만약 yum 으로 설치되지 않는다면

# yum install epel-release

다음과 같은 epel 저장소 추가 후 설치.

 

[리눅스] apache - django 연동

apache - django 연동 하기

  1. mod_wsgi 설치
다운로드
# wget https://github.com/GrahamDumpleton/mod_wsgi/archive/4.6.4.tar.gz
# ./configure --with-apxs=/usr/local/cafe24/apache/bin/apxs --with-python=/usr/local/cafe24/python3.7/bin/python3
# make
# make install

 

* 모듈을 만드는 아파치 도구
--with-apxs=/usr/local/cafe24/apache/bin/apxs
  1. 설정

    1) httpd.conf

# 모듈 로딩 추가
LoadModule wsgi_module modules/mod_wsgi.so

2) extra/httpd-vhosts.conf

<VirtualHost *:8888>
    ...

	(내용 추가)
    WSGIScriptAlias / /home/django/python_ch3/python_ch3/wsgi.py
    WSGIDaemonProcess python_ch3 python-path=/home/django/python_ch3/python_ch3

    <Directory "/home/django/python_ch3">
    	(내용 추가)
    	<Files wsgi.py>
            Order allow,deny
            Allow from all
        </Files>
    </Directory>

</VirtualHost>

 

  1. django application 설치

    # cd /home/django
    # mv python_ch3 python_ch3_test
    # git clone https://....
    
  1. venv 에서 서버 띠우기

    # cd python_ch3
    # virtualenv venv
    # source venv/bin/activate
    (venv) # python manage.py runserver 0.0.0.0:9999
    
    [주의]
    1. 방화벽 9999 포트 오픈
    2. settings.py 에서 ALLOWED_HOSTS = ['*']
    
    반드시 확인
    
    
  1. 내부 서버 띠우기
# pip3 install -r python_ch3/requirements.txt --target=python_ch3
# export PYTHONPATH='/home/django/python_ch3'
(서버 실행)
python3 python_ch3/manage.py runserver 0.0.0.0:9999

 

  1. 연동

    wsgi.py 에
    sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
    추가 후, commit
    # git clone ..
    # pip3 install -r python_ch3/requirements.txt --target=python_ch3
    # /etc/init.d/httpd restart
    

     

[리눅스] apache vhost 멀티포트 서비스

apache vhost 설정

● 도메인 기준(같은 포트, 다른 도메인)

● 포트 기준(다른 포트, 다른 도메인) : apache 멀티포트 서비스

 

  1. httpd.conf

    1)

    Listen 80

    Listen 8888 (추가)

    2) DocumentRoot 디렉토리 권한 설정 주석처리

     

#<Directory "/usr/local/cafe24/apache/htdocs">
#    Options Indexes FollowSymLinks
#    AllowOverride None
#    Order allow,deny
#    Allow from all
#</Directory>

3) Virtual Host 설정 파일 주석 해제

# Virtual hosts
Include conf/extra/httpd-vhosts.conf

4) httpd-vhosts.conf 설정

NameVirtualHost *:8888 추가

포트별 VirtualHost설정

NameVirtualHost *:80
NameVirtualHost *:8888

#
# VirtualHost example:
# Almost any Apache directive may go into a VirtualHost container.
# The first VirtualHost section is used for all requests that do not
# match a ServerName or ServerAlias in any <VirtualHost> block.
#
<VirtualHost *:80>
    ServerAdmin jooyg62@naver.com
    DocumentRoot "/usr/local/cafe24/apache/htdocs"
    ErrorLog "logs/localhost.80-error_log"
    CustomLog "logs/localhost.80-access_log" common

    <Directory "/usr/local/cafe24/apache/htdocs">
        Options Indexes FollowSymLinks
        AllowOverride None
        Order allow,deny
        Allow from all
    </Directory>
    
    JkMountFile conf/uriworkermap.properties
    
</VirtualHost>

<VirtualHost *:8888>
    ServerAdmin jooyg62@naver.com
    DocumentRoot "/home/django/python_ch3"
    ErrorLog "logs/localhost.8888-error_log"
    CustomLog "logs/localhost.8888-access_log" common

    <Directory "/home/django/python_ch3">
        Options Indexes FollowSymLinks
        AllowOverride None
        Order allow,deny
        Allow from all
    </Directory>
</VirtualHost>

** tomcat 연동과 함께 할 경우
JkMountFile 설정은 VirtualHost에 할 것!!!!

 

httpd.conf 주석 처리
# JkMountFile conf/uriworkermap.properties

 

 

 

 

'규린이 IT 개발 > 규린이 필살 정리' 카테고리의 다른 글

[리눅스] node.js 설치  (0) 2019.07.03
[리눅스] apache - django 연동  (0) 2019.07.02
[리눅스] python 배포 설정  (0) 2019.07.02
[리눅스] python 설치  (0) 2019.07.01
[centOS] postgreSQL 설치  (0) 2019.06.10

[리눅스] python 배포 설정

 

# os.path.dirname: 상위 디렉토리
BASE_DIR = os.path.dirname(os.path.abspath(__file__))

 

python3 zipapp -p "/usr/bin/cafe24/python3.7/bin/python3" python_crawler
python_crawler.pyz
python3 python_crawler.pyz

 

git 명령어 사용


.gitignore 생성

# .gitignore
.idea/
venv/

 

git rm -r --cached .
git add .
git commit -m '[메시지]'
git push

 

  1. python 설치 시, python aplication 실행(venv 아닌상황)

    1.1export PYTHONPATH='application 의존성 경로'

 

ex>
# git clone https://....
# pip3 install -r python_crawler/requirements.txt --target=python_crawler/packages
# export PYTHONPATH='/root/python-projects/python_crawler'
# python3 python_crawler

1.2 꼭 export PYTHONPATH 를 해야돼?

ex)

ex>
# git clone https://....
# pip3 install -r python_crawler/requirements.txt --target=python_crawler
# python3 python_crawler

1.3 압축

ex>
# git clone https://....
# pip3 install -r python_crawler/requirements.txt --target=python_crawler
# python3 -m zipapp python_crawler
# python3 python_crawler.pyz

 

1.4 실행 가능한 파일로 packaging 하기

ex>
# git clone https://....
# pip3 install -r python_crawler/requirements.txt --target=python_crawler
# python3 -m zipapp -p "/cafe24/python3.7/bin/python3" python_crawler
# ./python_crawler.pyz

 

HTTP -> [8080:tomcat-cafe24] <-- AJP --> [:apache:80] <- HTTP

HTTP -> [9090:tomcat-jenkins(server.xml):9009]

+ Recent posts