base
This commit is contained in:
@@ -0,0 +1,163 @@
|
||||
Revision 1370
|
||||
-------------------
|
||||
수정일 : 2016-05-19
|
||||
수정자 : 유희곤
|
||||
|
||||
- CHG: help 기능 추가 (#27605)
|
||||
- 다른 RCTS 모듈들과 유사한 help 표시 기능 추가
|
||||
- 추가 옵션 관련 설명 추가.
|
||||
|
||||
- NEW: main, worker 프로세스 구분을 위한 표시기능 추가.
|
||||
|
||||
- BUG: Worker 종료시 return 코드 관련 문제점 수정
|
||||
- Worker 종료시 반환되는 return 코드를 무조건 정상으로 처리하여
|
||||
- 초기화 실패 상황에도 무조건 Worker 재기동 발생 가능.
|
||||
- 이에 대한 수정 처리.
|
||||
|
||||
- CHG: ftsd 연동 interface Revision 1364 버전 적용
|
||||
- ftsd Revision 1364 에 적용된 Data 수신 Timeout 수정 기능 적용을 위해
|
||||
- 해당 ftsd interface 관련 파일 업데이트 적용.
|
||||
|
||||
- CHG: 로그 가독성 향상
|
||||
- 로그 표시 내역 정리 및 가독성 향상
|
||||
|
||||
- CHG: 줄 끝 처리 관련 unix 형식으로 변경 처리 저장.
|
||||
- main.cpp Worker.cpp
|
||||
|
||||
- CHG: g++ 4.8.5 컴파일 관련
|
||||
- 컴파일 미지원 waring 발생 관련 -Wimplicit 옵션 제거
|
||||
- sleep() 함수 사용 관련 unistd.h header 추가.
|
||||
|
||||
|
||||
Revision 1244
|
||||
-------------------
|
||||
수정일 : 2015-09-23
|
||||
수정자 : 김오종
|
||||
|
||||
- CHG: 최신 BaseSocket 모듈 적용 (#24369, #24141)
|
||||
- EPIPE 및 usleep 관련 수정 버전 적용
|
||||
- 수정 파일: lib/BaseSocket.cpp
|
||||
|
||||
- CHG: usleep -> nanosleep 변경 (#24537)
|
||||
- multi thread 에서 lock 관련 문제점 발생 가능.
|
||||
- 수정 파일: Main.cpp, Worker.cpp
|
||||
|
||||
- CHG: Main 버전 (3.5.0) 변경 사항 적용
|
||||
- 기존 3.4.0 -> 3.5.0 으로 버전 변경 처리.
|
||||
|
||||
|
||||
Revision 1135
|
||||
-------------------
|
||||
수정일 : 2014-11-18
|
||||
수정자 : 김오종
|
||||
|
||||
- BUG: 폴더 속성 row에 대한 삭제 안되는 버그 수정
|
||||
- 폴더 속성일 경우 filename_hash 조건 배제
|
||||
|
||||
- CHG: 프로그램 종료시 core 발생 가능성 제거
|
||||
- 프로그램 종료시 전역객체 소멸 후 참조 되어 core발생
|
||||
- 이를 해결하기 위해 WorkMain()함수로 객체 소멸 이동 처리
|
||||
|
||||
Revision 1127
|
||||
-------------------
|
||||
수정일 : 2014-11-17
|
||||
수정자 : 김오종
|
||||
|
||||
- CHG: DNS resolve 실패시 Retry 기능 추가 (#20812, #20783)
|
||||
- 통신 접속 관련 lib/CBaseSocket 모듈에서
|
||||
- getaddrinfo() 의 DNS resolve 실패가 자주 발생함.
|
||||
- 오류코드 FreeBSD : EAI_NONAME(8), Linux: EAI_AGAIN(-3)
|
||||
- 이에 3회 재시도 기능 추가
|
||||
- 수정파일: lib/BaseSocket.cpp
|
||||
|
||||
Revision 1107
|
||||
-------------------
|
||||
수정일 : 2014-10-30
|
||||
수정자 : 김오종
|
||||
|
||||
- NEW: RCDB 로그, 모니터링 상에 application_name 정보 표시되도록 기능 추가
|
||||
- RCDB 연결 관련 PgOpenDB() 함수 호출시
|
||||
- " application_name=" << PROG_NAME; 을 추가하여
|
||||
- RCDB 로그, 모니터링 정보 상에 정보가 표시되도록 한다.
|
||||
- 수정: Database.cpp
|
||||
|
||||
Revision 1040
|
||||
-------------------
|
||||
수정일 : 2014-07-30
|
||||
수정자 : 김오종
|
||||
|
||||
- CHG: CompleteJob Queue 적체 현상 해결
|
||||
- m_threadHandle값에 대해 초기화 및 검증 절차를 넣어 엉뚱한 Thread가 cancel되지 않도록 조정
|
||||
- CHG: RCDB 스키마 변경에 따른 수정
|
||||
- t_dav_resource 테이블에서 t_meta_#service_id# 로 변경됨에 따라..
|
||||
- 두 가지 스키마 모두를 지원하도록 소스 수정
|
||||
|
||||
Revision 985
|
||||
-------------------
|
||||
수정일 : 2014-04-21
|
||||
수정자 : 김오종
|
||||
|
||||
- DEL: report log 클랙스 삭제
|
||||
- CHG: 하나의 FHS에 동일한 filename_hash를 갖는 컨텐츠가 있을 경우..
|
||||
- 기존에는 report log에 보고하고, 차 후에 수동 삭제했었으나..
|
||||
- rc_gcmd 자체에서 판단하여 삭제하도록 변경
|
||||
|
||||
Revision 926
|
||||
-------------------
|
||||
수정일 : 2014-01-13
|
||||
수정자 : 김오종
|
||||
|
||||
- CHG: report log에 대한 형식변경 및 메세지 간소화
|
||||
|
||||
Revision 898
|
||||
-------------------
|
||||
수정일 : 2013-10-17
|
||||
수정자 : 김오종
|
||||
|
||||
- CHG: conf file의 MAX_DELETE_THREAD 값을 기존 최대 20에서 100으로 조정하고 기본 권장 설정값을 20으로 조정
|
||||
- ADD: 컨텐츠 삭제를 진행 함에 있어 현재 업무 flow상 발생하면 안되는 현상이 발생했을경우 report 로그에 기록 하도록 기능 추가
|
||||
- 위 설명과 같은 현상이 있을 경우 데몬 로그파일에만 기록하였던 것을 report 로그에도 기록 함
|
||||
- 이와 같이 한 배경은 위 상황이 발현됨에 따라 정확한 원인이 파악되기 전까지 운영으로 대처 하기 위함 임
|
||||
|
||||
Revision 868
|
||||
-------------------
|
||||
수정일 : 2013-04-23
|
||||
수정자 : 김오종
|
||||
|
||||
- CHG: PhysicalDeleteThread Class의 개수를 조정하는 부분 버그
|
||||
- Worker에 있는 AddJobThreadCount()함수를 PhysicalDeleteThread의 Start() 함수로 이동
|
||||
|
||||
Revision 852
|
||||
-------------------
|
||||
수정일 : 2013-02-26
|
||||
수정자 : 김오종
|
||||
|
||||
- CHG: 삭제요청 파일에 대한 검증시 쿼리 문 변경
|
||||
- 동일한 filename_hash 로 존재하는 파일을 검증하는 절차에서 쿼리를 아래와 같이 변경함
|
||||
- filename_hash ,컨텐츠 크기, 삭제여부 -> host_name, filename_hash, 삭제여부
|
||||
|
||||
Revision 841
|
||||
-------------------
|
||||
수정일 : 2012-11-27
|
||||
수정자 : 김오종
|
||||
|
||||
- CHG: GetContentsList 로직 수정
|
||||
- TranID 에 대한 인덱스를 타게됨에 따라 DB 부하가 많아지는 현상 해결
|
||||
- 구간 별로 limit 를 주는 쿼리로 변경 처리 함
|
||||
|
||||
- CHG: 삭제 쓰레드의 최대 수를 10개에서 20 개로 변경
|
||||
|
||||
- CHG: CategorizeThread.cpp 의 내용 중 확인 쿼리에 host_name 필드 추가 select
|
||||
|
||||
- CHG: 본 데몬 시작시 삭제 컨텐츠 조회 기간으 시작 시점 구동 파라메터로 추가 함
|
||||
|
||||
- CHG: Log Level 조정
|
||||
|
||||
|
||||
Revision 833
|
||||
-------------------
|
||||
수정일 : 2012-11-14
|
||||
수정자 : 김오종
|
||||
|
||||
- NEW: SVN 신규 등록
|
||||
- rc_gcmd 소스 등록
|
||||
@@ -0,0 +1,37 @@
|
||||
#****************************************************************************
|
||||
# Makefile for rc_cchkd
|
||||
# -----------------------------------------
|
||||
#
|
||||
# begin : 2012/08/08
|
||||
# copyright : (C) 2012 SolutionBox Inc.
|
||||
# author : Service 1 Team
|
||||
# email : svc1@solbox.com
|
||||
# version : 3.2.0
|
||||
#
|
||||
# CopyRight(C) 2005 SolutionBox Inc. All Rights reserved.
|
||||
# Redistribution and use in source and binary forms, with or with out
|
||||
# modification, are not permitted in outside of SolutionBox Inc.
|
||||
#*****************************************************************************
|
||||
|
||||
SUBDIRS = lib src
|
||||
|
||||
.PHONY: all $(SUBDIRS)
|
||||
|
||||
|
||||
all: $(SUBDIRS)
|
||||
sync;
|
||||
|
||||
|
||||
$(SUBDIRS):
|
||||
$(MAKE) all -C $@
|
||||
|
||||
|
||||
install:
|
||||
@for dir in $(SUBDIRS); do (cd $$dir; $(MAKE) install); done
|
||||
|
||||
|
||||
clean:
|
||||
@for dir in $(SUBDIRS); do (cd $$dir; $(MAKE) clean); done
|
||||
|
||||
|
||||
# End of Makefile
|
||||
@@ -0,0 +1,595 @@
|
||||
#include "BaseSocket.h"
|
||||
|
||||
|
||||
#include <sys/select.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/types.h>
|
||||
#include <netinet/in.h>
|
||||
#include <arpa/inet.h>
|
||||
#include <netdb.h>
|
||||
#include <errno.h>
|
||||
#include <string.h>
|
||||
#include <stdlib.h>
|
||||
#include <time.h>
|
||||
|
||||
|
||||
#define SOCKET_NOT_VALID -1
|
||||
#define MAX_SEND_RETRY_COUNT 10 // Socket send 실패시 최대 재전송 시도 횟수.
|
||||
|
||||
|
||||
/// @brief 생성자.
|
||||
/// @param socket [in] 처리할 socket descriptor
|
||||
CBaseSocket::CBaseSocket( const int& socket )
|
||||
: m_sock( socket )
|
||||
{
|
||||
if( m_sock < 0 )
|
||||
{
|
||||
m_sock = SOCKET_NOT_VALID;
|
||||
m_bConnected = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
m_bConnected = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// @brief 소멸자
|
||||
CBaseSocket::~CBaseSocket()
|
||||
{
|
||||
// 소멸자 Socket 명시적 Close 처리.
|
||||
Close();
|
||||
}
|
||||
|
||||
/// @brief 소켓의 Close 처리를 수행함.
|
||||
void CBaseSocket::Close()
|
||||
{
|
||||
m_bConnected = false;
|
||||
|
||||
if( m_sock != SOCKET_NOT_VALID )
|
||||
{
|
||||
close( m_sock );
|
||||
m_sock = SOCKET_NOT_VALID;
|
||||
}
|
||||
}
|
||||
|
||||
/// @brief 전달받은 Target 으로 Socket 접속을 수행
|
||||
/// @param szTarget [in] 접속 대상 Host name 또는 IP
|
||||
/// @param nPort [in] 접속 Port
|
||||
/// @return 접속 성공시 true, 실패시 false 반환. ( 오류 내역은 로깅처리됨.)
|
||||
bool CBaseSocket::Connect( const std::string& szTarget, int nPort )
|
||||
{
|
||||
// 기존 접속을 Close 처리
|
||||
Close();
|
||||
|
||||
unsigned int nHost = ConversionAddr( szTarget.c_str() );
|
||||
if( nHost == INADDR_NONE )
|
||||
{
|
||||
LOG( LERR, "target host name resolve fail. [%s]->INADDR_NONE", szTarget.c_str());
|
||||
return false;
|
||||
}
|
||||
|
||||
struct sockaddr_in stTargetAddr;
|
||||
|
||||
m_sock = socket(AF_INET, SOCK_STREAM, 0);
|
||||
if( m_sock == -1 )
|
||||
{
|
||||
int errorNum = errno;
|
||||
|
||||
LOG( LERR, "socket create failed.[%d][%s] Target:[%s]", errorNum, strerror(errorNum), szTarget.c_str() );
|
||||
|
||||
m_sock = SOCKET_NOT_VALID;
|
||||
return false;
|
||||
}
|
||||
|
||||
stTargetAddr.sin_family = AF_INET;
|
||||
stTargetAddr.sin_addr.s_addr = nHost;
|
||||
stTargetAddr.sin_port = htons( nPort );
|
||||
|
||||
// NEW 2012-05-18 huibong
|
||||
// Connnection 종료시 많은 TIME_WAIT 상태 발생으로 인해 .. 이를 제거하기 위해 SO_LINGER 옵션을 설정처리한다.
|
||||
struct linger opt_linger;
|
||||
opt_linger.l_onoff = 1; /* LINGER ON */
|
||||
|
||||
// CHG 2014-05-27 huibong
|
||||
// 아래와 같이 No Wait 로 처리할 경우... Server 역활 수행 중 Close 신호를 받지 못하는 경우가 발생 가능함.
|
||||
// 따라서 5 sec 정도 대기하도록 수정 처리한다.
|
||||
//opt_linger.l_linger = 0; /* No Wait => 0 for abortive disconnect */
|
||||
opt_linger.l_linger = 5; // 5 sec 대기
|
||||
|
||||
int result = setsockopt( m_sock, SOL_SOCKET, SO_LINGER, &opt_linger, sizeof(opt_linger));
|
||||
if( result != 0 )
|
||||
{
|
||||
int errorNum = errno;
|
||||
LOG( LERR, "setsockopt func SO_LINGER set fail.[%d][%s]", errorNum, strerror(errorNum));
|
||||
|
||||
}
|
||||
|
||||
/* Send Timeout 설정. */
|
||||
struct timeval tv_timeo = { 5, 0 };
|
||||
|
||||
result = setsockopt( m_sock, SOL_SOCKET, SO_SNDTIMEO, &tv_timeo, sizeof(tv_timeo));
|
||||
if( result != 0 )
|
||||
{
|
||||
int errorNum = errno;
|
||||
LOG( LERR, "setsockopt func SO_SNDTIMEO set fail.[%d][%s]", errorNum, strerror(errorNum));
|
||||
|
||||
}
|
||||
|
||||
if(connect(m_sock, (struct sockaddr *)&stTargetAddr, sizeof(stTargetAddr)) < 0 )
|
||||
{
|
||||
int errorNum = errno;
|
||||
LOG( LERR, "connect fail.[%s][%d] [%d][%s]", szTarget.c_str(), nPort, errorNum, strerror( errorNum ) );
|
||||
|
||||
Close();
|
||||
return false;
|
||||
}
|
||||
else
|
||||
{
|
||||
m_bConnected = true;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// @brief 멤버 변수인 m_sock 이 유효하고 연결된 상태인 경우 true 반환.
|
||||
/// @return socket이 유효하지 않거나 연결이 끊어지 경우 false 반환, 그외에는 true 반환.
|
||||
bool CBaseSocket::IsValidSocket()
|
||||
{
|
||||
if( m_sock != SOCKET_NOT_VALID && m_bConnected == true )
|
||||
return true;
|
||||
else
|
||||
return false;
|
||||
}
|
||||
|
||||
/// @brief m_sock 으로부터 지정된 size 만큼 데이터 read 를 시도 ( read 함수와 동일 )
|
||||
/// @param vptr [out] Read 된 데이터를 저장하기 위한 변수에 대한 포인터.
|
||||
/// @param size [in] read 하고자 하는 데이터의 크기.
|
||||
/// @return read 된 데이터의 크기. 0: fd closed, -1: 오류
|
||||
ssize_t CBaseSocket::Read( void * vptr, size_t size )
|
||||
{
|
||||
if( IsValidSocket() == false )
|
||||
return 0;
|
||||
|
||||
ssize_t nRead = 0;
|
||||
while( (nRead = read( m_sock, vptr, size )) < 0 )
|
||||
{
|
||||
int errorNum = errno;
|
||||
if( errorNum == EINTR || errorNum == EAGAIN || errorNum == EWOULDBLOCK )
|
||||
{
|
||||
nRead = 0;
|
||||
continue;
|
||||
}
|
||||
else if( errorNum == ECONNRESET || errorNum == EPIPE )
|
||||
{
|
||||
// 2010-07-23 BUG huibong 잘못된 대입연산자를 비교연산자로 수정.
|
||||
// 2015-08-28 CHG huibong EPIPE(32) 오류 발생시.. 연결 종료로 처리되도록 수정
|
||||
m_bConnected = false;
|
||||
return 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
LOG( LERR, "read func fail.[%d][%s]", errorNum, strerror(errorNum) );
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
return nRead;
|
||||
}
|
||||
|
||||
/// @brief m_sock 로부터 지정된 size 만큼 read 를 시도, \n
|
||||
///< 만약 지정된 크기만큼 데이터가 존재하지 않을 경우 해당 크기만큼 데이터를 read 할때까지 대기.
|
||||
/// @param vptr [out] Read 된 데이터를 저장하기 위한 변수에 대한 포인터.
|
||||
/// @param size [in] read 하고자 하는 데이터의 크기.
|
||||
/// @return read 된 데이터의 크기. 0: fd closed, -1: 오류
|
||||
ssize_t CBaseSocket::ReadN( void * vptr, size_t size )
|
||||
{
|
||||
if( IsValidSocket() == false )
|
||||
return 0;
|
||||
|
||||
ssize_t nRead = 0;
|
||||
size_t nLeft = size;
|
||||
char * ptr = (char *)vptr;
|
||||
|
||||
while( nLeft > 0 )
|
||||
{
|
||||
if( (nRead = read( m_sock, ptr, nLeft )) < 0 )
|
||||
{
|
||||
int errorNum = errno;
|
||||
if( errorNum == EINTR || errorNum == EAGAIN || errorNum == EWOULDBLOCK )
|
||||
{
|
||||
nRead = 0;
|
||||
continue;
|
||||
}
|
||||
else if( errorNum == ECONNRESET || errorNum == EPIPE )
|
||||
{
|
||||
// 2015-08-28 CHG huibong EPIPE(32) 오류 발생시.. 연결 종료로 처리되도록 수정
|
||||
m_bConnected = false;
|
||||
return 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
LOG( LERR, "read func fail.[%d][%s]", errorNum, strerror(errorNum) );
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
else if( nRead == 0 )
|
||||
{
|
||||
m_bConnected = false;
|
||||
return 0;
|
||||
}
|
||||
|
||||
nLeft -= nRead;
|
||||
ptr += nRead;
|
||||
}
|
||||
|
||||
return size;
|
||||
}
|
||||
|
||||
/// @brief m_sock 로부터 지정된 size 만큼 read 를 시도, \n
|
||||
///< 만약 지정된 크기만큼 데이터가 존재하지 않을 경우 해당 크기만큼 데이터를 read 할때까지 대기. \n
|
||||
///< 또는 지정된 Timeout 값 동안 read 를 하지 못하는 경우 오류 처리.
|
||||
/// @param vptr [out] Read 된 데이터를 저장하기 위한 변수에 대한 포인터.
|
||||
/// @param size [in] read 하고자 하는 데이터의 크기.
|
||||
/// @param timeout [in] Timeout value (sec)
|
||||
/// @return read 된 데이터의 크기. 0: fd closed, -1: 오류 , -2: Timeout
|
||||
ssize_t CBaseSocket::ReadNTimeout( void * vptr, size_t size, int timeout )
|
||||
{
|
||||
if( IsValidSocket() == false )
|
||||
return 0;
|
||||
|
||||
ssize_t nRead = 0;
|
||||
size_t nLeft = size;
|
||||
char * ptr = (char *)vptr;
|
||||
|
||||
struct timeval timeOver;
|
||||
int result;
|
||||
|
||||
fd_set selectFds;
|
||||
FD_ZERO( &selectFds );
|
||||
|
||||
while( nLeft > 0 )
|
||||
{
|
||||
timeOver.tv_sec = timeout;
|
||||
timeOver.tv_usec = 0;
|
||||
FD_SET( m_sock, &selectFds );
|
||||
|
||||
result = select( m_sock+1, &selectFds, (fd_set *)NULL, (fd_set *)NULL, &timeOver );
|
||||
|
||||
if( result > 0 )
|
||||
{
|
||||
if( FD_ISSET( m_sock, &selectFds ))
|
||||
{
|
||||
if( (nRead = read( m_sock, ptr, nLeft) ) < 0 )
|
||||
{
|
||||
int errorNum = errno;
|
||||
if(errorNum == EINTR || errorNum == EAGAIN || errorNum == EWOULDBLOCK)
|
||||
{
|
||||
nRead = 0;
|
||||
continue;
|
||||
}
|
||||
else if( errorNum == ECONNRESET || errorNum == EPIPE )
|
||||
{
|
||||
// 2015-08-28 CHG huibong EPIPE(32) 오류 발생시.. 연결 종료로 처리되도록 수정
|
||||
m_bConnected = false;
|
||||
return 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
LOG( LERR, "read func fail.[%d][%s]", errorNum, strerror(errorNum) );
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
else if( nRead == 0 )
|
||||
{
|
||||
m_bConnected = false;
|
||||
return 0;
|
||||
}
|
||||
|
||||
nLeft -= nRead;
|
||||
ptr += nRead;
|
||||
}
|
||||
|
||||
}
|
||||
else if( result == 0 ) // Timeout
|
||||
{
|
||||
//LOG( LDBG, "read timeout");
|
||||
return -2;
|
||||
}
|
||||
else
|
||||
{
|
||||
int errorNum = errno;
|
||||
LOG( LERR, "select func error.[%d][%s]", errorNum, strerror(errorNum) );
|
||||
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
return size;
|
||||
}
|
||||
|
||||
/// @brief m_sock 로부터 지정된 size 만큼 read 를 시도, \n
|
||||
///< 만약 지정된 크기만큼 데이터가 존재하지 않을 경우 해당 크기만큼 데이터를 read 할때까지 대기. \n
|
||||
///< 또는 지정된 Timeout 값 동안 read 를 하지 못하는 경우 오류 처리.
|
||||
///< 본 함수는 Socket 상에 이미 Data 가 존재하는 경우에만 사용.
|
||||
/// @param vptr [out] Read 된 데이터를 저장하기 위한 변수에 대한 포인터.
|
||||
/// @param size [in] read 하고자 하는 데이터의 크기.
|
||||
/// @param timeout [in] Timeout value (sec)
|
||||
/// @return read 된 데이터의 크기. 0: fd closed, -1: 오류, -2: Timeout
|
||||
ssize_t CBaseSocket::ReadNTimeout2( void * vptr, size_t size, int timeout )
|
||||
{
|
||||
if( IsValidSocket() == false )
|
||||
return 0;
|
||||
|
||||
ssize_t nRead = 0;
|
||||
size_t nLeft = size;
|
||||
char * ptr = (char *)vptr;
|
||||
int errorNum;
|
||||
|
||||
// 우선은 읽기 시도.
|
||||
if( (nRead = read( m_sock, ptr, nLeft) ) < 0 )
|
||||
{
|
||||
errorNum = errno;
|
||||
if( errorNum == EINTR || errorNum == EAGAIN || errorNum == EWOULDBLOCK )
|
||||
{
|
||||
nRead = 0;
|
||||
}
|
||||
else if( errorNum == ECONNRESET || errorNum == EPIPE )
|
||||
{
|
||||
// 2015-08-28 CHG huibong EPIPE(32) 오류 발생시.. 연결 종료로 처리되도록 수정
|
||||
|
||||
m_bConnected = false;
|
||||
return 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
LOG( LERR, "read func fail.[%d][%s]", errorNum, strerror(errorNum) );
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
else if( nRead == 0 )
|
||||
{
|
||||
m_bConnected = false;
|
||||
return 0;
|
||||
}
|
||||
|
||||
nLeft -= nRead;
|
||||
ptr += nRead;
|
||||
|
||||
// 만약 더 받을 데이터가 존재한다면.
|
||||
if( nLeft > 0 )
|
||||
{
|
||||
struct timeval timeOver;
|
||||
int result;
|
||||
|
||||
fd_set selectFds;
|
||||
FD_ZERO( &selectFds );
|
||||
|
||||
while( nLeft > 0 )
|
||||
{
|
||||
timeOver.tv_sec = timeout;
|
||||
timeOver.tv_usec = 0;
|
||||
FD_SET( m_sock, &selectFds );
|
||||
|
||||
result = select( m_sock+1, &selectFds, (fd_set *)NULL, (fd_set *)NULL, &timeOver );
|
||||
|
||||
if( result > 0 )
|
||||
{
|
||||
if( FD_ISSET( m_sock, &selectFds ))
|
||||
{
|
||||
if( (nRead = read( m_sock, ptr, nLeft) ) < 0 )
|
||||
{
|
||||
errorNum = errno;
|
||||
if(errorNum == EINTR || errorNum == EAGAIN || errorNum == EWOULDBLOCK)
|
||||
{
|
||||
nRead = 0;
|
||||
continue;
|
||||
}
|
||||
else if( errorNum == ECONNRESET || errorNum == EPIPE )
|
||||
{
|
||||
// 2015-08-28 CHG huibong EPIPE(32) 오류 발생시.. 연결 종료로 처리되도록 수정
|
||||
m_bConnected = false;
|
||||
return 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
LOG( LERR, "read func fail.[%d][%s]", errorNum, strerror(errorNum) );
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
else if( nRead == 0 )
|
||||
{
|
||||
m_bConnected = false;
|
||||
return 0;
|
||||
}
|
||||
|
||||
nLeft -= nRead;
|
||||
ptr += nRead;
|
||||
}
|
||||
}
|
||||
else if( result == 0 ) // Timeout
|
||||
{
|
||||
//LOG( LDBG, "read timeout");
|
||||
return -2;
|
||||
}
|
||||
else
|
||||
{
|
||||
errorNum = errno;
|
||||
LOG( LERR, "select func error.[%d][%s]", errorNum, strerror(errorNum) );
|
||||
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return size;
|
||||
}
|
||||
|
||||
/// @brief m_sock 으로 지정된 크기만큼 vptr 의 데이터를 전송 시도.\n
|
||||
///< Send Timeout 옵션 설정으로 Write Timeout 설정 가능. \n
|
||||
///< 지정된 횟수만큼 재전송 실패시 오류로 처리함.
|
||||
/// @param vptr [in] 전달할 데이터를 저장한 변수에 대한 포인터.
|
||||
/// @param size [in] write 하고자 하는 데이터의 크기.
|
||||
/// @return write 된 데이터의 크기. 0: fd closed, -1: 오류
|
||||
ssize_t CBaseSocket::WriteN( const void * vptr, size_t size )
|
||||
{
|
||||
if( IsValidSocket() == false )
|
||||
return 0;
|
||||
|
||||
size_t nLeft;
|
||||
ssize_t nWrite;
|
||||
|
||||
const char * ptr = (const char *)vptr;
|
||||
nLeft = size;
|
||||
|
||||
int nTryCount = 0;
|
||||
|
||||
while( nLeft > 0 )
|
||||
{
|
||||
if( (nWrite = send( m_sock, ptr, nLeft, 0 )) < 0 )
|
||||
{
|
||||
int errorNum = errno;
|
||||
|
||||
if( errorNum == EINTR || errorNum == EAGAIN || errorNum == EWOULDBLOCK )
|
||||
{
|
||||
nWrite = 0;
|
||||
++nTryCount;
|
||||
}
|
||||
else if( errorNum == ECONNRESET || errorNum == EPIPE )
|
||||
{
|
||||
// 2015-08-28 CHG huibong EPIPE(32) 오류 발생시.. 연결 종료로 처리되도록 수정
|
||||
m_bConnected = false;
|
||||
return 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
LOG( LERR, "send func fail.[%d][%s]", errorNum, strerror(errorNum));
|
||||
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
else if( nWrite == 0 )
|
||||
{
|
||||
m_bConnected = false;
|
||||
return 0;
|
||||
}
|
||||
|
||||
if( nTryCount > MAX_SEND_RETRY_COUNT )
|
||||
{
|
||||
LOG( LERR, "send func failure due to exceeding count of retry[%d/%d]", nTryCount, MAX_SEND_RETRY_COUNT );
|
||||
return 0 ;
|
||||
}
|
||||
|
||||
nLeft -= nWrite;
|
||||
ptr += nWrite;
|
||||
}
|
||||
|
||||
return size;
|
||||
}
|
||||
|
||||
// CHG 2011-05-03 huibong
|
||||
// gethostbyname() 함수가 Thread Safe 하지 않기 때문에
|
||||
// DNS resolve 처리시 잘못된 정보를 반환할 가능성이 존재
|
||||
// 이에 따라 본 함수를 수정처리함.
|
||||
/*
|
||||
unsigned int CBaseSocket::ConversionAddr( const char * name )
|
||||
{
|
||||
struct hostent *he;
|
||||
int max;
|
||||
unsigned int retval;
|
||||
|
||||
if ((retval = inet_addr(name)) != INADDR_NONE)
|
||||
return retval;
|
||||
|
||||
he = gethostbyname(name);
|
||||
if (he == NULL)
|
||||
return INADDR_NONE;
|
||||
|
||||
for (max = 0; he->h_addr_list[max]; max++) ;
|
||||
if (max == 1)
|
||||
return *((unsigned int *)(he->h_addr_list[0]));
|
||||
else
|
||||
return *((unsigned int *)(he->h_addr_list[random() % max]));
|
||||
}
|
||||
*/
|
||||
|
||||
unsigned int CBaseSocket::ConversionAddr( const char * name )
|
||||
{
|
||||
unsigned int retval;
|
||||
struct addrinfo hints;
|
||||
struct addrinfo *result = NULL;
|
||||
int error;
|
||||
|
||||
|
||||
// 전달받은 정보가 IP 주소인 경우...
|
||||
// - DNS resolve 할 필요 없이 변환시킨 값을 그대로 사용한다.
|
||||
if( (retval = inet_addr(name)) != INADDR_NONE )
|
||||
return retval;
|
||||
|
||||
// getaddrinfo() 함수 호출을 위한 Hint 설정
|
||||
memset( &hints, 0x00, sizeof(hints));
|
||||
hints.ai_family = PF_UNSPEC;
|
||||
hints.ai_socktype = SOCK_STREAM;
|
||||
|
||||
// Thread Safe 한 DNS Resolve 처리함수 호출
|
||||
// int getaddrinfo(const char *hostname, const char *servname, const struct addrinfo *hints, struct addrinfo **res);
|
||||
|
||||
// CHG 2014-11-14 huibong
|
||||
// getaddrinfo 호출시 종종 EAI_NONAME 오류가 반환됨. (#20783)
|
||||
// - 따라서 오류 반환시 재시도하도록 기능 추가
|
||||
// CHG 2015-07-15 huibong
|
||||
// usleep 의 multi thread 상에서 block 발생 가능
|
||||
// - nanosleep 을 사용토록 변경 처리
|
||||
for( int count = 0 ; count < 3; count++ )
|
||||
{
|
||||
error = getaddrinfo( name, NULL, &hints, &result );
|
||||
|
||||
// 오류 발생시
|
||||
if( error != 0 )
|
||||
{
|
||||
if( result != NULL)
|
||||
{
|
||||
freeaddrinfo(result);
|
||||
result = NULL;
|
||||
}
|
||||
|
||||
// 잠시 대기 후 재시도 처리
|
||||
struct timespec sleep;
|
||||
sleep.tv_sec = 0;
|
||||
sleep.tv_nsec = 500000000; // 0.5 sec
|
||||
nanosleep( &sleep, NULL );
|
||||
}
|
||||
else
|
||||
{
|
||||
// 정상 처리된 경우...
|
||||
// - loop 탈출
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// 최종 오류 발생시
|
||||
if( error != 0 )
|
||||
{
|
||||
LOG( LERR, "name[%s] dns resolve fail. getaddrinfo return error [%d][%s]", name, error, gai_strerror(error) );
|
||||
return INADDR_NONE;
|
||||
}
|
||||
|
||||
struct sockaddr_in * addr = (struct sockaddr_in *)result->ai_addr;
|
||||
retval = (unsigned int)(addr->sin_addr.s_addr);
|
||||
|
||||
// DNS Resovle 결과 확인용 코드
|
||||
/*
|
||||
struct addrinfo *temp;
|
||||
for( temp = result; temp; temp = temp->ai_next )
|
||||
{
|
||||
addr = (struct sockaddr_in *)temp->ai_addr;
|
||||
printf ("getaddrinfo result = %s\n",inet_ntoa( addr->sin_addr));
|
||||
}
|
||||
*/
|
||||
|
||||
// getaddrinfo() 함수에서 생성한 메모리 영역 해제 처리.
|
||||
freeaddrinfo(result);
|
||||
|
||||
return retval;
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
/***************************************************************************
|
||||
BaseSocket ( Base Socket Class )
|
||||
-----------------------------------------
|
||||
begin : 2010/03/02
|
||||
copyright : (C) 2005 SolutionBox Inc.
|
||||
author : Service 1 Team
|
||||
email : svc1@solbox.com
|
||||
version : 1.0
|
||||
|
||||
CopyRight(C) 2005 SolutionBox Inc. All Rights reserved.
|
||||
Redistribution and use in source and binary forms, with or with out
|
||||
modification, are not permitted in outside of SolutionBox Inc.
|
||||
***************************************************************************/
|
||||
|
||||
#ifndef __LIBRARY_BASE_SOCKET_H__
|
||||
#define __LIBRARY_BASE_SOCKET_H__
|
||||
|
||||
#include <unistd.h>
|
||||
#include <sys/types.h>
|
||||
|
||||
#include "Logger.h"
|
||||
|
||||
#define SOCKET_NOT_VALID -1
|
||||
#define DEFAULT_DATA_RECEIVE_TIMEOUT 15 // sec
|
||||
|
||||
|
||||
class CBaseSocket
|
||||
{
|
||||
|
||||
protected:
|
||||
|
||||
/// @brief socket descriptor
|
||||
int m_sock;
|
||||
|
||||
/// @brief socket 의 연결상태인지 여부를 저장하기 위한 변수.
|
||||
bool m_bConnected;
|
||||
|
||||
|
||||
public:
|
||||
|
||||
/// @brief 생성자.
|
||||
CBaseSocket( const int & socket );
|
||||
|
||||
/// @brief 소멸자.
|
||||
~CBaseSocket();
|
||||
|
||||
/// @brief 소켓의 Close 처리를 수행함.
|
||||
void Close(void);
|
||||
|
||||
/// @brief 전달받은 Target 으로 Socket 접속을 수행
|
||||
/// @param szTarget [in] 접속 대상 Host name 또는 IP
|
||||
/// @param nPort [in] 접속 Port
|
||||
/// @return 접속 성공시 true, 실패시 false 반환. ( 오류 내역은 로깅처리됨.)
|
||||
bool Connect( const std::string& szTarget, int nPort );
|
||||
|
||||
/// @brief 멤버 변수인 m_sock 이 유효하고 연결된 상태인 경우 true 반환.
|
||||
/// @return socket이 유효하지 않거나 연결이 끊어지 경우 false 반환, 그외에는 true 반환.
|
||||
bool IsValidSocket(void);
|
||||
|
||||
/// @brief 멤버변수인 socket 의 접속 상태 여부를 설정하기 위한 함수.
|
||||
void SetConnectionStatus( bool bConnected) { m_bConnected = bConnected; }
|
||||
|
||||
/// @brief 현재 socket 의 접속 상태를 반환.
|
||||
bool GetConnectionStatus( void) { return m_bConnected; }
|
||||
|
||||
//void SetLogger( Logger * pLog ) { m_pLog = pLog; }
|
||||
|
||||
protected:
|
||||
|
||||
/// @brief m_sock 로 부터 지정된 size 만큼 데이터 read 를 시도 ( read 함수와 동일 )
|
||||
/// @param vptr [out] Read 된 데이터를 저장하기 위한 변수에 대한 포인터.
|
||||
/// @param size [in] read 하고자 하는 데이터의 크기.
|
||||
/// @return read 된 데이터의 크기. 0: fd closed, -1: 오류
|
||||
ssize_t Read( void * vptr, size_t size );
|
||||
|
||||
/// @brief m_sock 로부터 지정된 size 만큼 read 를 시도, \n
|
||||
///< 만약 지정된 크기만큼 데이터가 존재하지 않을 경우 해당 크기만큼 데이터를 read 할때까지 대기.
|
||||
/// @param vptr [out] Read 된 데이터를 저장하기 위한 변수에 대한 포인터.
|
||||
/// @param size [in] read 하고자 하는 데이터의 크기.
|
||||
/// @return read 된 데이터의 크기. 0: fd closed, -1: 오류
|
||||
ssize_t ReadN( void * vptr, size_t size );
|
||||
|
||||
/// @brief m_sock 로부터 지정된 size 만큼 read 를 시도, \n
|
||||
///< 만약 지정된 크기만큼 데이터가 존재하지 않을 경우 해당 크기만큼 데이터를 read 할때까지 대기. \n
|
||||
///< 또는 지정된 Timeout 값 동안 read 를 하지 못하는 경우 오류 처리.
|
||||
/// @param vptr [out] Read 된 데이터를 저장하기 위한 변수에 대한 포인터.
|
||||
/// @param size [in] read 하고자 하는 데이터의 크기.
|
||||
/// @param timeout [in] Timeout value (sec)
|
||||
/// @return read 된 데이터의 크기. 0: fd closed, -1: 오류, -2: Timeout
|
||||
ssize_t ReadNTimeout( void * vptr, size_t size, int timeout = DEFAULT_DATA_RECEIVE_TIMEOUT );
|
||||
|
||||
/// @brief m_sock 로부터 지정된 size 만큼 read 를 시도, \n
|
||||
///< 만약 지정된 크기만큼 데이터가 존재하지 않을 경우 해당 크기만큼 데이터를 read 할때까지 대기. \n
|
||||
///< 또는 지정된 Timeout 값 동안 read 를 하지 못하는 경우 오류 처리.
|
||||
///< 본 함수는 Socket 상에 이미 Data 가 존재하는 경우에만 사용.
|
||||
/// @param vptr [out] Read 된 데이터를 저장하기 위한 변수에 대한 포인터.
|
||||
/// @param size [in] read 하고자 하는 데이터의 크기.
|
||||
/// @param timeout [in] Timeout value (sec)
|
||||
/// @return read 된 데이터의 크기. 0: fd closed, -1: 오류, -2: Timeout
|
||||
ssize_t ReadNTimeout2( void * vptr, size_t size, int timeout = DEFAULT_DATA_RECEIVE_TIMEOUT );
|
||||
|
||||
public:
|
||||
/// @brief m_sock 으로 지정된 크기만큼 vptr 의 데이터를 전송 시도.\n
|
||||
///< Send Timeout 옵션 설정으로 Write Timeout 설정 가능. \n
|
||||
///< 지정된 횟수만큼 재전송 실패시 오류로 처리함.
|
||||
/// @param vptr [in] 전달할 데이터를 저장한 변수에 대한 포인터.
|
||||
/// @param size [in] write 하고자 하는 데이터의 크기.
|
||||
/// @return write 된 데이터의 크기. 0: fd closed, -1: 오류
|
||||
ssize_t WriteN( const void * vptr, size_t size );
|
||||
|
||||
protected:
|
||||
|
||||
/// @brief 문자열로 전달받은 정보를 검사하여 IP 접속 정보를 생성한다.
|
||||
unsigned int ConversionAddr( const char * name );
|
||||
|
||||
};
|
||||
|
||||
#endif /* __LIBRARY_BASE_SOCKET_H__ */
|
||||
@@ -0,0 +1,215 @@
|
||||
|
||||
#include "Config.h"
|
||||
|
||||
#include <iostream>
|
||||
#include <fstream>
|
||||
|
||||
#include <errno.h>
|
||||
#include <stdlib.h>
|
||||
#include <boost/algorithm/string.hpp> // use boost
|
||||
|
||||
|
||||
Config::Config()
|
||||
: m_keyDelimiter( CONFIG_DEFAULT_KEY_DELIMITER )
|
||||
, m_valueDelimiter( CONFIG_DEFAULT_VALUE_DELIMITER )
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
/// @brief destructor
|
||||
Config::~Config()
|
||||
{
|
||||
Clear();
|
||||
}
|
||||
|
||||
/// @brief 지정된 Config 파일의 모든 정보를 읽어 내부 변수에 저장처리
|
||||
/// @param path [in] Config file 의 전체 경로정보( C 배열 지원을 위해 & 사용안함)
|
||||
/// @return On success return true, otherwise return false
|
||||
bool Config::Open( const string path )
|
||||
{
|
||||
ifstream file;
|
||||
|
||||
// Config file open
|
||||
file.open( path.c_str());
|
||||
if( file.is_open() == false )
|
||||
{
|
||||
cerr << "[error] " << __FILE__<< ":" << __func__ << ": config file open failed.[" << path << "][" << strerror( errno ) << "]" << endl;
|
||||
return false;
|
||||
}
|
||||
|
||||
// 기존 데이터가 존재하면 삭제 처리.
|
||||
if( m_configData.empty() == false )
|
||||
m_configData.clear();
|
||||
|
||||
// config file parsing
|
||||
string line;
|
||||
string section;
|
||||
vector< string > configs;
|
||||
|
||||
// 루프를 돌면서 Config 파일을 line 단위로 읽어들인당....
|
||||
while( std::getline( file, line ) )
|
||||
{
|
||||
// 앞뒤 공백 제거 처리
|
||||
boost::trim( line );
|
||||
|
||||
// 공백 or 주석처리 라인 검사
|
||||
if( line.empty() == true || boost::starts_with( line, string("#") ) == true || line == "\r" )
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// Section 여부 검사
|
||||
if( boost::starts_with( line, string("[") ) == true && boost::ends_with( line, string("]") ) == true )
|
||||
{
|
||||
// [] 로 정의된 section 의 문자열 값 추출
|
||||
line.erase( line.begin() );
|
||||
line.erase( line.end() -1 );
|
||||
boost::trim( line );
|
||||
|
||||
if( section.empty() == false && section != line )
|
||||
{
|
||||
// 이전 세션과 다른 신규 세션인 경우
|
||||
// 기존까지 저장했던 데이터를 멤버 변수에 입력 처리 후 내부변수 초기화 처리.
|
||||
|
||||
m_configData.insert( make_pair( section, configs ) );
|
||||
section.clear();
|
||||
configs.clear();
|
||||
}
|
||||
|
||||
// 신규 section 정보 저장처리.
|
||||
section = line;
|
||||
line.clear();
|
||||
}
|
||||
else
|
||||
{
|
||||
// Section 정보가 아닌 경우 => 실제 설정값 .. ^^
|
||||
configs.push_back( line );
|
||||
}
|
||||
}
|
||||
|
||||
// 마지막 세션 처리된 정보가 존재하는 경우 멤버 변수에 저장 처리.
|
||||
if( section.empty() == false )
|
||||
{
|
||||
m_configData.insert( make_pair( section, configs ) );
|
||||
}
|
||||
|
||||
// 종료 처리.
|
||||
file.close();
|
||||
return true;
|
||||
}
|
||||
|
||||
/// @brief Config 멤버 변수에 저장된 데이터 삭제처리.
|
||||
/// @return void
|
||||
void Config::Clear()
|
||||
{
|
||||
m_configData.clear();
|
||||
}
|
||||
|
||||
/// @brief 해당 Section, Key 에 해당하는 value 값을 찾아 반환
|
||||
/// @param section [in] 찾고자 하는 Section 값
|
||||
/// @param key [in] 찾고자 하는 key 값
|
||||
/// @param value [out] 해당 Section, Key 에 해당하는 value 값을 저장하기 위한 변수
|
||||
/// @return On success return true, otherwise return false
|
||||
bool Config::GetConfig( const string section, const string key, string& value )
|
||||
{
|
||||
// Section 에 대한 임시 데이터 저장객체 생성
|
||||
vector< string > configs;
|
||||
|
||||
// 해당 Section 이 존재하지 않는 경우
|
||||
if( Find( section, configs ) == false )
|
||||
return false;
|
||||
|
||||
string line;
|
||||
string result;
|
||||
vector< string >::const_iterator it;
|
||||
|
||||
// 해당 Key 이 존재하는지 검사
|
||||
for( it = configs.begin(); it != configs.end(); it++)
|
||||
{
|
||||
line = *it;
|
||||
|
||||
// Line 상의 주석 제거
|
||||
string::size_type pos = line.find( '#' );
|
||||
if( pos != string::npos)
|
||||
{
|
||||
line = line.substr(0, pos);
|
||||
boost::trim( line );
|
||||
}
|
||||
|
||||
// key = value 에서 key 부분 추출
|
||||
pos = line.find( m_keyDelimiter );
|
||||
if( pos == string::npos )
|
||||
{
|
||||
continue;
|
||||
}
|
||||
else
|
||||
{
|
||||
result = line.substr(0, pos);
|
||||
boost::trim( result );
|
||||
}
|
||||
|
||||
if( key == result )
|
||||
{
|
||||
// Key 값이 동일한 경우
|
||||
value = line.substr( pos+1 );
|
||||
boost::trim( value );
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// @brief 해당 Section, Key 에 해당하는 value Array 값을 찾아 반환
|
||||
/// @param section [in] 찾고자 하는 Section 값
|
||||
/// @param key [in] 찾고자 하는 key 값
|
||||
/// @param value [out] 해당 Section, Key 에 해당하는 value 값을 저장하기 위한 배열
|
||||
/// @return On success return true, otherwise return false
|
||||
bool Config::GetConfig( const string section, const string key, vector< string >& value )
|
||||
{
|
||||
string result;
|
||||
vector< string > vec;
|
||||
|
||||
if( GetConfig( section, key, result ) == false )
|
||||
return false;
|
||||
|
||||
// 전달받은 result 값을 value delimiter 를 이용하여 parsing 처리
|
||||
boost::split( vec, result, boost::is_any_of( m_valueDelimiter ));
|
||||
if( vec.empty() == true )
|
||||
return false;
|
||||
|
||||
// 루프를 돌면서 trim 처리 후 결과값 저장처리.
|
||||
vector< string >::const_iterator it;
|
||||
for( it = vec.begin(); it != vec.end(); it++)
|
||||
{
|
||||
result = boost::trim_copy( *it );
|
||||
|
||||
if( result.empty() == false )
|
||||
value.push_back( result );
|
||||
}
|
||||
|
||||
if( value.empty() == true )
|
||||
return false;
|
||||
else
|
||||
return true;
|
||||
}
|
||||
|
||||
/// @brief Config 멤버 변수에 저장된 데이터 중 해당 Section 에 해당하는 데이터 반환.
|
||||
/// @param section [in] section 명
|
||||
/// @param configData [out] 해당 Section 에서 읽은 Cofig 정보를 저장할 string 배열
|
||||
/// @return On success return true, otherwise return false
|
||||
bool Config::Find( const string& section, vector<string>& configData )
|
||||
{
|
||||
map< string, vector< string > >::iterator it = m_configData.find( section );
|
||||
if( it != m_configData.end() )
|
||||
{
|
||||
// 해당 section 을 찾은 경우
|
||||
configData = it->second;
|
||||
return true;
|
||||
}
|
||||
|
||||
// 해당 section 을 찾지 못한 경우
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
/***************************************************************************
|
||||
Config File Parser Class
|
||||
-----------------------------------------
|
||||
begin : 2010/02/27
|
||||
copyright : (C) 2005 SolutionBox Inc.
|
||||
author : Service 1 Team
|
||||
email : svc1@solbox.com
|
||||
version : 1.0
|
||||
|
||||
CopyRight(C) 2005 SolutionBox Inc. All Rights reserved.
|
||||
Redistribution and use in source and binary forms, with or with out
|
||||
modification, are not permitted in outside of SolutionBox Inc.
|
||||
***************************************************************************/
|
||||
|
||||
#ifndef __LIBRARY_CONFIG_H__
|
||||
#define __LIBRARY_CONFIG_H__
|
||||
|
||||
#include <string>
|
||||
#include <map>
|
||||
#include <vector>
|
||||
|
||||
using namespace std;
|
||||
|
||||
|
||||
#define CONFIG_DEFAULT_KEY_DELIMITER "="
|
||||
#define CONFIG_DEFAULT_VALUE_DELIMITER ","
|
||||
|
||||
|
||||
/// @brief Config class
|
||||
/// 1. config 파일의 내용을 파싱처리하여 각 Section, Key 에 해당하는 값을 반환처리
|
||||
/// 2. config 파일은 [section] 단위로 구분된다.
|
||||
/// 3. config 파일은 key=value 로 구분가능하며 이는 Delimiter 설정을 통해 변경가능하다.
|
||||
/// 4. value 값이 다중으로 존재하는 경우 "," 값을 통해 구분가능, Delimiter 변경시 다른 값도 사용가능함.
|
||||
/// 5. config 파일상에서 "#" 로 시작하는 문자열은 라인 끝까지 주석으로 처리된다.
|
||||
/// 6. 특정 Key 값에 대한 다중 value 값 조회는 vector<string> 을 통해 수행한다.
|
||||
/// 7. 만약 다중 value 값이 존재시 string 으로 반환받을 경우 해당 Row 가 통째로 반환된다.
|
||||
/// 8. 본 객체는 Open , Clear 함수가 호출되기전까지 이전 Config 정보가 저장된다.
|
||||
class Config
|
||||
{
|
||||
private:
|
||||
/// @brief config information saved variable
|
||||
// string : section data
|
||||
// vector<string> : key=value data
|
||||
map< string, vector< string> > m_configData;
|
||||
|
||||
/// @brief Key, Value 구분자 저장 변수
|
||||
string m_keyDelimiter;
|
||||
string m_valueDelimiter;
|
||||
|
||||
public:
|
||||
/// @brief constructor
|
||||
Config();
|
||||
|
||||
/// @brief destructor
|
||||
~Config();
|
||||
|
||||
/// @brief 지정된 Config 파일의 모든 정보를 읽어 내부 변수에 저장처리
|
||||
/// @param path [in] Config file 의 전체 경로정보( C 배열 지원을 위해 & 사용안함)
|
||||
/// @return On success return true, otherwise return false
|
||||
bool Open( const string path );
|
||||
|
||||
/// @brief Config 멤버 변수에 저장된 데이터 삭제처리.
|
||||
/// @return void
|
||||
void Clear();
|
||||
|
||||
/// @brief 해당 Section, Key 에 해당하는 value 값을 찾아 반환
|
||||
/// @param section [in] 찾고자 하는 Section 값
|
||||
/// @param key [in] 찾고자 하는 key 값
|
||||
/// @param value [out] 해당 Section, Key 에 해당하는 value 값을 저장하기 위한 변수
|
||||
/// @return On success return true, otherwise return false
|
||||
bool GetConfig( const string section, const string key, string& value );
|
||||
|
||||
/// @brief 해당 Section, Key 에 해당하는 value Array 값을 찾아 반환
|
||||
/// @param section [in] 찾고자 하는 Section 값
|
||||
/// @param key [in] 찾고자 하는 key 값
|
||||
/// @param value [out] 해당 Section, Key 에 해당하는 value 값을 저장하기 위한 배열
|
||||
/// @return On success return true, otherwise return false
|
||||
bool GetConfig( const string section, const string key, vector< string >& value );
|
||||
|
||||
/// @brief Key, Value Delimiter Get 함수
|
||||
/// @param key [out] key delimiter 값
|
||||
/// @param value [out] value delimiter 값
|
||||
void GetDelimiter( string& key, string& value )
|
||||
{
|
||||
key = m_keyDelimiter;
|
||||
value = m_valueDelimiter;
|
||||
}
|
||||
|
||||
// BUG 2010-12-06 huibong
|
||||
// string& value = CONFIG_DEFAULT_VALUE_DELIMITER 값은 문법상 오류 구문임.
|
||||
// gcc 3.4.6 버전에서는 Compile 되나 gcc 4.4.5 에서는 error 로 처리되어 수정처리함.
|
||||
|
||||
/// @brief Key, Value Delimiter Set 함수
|
||||
/// @param key [out] key delimiter 값
|
||||
/// @param value [out] value delimiter 값, 지정하지 않을 경우 Default 값이 사용됨.
|
||||
void SetDelimiter( string& key, string value = CONFIG_DEFAULT_VALUE_DELIMITER )
|
||||
{
|
||||
m_keyDelimiter = key;
|
||||
m_valueDelimiter = value;
|
||||
}
|
||||
|
||||
|
||||
protected:
|
||||
/// @brief Config 멤버 변수에 저장된 데이터 중 해당 Section 에 해당하는 데이터 반환.
|
||||
/// @param section [in] section 명
|
||||
/// @param configData [out] 해당 Section 에서 읽은 Cofig 정보를 저장할 string 배열
|
||||
/// @return On success return true, otherwise return false
|
||||
bool Find( const string& section, vector<string>& configData );
|
||||
|
||||
};
|
||||
|
||||
|
||||
|
||||
#endif /* __LIBRARY_CONFIG_H__ */
|
||||
@@ -0,0 +1,487 @@
|
||||
/***************************************************************************
|
||||
Logger.cpp
|
||||
-----------------------------------------
|
||||
begin : 2011/10/26
|
||||
copyright : (C) 2005 SolutionBox Inc.
|
||||
author : Service 1 Team
|
||||
email : svc1@solbox.com
|
||||
version : 1.0
|
||||
|
||||
CopyRight(C) 2005 SolutionBox Inc. All Rights reserved.
|
||||
Redistribution and use in source and binary forms, with or with out
|
||||
modification, are not permitted in outside of SolutionBox Inc.
|
||||
***************************************************************************/
|
||||
#include "Logger.h"
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdarg.h>
|
||||
#include <sys/types.h>
|
||||
#include <sys/stat.h>
|
||||
#include <iostream>
|
||||
#include <errno.h>
|
||||
#include <string.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
#define MAX_BUFFER_SIZE 2048 // 임시 버퍼 최대 크기
|
||||
#define DEFAULT_LOG_LEVEL LINF
|
||||
|
||||
using namespace std;
|
||||
|
||||
CLogger* CLogger::m_pInstance = NULL;
|
||||
bool CLogger::m_bIsInitialized = false;
|
||||
pthread_mutex_t CLogger::m_mutex = PTHREAD_MUTEX_INITIALIZER;
|
||||
|
||||
|
||||
CLogger::CLogger( string programName, string logDir, int logLevel )
|
||||
{
|
||||
m_szProgramName = programName;
|
||||
m_szLogDir = logDir;
|
||||
|
||||
if( IsValidLogLevel( logLevel ) == true )
|
||||
{
|
||||
m_nLogLevel = logLevel;
|
||||
}
|
||||
else
|
||||
{
|
||||
m_nLogLevel = DEFAULT_LOG_LEVEL;
|
||||
}
|
||||
|
||||
MakeLogLevelString();
|
||||
}
|
||||
|
||||
void CLogger::MakeLogLevelString()
|
||||
{
|
||||
m_vectorLogLevelString.push_back( "EMR" );
|
||||
m_vectorLogLevelString.push_back( "ALT" );
|
||||
m_vectorLogLevelString.push_back( "CRT" );
|
||||
m_vectorLogLevelString.push_back( "ERR" );
|
||||
m_vectorLogLevelString.push_back( "WAR" );
|
||||
m_vectorLogLevelString.push_back( "NOT" );
|
||||
m_vectorLogLevelString.push_back( "INF" );
|
||||
m_vectorLogLevelString.push_back( "DBG" );
|
||||
m_vectorLogLevelString.push_back( "DEV" );
|
||||
m_vectorLogLevelString.push_back( "DEV1" );
|
||||
m_vectorLogLevelString.push_back( "DEV2" );
|
||||
}
|
||||
|
||||
CLogger::~CLogger()
|
||||
{
|
||||
m_vectorLogLevelString.clear();
|
||||
}
|
||||
|
||||
bool CLogger::Init( string programName, string logDir, int logLevel )
|
||||
{
|
||||
if( m_bIsInitialized == true )
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
pthread_mutex_lock( &m_mutex );
|
||||
|
||||
// 변수 유효성 검사.
|
||||
if( programName.empty() == true || logDir.empty() == true )
|
||||
{
|
||||
pthread_mutex_unlock( &m_mutex );
|
||||
return false;
|
||||
}
|
||||
|
||||
if( IsValidLogLevel( logLevel ) == false )
|
||||
{
|
||||
pthread_mutex_unlock( &m_mutex );
|
||||
return false;
|
||||
}
|
||||
|
||||
if( MakeLogDir( programName, logDir ) == false )
|
||||
{
|
||||
pthread_mutex_unlock( &m_mutex );
|
||||
return false;
|
||||
}
|
||||
|
||||
if( CLogger::m_pInstance != NULL )
|
||||
{
|
||||
delete CLogger::m_pInstance;
|
||||
CLogger::m_pInstance = NULL;
|
||||
}
|
||||
|
||||
CLogger::m_pInstance = new CLogger( programName, logDir, logLevel );
|
||||
m_bIsInitialized = true;
|
||||
|
||||
pthread_mutex_unlock( &m_mutex );
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CLogger::IsValidLogLevel( int logLevel )
|
||||
{
|
||||
return ( ( logLevel < 0 || logLevel > MAX_LOG_LEVEL ) ? false : true );
|
||||
}
|
||||
|
||||
bool CLogger::SetLogLevel( int logLevel )
|
||||
{
|
||||
if( IsValidLogLevel( logLevel ) == false )
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
m_nLogLevel = logLevel;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CLogger::MakeLogDir( string programName, string logDir )
|
||||
{
|
||||
string path = logDir + "/" + programName;
|
||||
|
||||
struct stat dirStat;
|
||||
|
||||
// 해당 이름을 가진 파일 또는 디렉토리가 존재하고
|
||||
if( lstat( path.c_str(), &dirStat ) == 0 )
|
||||
{
|
||||
// 해당 이름이 디렉토리인 경우
|
||||
if( S_ISDIR( dirStat.st_mode ) == true )
|
||||
{
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
cerr << "exist file with the same name as log path(" << path << ")." << endl;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// 디렉토리 가 존재하지 않는 경우 디렉토리 생성 시도
|
||||
string cmd = "mkdir -p " + path;
|
||||
system( cmd.c_str() );
|
||||
|
||||
if( IsDirectory( path ) == false )
|
||||
{
|
||||
cerr << "can't make log directory. path=" << path << "." << endl;
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CLogger::IsDirectory( string path )
|
||||
{
|
||||
struct stat dirStat;
|
||||
|
||||
if( lstat ( path.c_str(), &dirStat ) != 0 )
|
||||
{
|
||||
cerr << "Log path not valid. Check path [" << path << "][" << errno << "][" << strerror(errno) << "]" << endl;
|
||||
return false;
|
||||
}
|
||||
|
||||
// 해당 정보가 Directory 가 아닌 경우
|
||||
if( S_ISDIR( dirStat.st_mode ) == false )
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void CLogger::Exit()
|
||||
{
|
||||
if( m_bIsInitialized == false )
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
pthread_mutex_lock( &m_mutex );
|
||||
|
||||
if( CLogger::m_pInstance != NULL )
|
||||
{
|
||||
delete CLogger::m_pInstance;
|
||||
CLogger::m_pInstance = NULL;
|
||||
m_bIsInitialized = false;
|
||||
}
|
||||
|
||||
pthread_mutex_unlock( &m_mutex );
|
||||
}
|
||||
|
||||
CLogger* CLogger::GetInstance()
|
||||
{
|
||||
return CLogger::m_pInstance;
|
||||
}
|
||||
|
||||
string CLogger::GetLogFilename( struct tm &timeNow )
|
||||
{
|
||||
char timeStr[256];
|
||||
snprintf( timeStr, (size_t)256, "%04d%02d%02d.log", timeNow.tm_year+1900, timeNow.tm_mon+1, timeNow.tm_mday);
|
||||
|
||||
// Make File Name
|
||||
string filename = m_szLogDir + "/" + m_szProgramName + "/" + m_szProgramName + "_" + string( timeStr );
|
||||
|
||||
return filename;
|
||||
}
|
||||
|
||||
bool CLogger::Write( int logLevel, const char * fmt, ...)
|
||||
{
|
||||
// 가변 인자 처리
|
||||
va_list args;
|
||||
char buffer[MAX_BUFFER_SIZE];
|
||||
va_start( args, fmt );
|
||||
if( vsnprintf( buffer, MAX_BUFFER_SIZE, fmt, args) < 0 )
|
||||
{
|
||||
va_end( args );
|
||||
return false;
|
||||
}
|
||||
va_end(args);
|
||||
|
||||
return Write( logLevel, PREFIX_DATE, NULL, 0, buffer );
|
||||
}
|
||||
|
||||
bool CLogger::WriteNoPrefix( int logLevel, const char * fmt, ...)
|
||||
{
|
||||
// 가변 인자 처리
|
||||
va_list args;
|
||||
char buffer[MAX_BUFFER_SIZE];
|
||||
va_start( args, fmt );
|
||||
if( vsnprintf( buffer, MAX_BUFFER_SIZE, fmt, args) < 0 )
|
||||
{
|
||||
va_end( args );
|
||||
return false;
|
||||
}
|
||||
va_end(args);
|
||||
|
||||
return Write( logLevel, PREFIX_NONE, NULL, 0, buffer );
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
// CHG 2012-08-16 huibong
|
||||
// 가변인자를 사용하는 Write 함수 다중 정의로 인해...
|
||||
// Complier 에서 인수 갯수 및 Type 이 동일할 경우 다른 함수를 가르키는 현상이 발견됨.
|
||||
// 이를 해결하기 위해 Write 함수에 대한 다중 정의를 제거토록 함수명을 명확하게 변경처리함.
|
||||
// 함수명 : Write -> WriteWithFunc 으로 변경 처리
|
||||
bool CLogger::WriteWithFunc( int logLevel, const char* filename, const char* funcname, int lineNum, const char * fmt, ...)
|
||||
{
|
||||
if( filename == NULL || funcname == NULL || lineNum < 0 || fmt == NULL )
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// 가변 인자 처리
|
||||
va_list args;
|
||||
char buffer[MAX_BUFFER_SIZE];
|
||||
va_start( args, fmt );
|
||||
if( vsnprintf( buffer, MAX_BUFFER_SIZE, fmt, args) < 0 )
|
||||
{
|
||||
va_end( args );
|
||||
return false;
|
||||
}
|
||||
va_end(args);
|
||||
|
||||
|
||||
char className[255];
|
||||
string funcPrefix = GetClassName( className, filename );
|
||||
funcPrefix += "::" + string( funcname ) + "()";
|
||||
|
||||
return Write( logLevel, PREFIX_FUNCTION, funcPrefix.c_str(), lineNum, buffer );
|
||||
}
|
||||
|
||||
const char* CLogger::GetClassName( char* className, const char* filename )
|
||||
{
|
||||
if( className == NULL )
|
||||
{
|
||||
cout << "[ERROR] The input argument 'className' is NULL." << endl;
|
||||
return NULL;
|
||||
}
|
||||
|
||||
if( filename == NULL )
|
||||
{
|
||||
cout << "[ERROR] The input argument 'filename' is NULL." << endl;
|
||||
strcpy( className, "NULL" );
|
||||
return className;
|
||||
}
|
||||
|
||||
int filenameSize = strlen( filename );
|
||||
memcpy( className, filename, filenameSize );
|
||||
|
||||
// find end position
|
||||
char endCharacter = '.';
|
||||
int endPos = filenameSize - 1;
|
||||
for( ; endPos > 0; --endPos )
|
||||
{
|
||||
if( className[endPos] == endCharacter )
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if( endPos == 0 )
|
||||
{
|
||||
cout << "[ERROR] endPos=0" << endl;
|
||||
strcpy( className, "NULL" );
|
||||
return className;
|
||||
}
|
||||
|
||||
className[endPos] = '\0';
|
||||
|
||||
// find start position
|
||||
char startCharacter = '/';
|
||||
int startPos = endPos - 1;
|
||||
for( ; startPos > 0; --startPos )
|
||||
{
|
||||
if( className[startPos] == startCharacter )
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if( startPos != 0 )
|
||||
{
|
||||
startPos += 1;
|
||||
}
|
||||
|
||||
return (className + startPos );
|
||||
}
|
||||
|
||||
bool CLogger::Write( int logLevel, int logPrefix, const char* functionName, int lineNum, const char* log )
|
||||
{
|
||||
/// 유효한 로그 레벨이 아니면 로깅하지 않음.
|
||||
if( IsValidLogLevel( logLevel ) == false )
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// Log Level 검사 : 지정된 Level 이상인 경우 로깅하지 않음.
|
||||
if( logLevel > m_nLogLevel )
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if( log == NULL )
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// Get Current Data & Time
|
||||
time_t now = time( NULL );
|
||||
struct tm timeNow;
|
||||
localtime_r( &now, &timeNow );
|
||||
|
||||
string filename = GetLogFilename( timeNow );
|
||||
|
||||
// Log file open
|
||||
FILE* pFile = NULL;
|
||||
pFile = fopen( filename.c_str(), "a+" );
|
||||
|
||||
if( pFile == NULL )
|
||||
{
|
||||
cerr << "Log file open fail.[" << filename.c_str() << "][" << errno << "][" << strerror(errno) << "]" << endl;
|
||||
return false;
|
||||
}
|
||||
|
||||
// 시간 정보처리
|
||||
char timeStr[256];
|
||||
snprintf( timeStr, (size_t)256, "[%02d:%02d:%02d]"
|
||||
, timeNow.tm_hour, timeNow.tm_min, timeNow.tm_sec );
|
||||
|
||||
// Log Level 문자열 검색
|
||||
string szLevel = m_vectorLogLevelString[ logLevel ];
|
||||
|
||||
switch( logPrefix )
|
||||
{
|
||||
case PREFIX_DATE:
|
||||
/// 형식 예: [15:47:41] [DBG] sample log message.
|
||||
fprintf( pFile, "%s [%-4s] %s\n", timeStr, szLevel.c_str(), log );
|
||||
break;
|
||||
|
||||
case PREFIX_FUNCTION:
|
||||
if( functionName == NULL )
|
||||
{
|
||||
fclose( pFile );
|
||||
return false;
|
||||
}
|
||||
/// 형식 예: [15:47:41] [DBG] sample log message. [SomeClass::SomeFunction():12]
|
||||
fprintf( pFile, "%s [%-4s] %s [%s:%d]\n", timeStr, szLevel.c_str(), log, functionName, lineNum );
|
||||
break;
|
||||
|
||||
case PREFIX_NONE:
|
||||
/// 형식 예: sample log message.
|
||||
fprintf( pFile, "%s\n", log );
|
||||
break;
|
||||
}
|
||||
// Write to log file
|
||||
fflush( pFile );
|
||||
|
||||
// 종료 처리.
|
||||
fclose( pFile );
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CLogger::WriteHex( int logLevel, const unsigned char* data, const int size )
|
||||
{
|
||||
/// 유효한 로그 레벨이 아니면 로깅하지 않음.
|
||||
if( IsValidLogLevel( logLevel ) == false )
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// Log Level 검사 : 지정된 Level 이상인 경우 로깅하지 않음.
|
||||
if( logLevel > m_nLogLevel )
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if( data == NULL )
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if( size <= 0 )
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// Get Current Data & Time
|
||||
time_t now = time( NULL );
|
||||
struct tm timeNow;
|
||||
localtime_r( &now, &timeNow );
|
||||
|
||||
string filename = GetLogFilename( timeNow );
|
||||
|
||||
// Log file open
|
||||
FILE* pFile = NULL;
|
||||
pFile = fopen( filename.c_str(), "a+" );
|
||||
|
||||
if( pFile == NULL )
|
||||
{
|
||||
cerr << "Log file open fail.[" << filename.c_str() << "][" << errno << "][" << strerror(errno) << "]" << endl;
|
||||
return false;
|
||||
}
|
||||
|
||||
for( int i = 0; i < size; ++i )
|
||||
{
|
||||
fprintf( pFile, "%02X", data[i] );
|
||||
|
||||
if( i == 0 )
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if( ( (i+1) % 8 ) == 0 )
|
||||
{
|
||||
fprintf( pFile, " " );
|
||||
}
|
||||
|
||||
if( ( (i+1) % 16 ) == 0 )
|
||||
{
|
||||
fprintf( pFile, " " );
|
||||
}
|
||||
|
||||
if( ( (i+1) % 32 ) == 0 )
|
||||
{
|
||||
fprintf( pFile, "\n" );
|
||||
}
|
||||
}
|
||||
fprintf( pFile, "\n" );
|
||||
fflush( pFile );
|
||||
|
||||
// 종료 처리.
|
||||
fclose( pFile );
|
||||
|
||||
return false;
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
/***************************************************************************
|
||||
Logger.h
|
||||
-----------------------------------------
|
||||
begin : 2011/10/26
|
||||
copyright : (C) 2005 SolutionBox Inc.
|
||||
author : Service 1 Team
|
||||
email : svc1@solbox.com
|
||||
version : 3.2.0.805
|
||||
|
||||
CopyRight(C) 2005 SolutionBox Inc. All Rights reserved.
|
||||
Redistribution and use in source and binary forms, with or with out
|
||||
modification, are not permitted in outside of SolutionBox Inc.
|
||||
***************************************************************************/
|
||||
#ifndef __LOGGER_H__
|
||||
#define __LOGGER_H__
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <pthread.h>
|
||||
|
||||
///@brief 로그 레벨 정의
|
||||
#define LEMR 0 /* system is or will be unusable if situation is not resolved */
|
||||
#define LALT 1 /* immediate action required */
|
||||
#define LCRT 2 /* critical situations */
|
||||
#define LERR 3 /* error conditions */
|
||||
#define LWAR 4 /* recoverable errors */
|
||||
#define LNOT 5 /* unusual situation that merits investigation */
|
||||
#define LINF 6 /* information messages */
|
||||
#define LDBG 7 /* verbose data for debugging */
|
||||
#define LDEV 8 /* verbose data for developer */
|
||||
#define LDEV1 9 /* start or end the function of application level */
|
||||
#define LDEV2 10 /* start or end the function of application level */
|
||||
|
||||
#define MAX_LOG_LEVEL LDEV2
|
||||
|
||||
|
||||
///@brief Log 정보를 파일로 저장하기 위한 Class.
|
||||
///1. 가변 format 으로 전달된 로그 관련 정보를 Log Level 에 따라 로그 파일에 아래의 4가지 형식으로 저장한다.
|
||||
///
|
||||
/// 1.1 Prefix로 [hh:mm:ss]와 [ClassName::FunctionName]이 추가된 로그
|
||||
/// LOG( level, format, ... ) 매크로 사용.
|
||||
/// 예) [17:43:40] [DBG] log level debug [LoggerTestTestLogger]
|
||||
///
|
||||
/// 1.2 Prefix로 [hh:mm:ss]이 추가된 로그
|
||||
/// _LOG( level, format, ... ) 매크로 사용
|
||||
/// 예) [17:43:40] [EMR] log level emergency
|
||||
///
|
||||
/// 1.3 Prefix가 없는 로그
|
||||
/// _LOG_( level, format, ... ) 매크로 사용
|
||||
/// 예) log level emergency
|
||||
///
|
||||
/// 1.4 Hex 로그.
|
||||
/// LOG_HEX( level, data, size ) 매크로 사용
|
||||
/// 예) 00010203 04050607 08090A0B 0C0D0E0F
|
||||
///
|
||||
///2. Logger 객체 초기화시 전달된 Log Level 정보보다 전달받은 Log Level 정보가 큰 경우 해당 로그는 파일로 저장되지 않는다.
|
||||
///
|
||||
///3. 로그 파일은 매 일단위로 저장파일이 변경된다.
|
||||
///
|
||||
///4. 로그 저장을 위한 program 경로가 존재하지 않는 경우 자동 생성 처리된다.
|
||||
///
|
||||
///5. 로그 저장방식은 매 저장로그마다 open-close 로 처리된다.
|
||||
///
|
||||
///6. 파일로 기록시 Log Level 에 대한 정보도 함께 기록된다.
|
||||
///
|
||||
///7. 싱글톤으로 작성되었고, CLogger::Init(...)시에 쓰레드 안정성을 제공한다.
|
||||
///
|
||||
///8. 동적으로 로그 레벨을 변경할 수 있는 인터페이스를 제공한다.
|
||||
///
|
||||
class CLogger
|
||||
{
|
||||
// Attributes
|
||||
private:
|
||||
///@brief 싱글톤 객체 인트턴스.
|
||||
static CLogger* m_pInstance;
|
||||
|
||||
///@brief 싱글톤 객체 초기화 여부.
|
||||
static bool m_bIsInitialized;
|
||||
|
||||
///@brief 싱글톤 객체 초기화시 스레드 안정성을 위한 뮤텍스.
|
||||
static pthread_mutex_t m_mutex;
|
||||
|
||||
///@brief 프로그램 이름. 로그 파일 경로를 만들 때 사용.
|
||||
std::string m_szProgramName;
|
||||
|
||||
///@brief 공통 로그 디렉토리 이름. 로그 파일 경로를 만들 때 사용.
|
||||
std::string m_szLogDir;
|
||||
|
||||
///@brief 로그 레벨.
|
||||
int m_nLogLevel;
|
||||
|
||||
///@brief 로그 레벨에 대응되는 문자열 정보를 저장.
|
||||
std::vector<std::string> m_vectorLogLevelString;
|
||||
|
||||
protected:
|
||||
|
||||
public:
|
||||
///@brief 로그 형식을 지정.
|
||||
typedef enum
|
||||
{
|
||||
PREFIX_NONE = 0, /// 클래스 설명의 1.3에 해당
|
||||
PREFIX_DATE, /// 클래스 설명의 1.2에 해당
|
||||
PREFIX_FUNCTION, /// 클래스 설명의 1.1에 해당
|
||||
} LOG_PREFIX;
|
||||
|
||||
// Operations
|
||||
private:
|
||||
///@brief 생성자.
|
||||
/// 프로그램 이름, 공통 로그 디렉토리, 로그 레벨을 저장하고
|
||||
/// 로그 레벨에 대응되는 문자열 정보를 만든다.
|
||||
///@param programName [in] 프로그램 이름
|
||||
///@param logDir [in] 공통 로그 디렉토리 경로
|
||||
///@param logLevel [in] 로그 레벨
|
||||
CLogger( std::string programName, std::string logDir, int logLevel );
|
||||
|
||||
///@brief 소멸자.
|
||||
/// 로그 레벨에 대응되는 문자열 정보를 저장하고 있는
|
||||
/// 벡터 m_vectorLogLevelString을 clear 시킴.
|
||||
virtual ~CLogger();
|
||||
|
||||
///@brief 로그 레벨에 대응되는 문자열을 만든다.
|
||||
///@param none.
|
||||
///@return none.
|
||||
void MakeLogLevelString();
|
||||
|
||||
///@brief 로그 파일이 위치할 실제 로그 디렉토리를 생성한다.
|
||||
/// 생성할 디렉토리 경로는 'logDir/programName'이 된다.
|
||||
///@param programName [in] 프로그램 이름
|
||||
///@param logDir [in] 공통 로그 디렉토리 경로
|
||||
///@return 디렉토리가 이미 존재하거나 생성 성공하면 true,
|
||||
/// 해당 경로가 존재하지만 디렉토리가 아니거나, 디렉토리 생성 실패하면 false 반환.
|
||||
static bool MakeLogDir( std::string programName, std::string logDir );
|
||||
|
||||
///@brief 해당 경로가 디렉토리 인지 아닌지 판단.
|
||||
///@param path [in] 디렉토리 인지 아닌지 판단할 경로.
|
||||
///@return 해당 경로가 디렉토이면 true,
|
||||
/// 경로가 존재하지 않거나 디렉토리가 아니면 false 반환.
|
||||
static bool IsDirectory( std::string path );
|
||||
|
||||
///@brief 로그 레벨이 올바른지 판별.
|
||||
///@param logLevel [in]
|
||||
///@return 올바른 로그 레벨이면 true, 그렇지 않으면 false 반환.
|
||||
static bool IsValidLogLevel( int logLevel );
|
||||
|
||||
///@brief 시간 정보를 입력 받아 로그 파일 이름을 만든다.
|
||||
/// 로그 파일 이름 형식 : 프로그램명_YYYYMMDD.log
|
||||
///param timeNow [in] 현재 시간 정보.
|
||||
///return 로그 파일 이름.
|
||||
std::string GetLogFilename( struct tm &timeNow );
|
||||
|
||||
///@brief 로그를 남기는는 클래스가 정의된 파일의 이름에서 클래스명을 추출한다.
|
||||
/// 쓰레드 안정성을 보장한다.
|
||||
///@param className [out] 파일 이름에서 추출된 클래스명
|
||||
///@param filename [in] 파일 이름.
|
||||
///@return 클래스명 추출이 성공하면 클래스명 문자열의 포인터, 추출 실패하면 NULL.
|
||||
const char* GetClassName( char* className, const char* filename );
|
||||
|
||||
///@brief 인자 logPrefix에 따라 적절한 형식으로 로그 파일에 로그를 저장한다.
|
||||
/// 인자 logLevel이 설정된 로그 레벨보다 높으면 로그를 출력하지 않는다.
|
||||
///@param logLevel [in] 로그 레벨
|
||||
///@param logPrefix [in] 로그 프리픽스 종류.
|
||||
///@functionName [in] ClassName::FunctionNmae() 형식의 문자열.
|
||||
///@lineNum [in] 라인 번호.
|
||||
///@log [in] 출력하고자 하는 로그 내용.
|
||||
bool Write( int logLevel, int logPrefix, const char* functionName, int lineNum, const char* log );
|
||||
|
||||
protected:
|
||||
|
||||
public:
|
||||
///@brief 싱글톤 객체 m_pInstance를 생성하고 인자 정보로 로그 디렉토리를 만든다.
|
||||
///@param programName [in] 프로그램 이름
|
||||
///@param logDir [in] 공통 로그 디렉토리 경로
|
||||
///@param logLevel [in] 로그 레벨
|
||||
///@return 로그 디렉토리를 만들고 싱글톤 객체를 생성했으면 true,
|
||||
/// 로그 디렉토리를 만들지 못 했거나 인자 값이 올바르지 않으면 false 반환.
|
||||
static bool Init( std::string programName, std::string logDir, int logLevel );
|
||||
|
||||
///@brief 싱글톤 객체 m_pInstance를 delete 한다.
|
||||
///@param none.
|
||||
///@return none.
|
||||
static void Exit();
|
||||
|
||||
///@brief 싱글톤 객체 m_pInstance를 반환한다.
|
||||
///@param none.
|
||||
///@return CLogger 객체의 인스턴스.
|
||||
static CLogger* GetInstance();
|
||||
|
||||
///@brief Prefix로 [hh:mm:ss]이 추가된 형식으로 로그 저장.
|
||||
///@param logLevel [in] 로그 레벨
|
||||
///@param fmt [in] 로그 내용 포맷.
|
||||
///@param __VAR_ARGS__ [in] 가변 인자.
|
||||
///@return 로그 파일에 로그를 저장했으면 true, 그렇지 않으면 false 반환
|
||||
bool Write( int logLevel, const char * fmt, ...)
|
||||
__attribute__((format(printf, 3, 4)));
|
||||
|
||||
///@brief Prefix가 없는 로그 저장.
|
||||
///@param logLevel [in] 로그 레벨
|
||||
///@param fmt [in] 로그 내용 포맷.
|
||||
///@param __VAR_ARGS__ [in] 가변 인자.
|
||||
///@return 로그 파일에 로그를 저장했으면 true, 그렇지 않으면 false 반환
|
||||
bool WriteNoPrefix( int logLevel, const char * fmt, ...)
|
||||
__attribute__((format(printf, 3, 4)));
|
||||
|
||||
|
||||
// CHG 2012-08-16 huibong
|
||||
// 가변인자를 사용하는 Write 함수 다중 정의로 인해...
|
||||
// Complier 에서 인수 갯수 및 Type 이 동일할 경우 다른 함수를 가르키는 현상이 발견됨.
|
||||
// 이를 해결하기 위해 Write 함수에 대한 다중 정의를 제거토록 함수명을 명확하게 변경처리함.
|
||||
|
||||
///@brief Prefix로 [hh:mm:ss]와 [ClassName::FunctionName:line]이 추가된 형식으로 로그 저장.
|
||||
///@param logLevel [in] 로그 레벨
|
||||
///@param filename [in] 파일 이름
|
||||
///@param funcname [in] 함수 이름
|
||||
///@param lineNum [in] 라인 번호
|
||||
///@param fmt [in] 로그 내용 포맷.
|
||||
///@param __VAR_ARGS__ [in] 가변 인자.
|
||||
///@return 로그 파일에 로그를 저장했으면 true, 그렇지 않으면 false 반환
|
||||
bool WriteWithFunc( int logLevel, const char* filename, const char* funcname, int lineNum, const char * fmt, ...)
|
||||
__attribute__((format(printf, 6, 7)));
|
||||
|
||||
///@brief 로그를 hex 형식으로 저장.
|
||||
///@param logLevel [in] 로그 레벨
|
||||
///@param data [in] hex 형식으로 출력할 데이터.
|
||||
///@pram size [in] data의 크기.
|
||||
///@return 로그 파일에 로그를 저장했으면 true, 그렇지 않으면 false 반환
|
||||
bool WriteHex( int logLevel, const unsigned char* data, const int size );
|
||||
|
||||
///@brief 로그을 설정한다. 인자 logLevel이 적절한 값이면 새로운 값으로 변경하고
|
||||
/// 적절한 값이 아니면 로그 레벨을 변경하지 않는다.
|
||||
///@param logLevel [in] 설정할 로그 레벨
|
||||
///@return none.
|
||||
bool SetLogLevel( int logLevel );
|
||||
|
||||
inline int GetLogLevel() { return m_nLogLevel; };
|
||||
inline std::string GetLogDir() { return m_szLogDir + "/" + m_szProgramName; };
|
||||
};
|
||||
|
||||
#define LOG( level, format, ... ) \
|
||||
if( CLogger::GetInstance() != NULL ) \
|
||||
{ \
|
||||
CLogger::GetInstance()->WriteWithFunc( level, __FILE__, __FUNCTION__, __LINE__, format, ##__VA_ARGS__ ); \
|
||||
}
|
||||
|
||||
|
||||
#define _LOG( level, format, ... ) \
|
||||
if( CLogger::GetInstance() != NULL ) \
|
||||
{ \
|
||||
CLogger::GetInstance()->Write( level, format, ##__VA_ARGS__ ); \
|
||||
}
|
||||
|
||||
|
||||
#define _LOG_( level, format, ... ) \
|
||||
if( CLogger::GetInstance() != NULL ) \
|
||||
{ \
|
||||
CLogger::GetInstance()->WriteNoPrefix( level, format, ##__VA_ARGS__ ); \
|
||||
}
|
||||
|
||||
|
||||
#define _LOG_HEX_( level, data, size ) \
|
||||
if( CLogger::GetInstance() != NULL ) \
|
||||
{ \
|
||||
CLogger::GetInstance()->WriteHex( level, (const unsigned char*)data, size ); \
|
||||
}
|
||||
|
||||
|
||||
|
||||
#define FUNC_BEGIN() LOG( LDEV1, "begin" )
|
||||
#define FUNC_END() LOG( LDEV1, "end" )
|
||||
|
||||
#define FRM_BEGIN() LOG( LDEV2, "begin" )
|
||||
#define FRM_END() LOG( LDEV2, "end" )
|
||||
|
||||
#endif // __LOGGER_H__
|
||||
@@ -0,0 +1,68 @@
|
||||
#****************************************************************************
|
||||
# Makefile for INTERACTIVE Common Libaray
|
||||
# -----------------------------------------
|
||||
#
|
||||
# begin : 2012/08/08
|
||||
# copyright : (C) 2005 SolutionBox Inc.
|
||||
# author : Service 1 Team
|
||||
# email : svc1@solbox.com
|
||||
# version : 1.0
|
||||
#
|
||||
# CopyRight(C) 2005 SolutionBox Inc. All Rights reserved.
|
||||
# Redistribution and use in source and binary forms, with or with out
|
||||
# modification, are not permitted in outside of SolutionBox Inc.
|
||||
#*****************************************************************************
|
||||
|
||||
# Library info
|
||||
|
||||
LIB_NAME = InterCommon
|
||||
|
||||
LIB = lib$(LIB_NAME).a
|
||||
|
||||
OBJS = Config.o Logger.o BaseSocket.o ProcessRename.o
|
||||
|
||||
# Compiler info
|
||||
CC = /usr/bin/g++
|
||||
AR = /usr/bin/ar
|
||||
|
||||
DIR_INCLUDE = -I/usr/local/include
|
||||
ifeq ($(DEBUG), yes)
|
||||
CFLAGS = -Wall -O0 -g -Wreturn-type -Wunused -Wuninitialized\
|
||||
-Wparentheses -Wshadow -Wpointer-arith -Woverloaded-virtual\
|
||||
-D_REENTRANT -D_THREAD_SAFE -D_REENTRANT -D_PTHREADS
|
||||
LFLAGS =
|
||||
DFLAGS =
|
||||
else
|
||||
CFLAGS = -Wall -O3 -g -Wreturn-type -Wunused -Wuninitialized\
|
||||
-Wparentheses -Wshadow -Wpointer-arith -Woverloaded-virtual\
|
||||
-D_REENTRANT -D_THREAD_SAFE -D_REENTRANT -D_PTHREADS
|
||||
LFLAGS =
|
||||
DFLAGS =
|
||||
endif
|
||||
############################
|
||||
|
||||
all:$(LIB)
|
||||
sync
|
||||
|
||||
%.o: %.cpp
|
||||
$(CC) $(CFLAGS) -o $@ -c $^ $(DFLAGS) $(DIR_INCLUDE)
|
||||
|
||||
%.o: %.c
|
||||
$(CC) $(CFLAGS) -o $@ -c $^ $(DFLAGS) $(DIR_INCLUDE)
|
||||
|
||||
|
||||
$(LIB): $(OBJS)
|
||||
$(AR) crsv $@ $^
|
||||
|
||||
|
||||
clean:
|
||||
-rm -f *.o core *.out *.log
|
||||
-rm -f $(LIB)
|
||||
sync
|
||||
|
||||
|
||||
install :
|
||||
sync
|
||||
|
||||
|
||||
# End of Makefile
|
||||
@@ -0,0 +1,185 @@
|
||||
#include "ProcessRename.h"
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
|
||||
typedef size_t Size;
|
||||
#define LONG_ALIGN_MASK (sizeof(long) - 1)
|
||||
#define MEMSET_LOOP_LIMIT 1024
|
||||
#define MemSet(start, val, len) \
|
||||
do \
|
||||
{ \
|
||||
/* must be void* because we don't know if it is integer aligned yet */ \
|
||||
void *_vstart = (void *) (start); \
|
||||
int _val = (val); \
|
||||
Size _len = (len); \
|
||||
\
|
||||
if ((((long) _vstart) & LONG_ALIGN_MASK) == 0 && \
|
||||
(_len & LONG_ALIGN_MASK) == 0 && \
|
||||
_val == 0 && \
|
||||
_len <= MEMSET_LOOP_LIMIT && \
|
||||
/* \
|
||||
* If MEMSET_LOOP_LIMIT == 0, optimizer should find \
|
||||
* the whole "if" false at compile time. \
|
||||
*/ \
|
||||
MEMSET_LOOP_LIMIT != 0) \
|
||||
{ \
|
||||
long *_start = (long *) _vstart; \
|
||||
long *_stop = (long *) ((char *) _start + _len); \
|
||||
while (_start < _stop) \
|
||||
*_start++ = 0; \
|
||||
} \
|
||||
else \
|
||||
memset(_vstart, _val, _len); \
|
||||
} while (0)
|
||||
|
||||
#define PS_PADDING '\0'
|
||||
|
||||
extern char **environ;
|
||||
bool update_process_title = true;
|
||||
|
||||
static char *ps_buffer; /* will point to argv area */
|
||||
static size_t ps_buffer_size; /* space determined at run time */
|
||||
static size_t last_status_len; /* use to minimize length of clobber */
|
||||
static size_t ps_buffer_cur_len; /* nominal strlen(ps_buffer) */
|
||||
static size_t ps_buffer_fixed_size; /* size of the constant prefix */
|
||||
|
||||
static int save_argc;
|
||||
static char **save_argv;
|
||||
|
||||
size_t strlcpy(char *dst, const char *src, size_t siz)
|
||||
{
|
||||
char *d = dst;
|
||||
const char *s = src;
|
||||
size_t n = siz;
|
||||
|
||||
/* Copy as many bytes as will fit */
|
||||
if (n != 0)
|
||||
{
|
||||
while (--n != 0)
|
||||
{
|
||||
if ((*d++ = *s++) == '\0')
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/* Not enough room in dst, add NUL and traverse rest of src */
|
||||
if (n == 0)
|
||||
{
|
||||
if (siz != 0)
|
||||
*d = '\0'; /* NUL-terminate dst */
|
||||
while (*s++)
|
||||
;
|
||||
}
|
||||
|
||||
return (s - src - 1); /* count does not include NUL */
|
||||
}
|
||||
|
||||
|
||||
void set_ps_display(const char *activity, bool force)
|
||||
{
|
||||
/* update_process_title=off disables updates, unless force = true */
|
||||
if (!force && !update_process_title)
|
||||
return;
|
||||
|
||||
/* no ps display for stand-alone backend */
|
||||
//if (!IsUnderPostmaster)
|
||||
// return;
|
||||
|
||||
/* If ps_buffer is a pointer, it might still be null */
|
||||
if (!ps_buffer)
|
||||
return;
|
||||
/* Update ps_buffer to contain both fixed part and activity */
|
||||
strlcpy(ps_buffer + ps_buffer_fixed_size, activity,
|
||||
ps_buffer_size - ps_buffer_fixed_size);
|
||||
ps_buffer_cur_len = strlen(ps_buffer);
|
||||
|
||||
/* pad unused memory; need only clobber remainder of old status string */
|
||||
if (last_status_len > ps_buffer_cur_len)
|
||||
MemSet(ps_buffer + ps_buffer_cur_len, PS_PADDING,
|
||||
last_status_len - ps_buffer_cur_len);
|
||||
last_status_len = ps_buffer_cur_len;
|
||||
|
||||
}
|
||||
|
||||
|
||||
char ** save_ps_display_args(int argc, char **argv)
|
||||
{
|
||||
save_argc = argc;
|
||||
save_argv = argv;
|
||||
|
||||
/*
|
||||
* If we're going to overwrite the argv area, count the available space.
|
||||
* Also move the environment to make additional room.
|
||||
*/
|
||||
{
|
||||
char *end_of_area = NULL;
|
||||
char **new_environ;
|
||||
int i;
|
||||
|
||||
/*
|
||||
* check for contiguous argv strings
|
||||
*/
|
||||
for (i = 0; i < argc; i++)
|
||||
{
|
||||
if (i == 0 || end_of_area + 1 == argv[i])
|
||||
end_of_area = argv[i] + strlen(argv[i]);
|
||||
}
|
||||
|
||||
if (end_of_area == NULL) /* probably can't happen? */
|
||||
{
|
||||
ps_buffer = NULL;
|
||||
ps_buffer_size = 0;
|
||||
return argv;
|
||||
}
|
||||
|
||||
/*
|
||||
* check for contiguous environ strings following argv
|
||||
*/
|
||||
for (i = 0; environ[i] != NULL; i++)
|
||||
{
|
||||
if (end_of_area + 1 == environ[i])
|
||||
end_of_area = environ[i] + strlen(environ[i]);
|
||||
}
|
||||
|
||||
ps_buffer = argv[0];
|
||||
last_status_len = ps_buffer_size = end_of_area - argv[0];
|
||||
|
||||
/*
|
||||
* move the environment out of the way
|
||||
*/
|
||||
new_environ = (char **) malloc((i + 1) * sizeof(char *));
|
||||
for (i = 0; environ[i] != NULL; i++)
|
||||
new_environ[i] = strdup(environ[i]);
|
||||
new_environ[i] = NULL;
|
||||
environ = new_environ;
|
||||
}
|
||||
|
||||
/*
|
||||
* If we're going to change the original argv[] then make a copy for
|
||||
* argument parsing purposes.
|
||||
*
|
||||
* (NB: do NOT think to remove the copying of argv[], even though
|
||||
* postmaster.c finishes looking at argv[] long before we ever consider
|
||||
* changing the ps display. On some platforms, getopt() keeps pointers
|
||||
* into the argv array, and will get horribly confused when it is
|
||||
* re-called to analyze a subprocess' argument string if the argv storage
|
||||
* has been clobbered meanwhile. Other platforms have other dependencies
|
||||
* on argv[].
|
||||
*/
|
||||
{
|
||||
char **new_argv;
|
||||
int i;
|
||||
|
||||
new_argv = (char **) malloc((argc + 1) * sizeof(char *));
|
||||
for (i = 0; i < argc; i++)
|
||||
new_argv[i] = strdup(argv[i]);
|
||||
new_argv[argc] = NULL;
|
||||
|
||||
argv = new_argv;
|
||||
}
|
||||
|
||||
return argv;
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
/***************************************************************************
|
||||
Process rename functions
|
||||
-----------------------------------------
|
||||
begin : 2013/06/21
|
||||
copyright : (C) 2005 Solbox Inc.
|
||||
author : Dev 1 Team
|
||||
email : dev1@solbox.com
|
||||
version : 3.2.0
|
||||
|
||||
CopyRight(C) 2005 Solbox Inc. All Rights reserved.
|
||||
Redistribution and use in source and binary forms, with or with out
|
||||
modification, are not permitted in outside of Solbox Inc.
|
||||
*****************************************************************************/
|
||||
|
||||
#ifndef __PROCESS_RENAME_H__
|
||||
#define __PROCESS_RENAME_H__
|
||||
|
||||
#include <unistd.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/// @brief linux의 Process Title을 변경
|
||||
void set_ps_display(const char *activity, bool force);
|
||||
|
||||
/// @brief main에 argv의 실제 위치를 기억하고 새로은 메모리 활당하여 반환
|
||||
char ** save_ps_display_args(int argc, char **argv);
|
||||
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
|
||||
#endif // __PROCESS_RENAME_H__
|
||||
@@ -0,0 +1,345 @@
|
||||
#include "CategorizeThread.h"
|
||||
|
||||
#include <unistd.h>
|
||||
#include <string.h>
|
||||
#include <errno.h>
|
||||
#include <list>
|
||||
|
||||
using namespace std;
|
||||
|
||||
#define DB_INFORMATION_UPDATE_INTERVAL 3 // sec
|
||||
//#define DB_INFORMATION_UPDATE_INTERVAL 1 // sec
|
||||
#define DEFAULT_QUERY_BUFFER_SIZE 1024
|
||||
|
||||
|
||||
// 2013-10-15
|
||||
// report log를 위한 추가 내역
|
||||
#define REPORT_LOG( format, ...) \
|
||||
m_LoggerReport.Write( LOG_ALERT, format, ##__VA_ARGS__ )
|
||||
|
||||
CCategorizeThread::CCategorizeThread(CQueue<CFileInfo>* pQueueFileInfo
|
||||
, CQueue<CFileInfo>* pQueueDeleteJob
|
||||
, CQueue<CFileInfo>* pQueueCompleteJob)
|
||||
:m_pQueueFileInfo(pQueueFileInfo)
|
||||
, m_pQueueDeleteJob(pQueueDeleteJob)
|
||||
, m_pQueueCompleteJob(pQueueCompleteJob)
|
||||
{
|
||||
m_pPgSQL = NULL;
|
||||
|
||||
// 멤버 변수 초기화
|
||||
m_threadHandle = 0;
|
||||
m_bServiceTableSeparate = false;
|
||||
}
|
||||
|
||||
CCategorizeThread::~CCategorizeThread()
|
||||
{
|
||||
DbClose();
|
||||
// Thread 동작 정지 처리
|
||||
// - 만약 Thread 가 이미 종료된 경우 m_threadHandle 이 다른 Thread Handle 일 수 있으므로
|
||||
// 업무 Flow 수정시 주의할 것
|
||||
if( m_threadHandle != 0 )
|
||||
pthread_cancel( m_threadHandle );
|
||||
}
|
||||
|
||||
/// @brief DB 연결 함수.
|
||||
bool CCategorizeThread::DbConnect()
|
||||
{
|
||||
if( m_pPgSQL != NULL )
|
||||
{
|
||||
DbClose();
|
||||
}
|
||||
m_pPgSQL = new DataBase;
|
||||
if( m_pPgSQL == NULL )
|
||||
{
|
||||
LOG(LERR, "Creating new Database has failed.");
|
||||
return false;
|
||||
}
|
||||
if( m_pPgSQL->PgOpenDB(m_szHost, m_nPort, m_szDBName, m_szAcct, m_szPasswd) == NULL )
|
||||
{
|
||||
LOG(LERR, "Connecting to Database has failed.");
|
||||
DbClose();
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// @breif DB close 함수.
|
||||
void CCategorizeThread::DbClose()
|
||||
{
|
||||
if( m_pPgSQL != NULL )
|
||||
{
|
||||
delete m_pPgSQL;
|
||||
m_pPgSQL = NULL;
|
||||
}
|
||||
}
|
||||
|
||||
bool CCategorizeThread::ThreadInit()
|
||||
{
|
||||
FUNC_BEGIN();
|
||||
|
||||
// RCDB 접속 처리를 위한 객체 생성
|
||||
DataBase rcdb;
|
||||
|
||||
m_szHost = CProcessStatus::GetInstance()->GetRcdbIp();
|
||||
m_nPort = CProcessStatus::GetInstance()->GetRcdbPort();
|
||||
m_szDBName = CProcessStatus::GetInstance()->GetRcdbName();
|
||||
m_szAcct = CProcessStatus::GetInstance()->GetRcdbAcct();
|
||||
m_szPasswd = CProcessStatus::GetInstance()->GetRcdbAcctPw();
|
||||
|
||||
// 최초 초기화 시에는 DB연결 정보들이 제대로 되는것인지에 대한
|
||||
// 확인만 처리 한다.
|
||||
if (rcdb.PgOpenDB(m_szHost, m_nPort, m_szDBName, m_szAcct, m_szPasswd) == NULL )
|
||||
{
|
||||
LOG(LERR, "Connecting to Database has failed.");
|
||||
return false;
|
||||
}
|
||||
|
||||
// 접속 성공한 경우...
|
||||
LOG( LINF, "RCDB connection test ok..." );
|
||||
|
||||
// 서비스 table 분리된 신규 형상인지.. 구형 형상인지 체크하여
|
||||
// m_bServiceTableSeparate 변수 설정 처리.
|
||||
// 해당 변수 초기화는 생성자에서 1차로 수행함.
|
||||
char szQuery[1024];
|
||||
snprintf( szQuery, 1023,"SELECT * FROM pg_tables WHERE schemaname = 'public' AND tablename = 't_dav_resource' " );
|
||||
|
||||
rcdb.PgDoExec( szQuery );
|
||||
if( rcdb.PgResult( DataBase::NOT_CLEAR ) < 0 )
|
||||
{
|
||||
// Query 수행 결과 오류 발생시...
|
||||
// - pg_tables 가 존재하지 않을 경우 오류 발생 가능...
|
||||
// - 이는 RCDB 가 아직 적절하게 구성되지 않았다는 의미이므로... Init()함수를 오류로 처리한다.
|
||||
LOG( LERR, "RCDB t_dav_resource exist check failed.[%s][%s]", rcdb.GetErrorMessage().c_str(), szQuery );
|
||||
|
||||
rcdb.PgClear();
|
||||
rcdb.PgCloseDB();
|
||||
|
||||
return false;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Query 수행이 정상인 경우.
|
||||
int nResult = rcdb.GetNoTuples();
|
||||
if( nResult > 0 )
|
||||
{
|
||||
// t_dav_resource 테이블이 존재하는 경우...
|
||||
m_bServiceTableSeparate = false;
|
||||
_LOG( LINF, "CCategorizeThread: t_dav_resource table exist.[Old RCDB Type]" );
|
||||
}
|
||||
else
|
||||
{
|
||||
// t_dav_resource 테이블이 존재하지 않는 서비스별 테이블 분리 형상인 경우.
|
||||
m_bServiceTableSeparate = true;
|
||||
_LOG( LINF, "CCategorizeThread: t_dav_resource table not exist.[New RCDB Type]" );
|
||||
}
|
||||
}
|
||||
|
||||
// RCDB 조회 결과 set 를 clear 처리 후 RCDB 접속 해제.
|
||||
rcdb.PgClear();
|
||||
rcdb.PgCloseDB();
|
||||
|
||||
FUNC_END();
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CCategorizeThread::Categorize()
|
||||
{
|
||||
FUNC_BEGIN();
|
||||
CFileInfo objFileInfo;
|
||||
int nCheck = 0;
|
||||
|
||||
// Query 문장 저장을 위한 버퍼 생성
|
||||
char szQuery[DEFAULT_QUERY_BUFFER_SIZE];
|
||||
int nResult = 0;
|
||||
|
||||
if( m_pPgSQL == NULL )
|
||||
{
|
||||
LOG(LWAR, "Pgsql is not initialized.");
|
||||
return false;
|
||||
}
|
||||
|
||||
while( m_pQueueFileInfo->GetSize() > 0 )
|
||||
{
|
||||
// 1. QueuePop
|
||||
objFileInfo = m_pQueueFileInfo->Front();
|
||||
|
||||
// Front 는 참조만하고 실제 pop은 Pop() 함수를 통해 한다.
|
||||
m_pQueueFileInfo->Pop();
|
||||
|
||||
// 2. resource type 을 체크 한다.
|
||||
// 경로의 경우는 바로 Compelete Job 으로 분류한다.
|
||||
if( objFileInfo.m_nType == 1 )
|
||||
{
|
||||
m_pQueueCompleteJob->Push(objFileInfo);
|
||||
continue;
|
||||
}
|
||||
|
||||
//!! webting 수정 필요
|
||||
if(m_bServiceTableSeparate == false)
|
||||
{
|
||||
// 구형 DB 스키마 용
|
||||
snprintf(szQuery, DEFAULT_QUERY_BUFFER_SIZE - 1,
|
||||
"SELECT uri ,host_name "
|
||||
"FROM t_dav_resource "
|
||||
"WHERE filename_hash = '%s' AND host_name= '%s' AND deleted_yn = 'N'; "
|
||||
, objFileInfo.m_szFileNameHash.c_str()
|
||||
, objFileInfo.m_szHostName.c_str());
|
||||
}
|
||||
else
|
||||
{
|
||||
// 신규형상.
|
||||
snprintf(szQuery, DEFAULT_QUERY_BUFFER_SIZE - 1,
|
||||
"SELECT uri ,host_name "
|
||||
"FROM t_meta_%s "
|
||||
"WHERE filename_hash = '%s' AND host_name= '%s' AND deleted_yn = 'N'; "
|
||||
, objFileInfo.m_szSvcTranid.c_str()
|
||||
, objFileInfo.m_szFileNameHash.c_str()
|
||||
, objFileInfo.m_szHostName.c_str());
|
||||
}
|
||||
|
||||
LOG( LDEV, "Checking Query : [%s]", szQuery );
|
||||
|
||||
// Query 실행
|
||||
m_pPgSQL->PgDoExec(szQuery);
|
||||
nResult = m_pPgSQL->PgResult( DataBase::NOT_CLEAR );
|
||||
|
||||
if( nResult < 0 )
|
||||
{
|
||||
// RCDB t_sms_sp_svc_product 테이블상에 preserv_day 컬럼이 존재하지 않는 경우
|
||||
// Replication 처리를 당장 수행할 필요가 없으므로 루프 대기처리후 다음에 다시 조회처리.
|
||||
if( m_pPgSQL != NULL )
|
||||
{
|
||||
LOG(LWAR, "RCDB Query failed.[%d][%s]", nResult, m_pPgSQL->GetErrorMessage().c_str() );
|
||||
m_pPgSQL->PgClear();
|
||||
DbClose();
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
nResult = m_pPgSQL->GetNoTuples();
|
||||
|
||||
|
||||
for( int i =0 ; i< nResult; i++ )
|
||||
{
|
||||
string szUri = m_pPgSQL->GetValue(i,0);
|
||||
string szHostName = m_pPgSQL->GetValue(i,1);
|
||||
|
||||
// uri 가 같은것이 존재하면 Metda Data 만 삭제하도록 Compelete Job 으로 분류한다.
|
||||
if( objFileInfo.m_szUri.compare(szUri.c_str()) != 0
|
||||
&& objFileInfo.m_szHostName.compare(szHostName.c_str()) == 0)
|
||||
{
|
||||
LOG( LINF ,"files is exist link....%s , %s ", objFileInfo.m_szFileNameHash.c_str(), m_pPgSQL->GetValue(i,0));
|
||||
nCheck = 1;
|
||||
// 존재 한다면 다음 컨텐츠를 확인 하도록 loop 시작으로 보낸다.
|
||||
break;
|
||||
}
|
||||
|
||||
if( objFileInfo.m_szUri.compare(szUri.c_str()) == 0
|
||||
&& objFileInfo.m_szHostName.compare(szHostName.c_str()) == 0)
|
||||
{
|
||||
nCheck = -1;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
// copy 또는 link 된 파일이 있는가?
|
||||
if( nCheck == 1 )
|
||||
{
|
||||
// 있으면 Meta 만 삭제..
|
||||
m_pQueueCompleteJob->Push(objFileInfo);
|
||||
}
|
||||
else if( nCheck == -1 )
|
||||
{
|
||||
// 2013-10-15
|
||||
// app. log에도 상황을 기록하고..
|
||||
// report log에도 기록하도록 조정한다.
|
||||
LOG(LALT, "Duplicate content event. HostName:[%s], Uri:[%s]", objFileInfo.m_szHostName.c_str(), objFileInfo.m_szUri.c_str() );
|
||||
|
||||
// 2014-04-17
|
||||
// #18785 이슈에 의해 Meta Data 삭제 처리 등록
|
||||
m_pQueueCompleteJob->Push(objFileInfo);
|
||||
|
||||
}
|
||||
else
|
||||
{
|
||||
// 없으면 물리파일도 삭제..
|
||||
m_pQueueDeleteJob->Push(objFileInfo);
|
||||
}
|
||||
|
||||
nCheck = 0;
|
||||
|
||||
// Query Result set Clear.
|
||||
m_pPgSQL->PgClear();
|
||||
}
|
||||
FUNC_END();
|
||||
return true;
|
||||
}
|
||||
|
||||
///@brief 이 함수에서 컨트롤 로직이 표현된다.
|
||||
void CCategorizeThread::Execute()
|
||||
{
|
||||
FUNC_BEGIN();
|
||||
// 아래 함수에서 return false 가 되더라도 무시한다.
|
||||
// 본 쓰레드 내에서 계속 재시도 할 수 있도록 한다.
|
||||
// Notify : 해당 함수에서 로깅처리됨
|
||||
if ( DbConnect() == false){;}
|
||||
|
||||
while(1)
|
||||
{
|
||||
// 아래 함수에서 return false 가 되면 기존 세션에대해 정리한 후
|
||||
// DB Connection을 다시 요청한다.
|
||||
if( Categorize() == false )
|
||||
{
|
||||
// 한 번더 정리한 후
|
||||
DbClose();
|
||||
|
||||
sleep( DB_INFORMATION_UPDATE_INTERVAL );
|
||||
// 연결 재시도 함.
|
||||
if ( DbConnect() == false){;}
|
||||
|
||||
// 두 번 sleep 하는것을 막기 위해서...
|
||||
continue;
|
||||
}
|
||||
sleep( DB_INFORMATION_UPDATE_INTERVAL );
|
||||
}
|
||||
|
||||
// 쓰레드 종료 될 때 DB 세션 정리 한다.
|
||||
DbClose();
|
||||
|
||||
LOG(LERR, "Thread create failed.: errno:%d errmsg:%s", errno, strerror(errno));
|
||||
FUNC_END();
|
||||
}
|
||||
|
||||
void* CCategorizeThread::EntryPoint(void* arg)
|
||||
{
|
||||
CCategorizeThread* pObject = reinterpret_cast<CCategorizeThread *>(arg);
|
||||
pthread_detach( pthread_self() );
|
||||
|
||||
pthread_testcancel();
|
||||
pObject->Execute();
|
||||
pthread_testcancel();
|
||||
|
||||
// Thread 종료시 m_threadHandle 값을 초기화 처리.
|
||||
// - 소멸자에서 잘못된 Thread 를 종료할 수 있기 때문.
|
||||
pObject->m_threadHandle = 0;
|
||||
|
||||
delete pObject;
|
||||
FUNC_END();
|
||||
return 0;
|
||||
}
|
||||
|
||||
bool CCategorizeThread::Start()
|
||||
{
|
||||
int nRet = ::pthread_create(&m_threadHandle, 0, CCategorizeThread::EntryPoint, this);
|
||||
|
||||
|
||||
if( nRet )
|
||||
{
|
||||
LOG(LERR, "Thread create failed.: errno:%d errmsg:%s", errno, strerror(errno));
|
||||
return false;
|
||||
}
|
||||
LOG(LDBG, "Thread create succeed");
|
||||
sleep(0);
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
/***************************************************************************
|
||||
Replicate Work Class
|
||||
-----------------------------------------
|
||||
begin : 2012/10/14
|
||||
copyright : (C) 2010 SolutionBox Inc.
|
||||
author : Service 1 Team
|
||||
email : svc1@solbox.com
|
||||
version : 1.0
|
||||
|
||||
CopyRight(C) 2010 SolutionBox Inc. All Rights reserved.
|
||||
Redistribution and use in source and binary forms, with or with out
|
||||
modification, are not permitted in outside of SolutionBox Inc.
|
||||
***************************************************************************/
|
||||
|
||||
#ifndef __CATEGORIZE_THREAD__
|
||||
#define __CATEGORIZE_THREAD__
|
||||
|
||||
#include <pthread.h>
|
||||
#include <string>
|
||||
#include "Logger.h"
|
||||
#include "Data.h"
|
||||
#include "DataQueue.h"
|
||||
#include "ProcessStatus.h"
|
||||
#include "Database.h"
|
||||
|
||||
/// @brief
|
||||
class CCategorizeThread
|
||||
{
|
||||
public:
|
||||
/// @brief 생성자
|
||||
/// @param [in] pLogger 로깅을 위한 클래스.
|
||||
CCategorizeThread(CQueue<CFileInfo>* pQueueFileInfo
|
||||
, CQueue<CFileInfo>* pQueueDeleteJob
|
||||
, CQueue<CFileInfo>* pQueueCompleteJob);
|
||||
~CCategorizeThread();
|
||||
|
||||
/// @brief Thread를 생성하고, 이를 시작한다.
|
||||
/// @param none
|
||||
/// @return 성공은 return true 실패는 return false
|
||||
bool Start();
|
||||
|
||||
bool DbConnect();
|
||||
void DbClose();
|
||||
|
||||
/// @brief ProcessStatus 내의 RCDB 관련 설정값을 이용해 DB Connection을 한다.
|
||||
/// @param None
|
||||
/// @return 성공하면 return true 실패하면 return false
|
||||
bool ThreadInit();
|
||||
|
||||
bool Categorize();
|
||||
|
||||
|
||||
// Attributes
|
||||
private:
|
||||
DataBase* m_pPgSQL;
|
||||
|
||||
CQueue<CFileInfo>* m_pQueueFileInfo;
|
||||
CQueue<CFileInfo>* m_pQueueDeleteJob;
|
||||
CQueue<CFileInfo>* m_pQueueCompleteJob;
|
||||
|
||||
std::string m_szHost;
|
||||
int m_nPort;
|
||||
std::string m_szDBName;
|
||||
std::string m_szAcct;
|
||||
std::string m_szPasswd;
|
||||
|
||||
bool m_bServiceTableSeparate;
|
||||
// 쓰레드 핸들
|
||||
pthread_t m_threadHandle;
|
||||
|
||||
// 쓰레드 시작 루틴이다.
|
||||
static void* EntryPoint(void* arg);
|
||||
|
||||
// 해당 함수의 내용은 수정하지 말것.
|
||||
void Execute();
|
||||
|
||||
};
|
||||
#endif //__CATEGORIZE_THREAD__
|
||||
@@ -0,0 +1,323 @@
|
||||
#include "CompleteThread.h"
|
||||
|
||||
#include <unistd.h>
|
||||
#include <string.h>
|
||||
#include <errno.h>
|
||||
#include <sys/time.h>
|
||||
|
||||
using namespace std;
|
||||
|
||||
#define DB_INFORMATION_UPDATE_INTERVAL 300 // sec
|
||||
//#define DB_INFORMATION_UPDATE_INTERVAL 1 // sec
|
||||
#define DEFAULT_QUERY_BUFFER_SIZE 1024
|
||||
|
||||
string StringReplace(const string& source, const string search, const string replacement)
|
||||
{
|
||||
string r = source;
|
||||
|
||||
string::size_type pos = 0;
|
||||
|
||||
while ( (pos = r.find(search, pos)) != string::npos )
|
||||
{
|
||||
r.replace( pos, search.size(), replacement );
|
||||
pos = pos + replacement.size();
|
||||
}
|
||||
|
||||
return r;
|
||||
}
|
||||
|
||||
CCompleteThread::CCompleteThread(CQueue<CFileInfo>* pQueueCompleteJob)
|
||||
: m_pQueueCompleteJob(pQueueCompleteJob)
|
||||
{
|
||||
m_pPgSQL = NULL;
|
||||
// 멤버 변수 초기화
|
||||
m_threadHandle = 0;
|
||||
m_bServiceTableSeparate = false;
|
||||
}
|
||||
|
||||
CCompleteThread::~CCompleteThread()
|
||||
{
|
||||
DbClose();
|
||||
// Thread 동작 정지 처리
|
||||
// - 만약 Thread 가 이미 종료된 경우 m_threadHandle 이 다른 Thread Handle 일 수 있으므로
|
||||
// 업무 Flow 수정시 주의할 것
|
||||
if( m_threadHandle != 0 )
|
||||
pthread_cancel( m_threadHandle );
|
||||
}
|
||||
|
||||
/// @brief DB 연결 함수.
|
||||
bool CCompleteThread::DbConnect()
|
||||
{
|
||||
if( m_pPgSQL != NULL )
|
||||
{
|
||||
DbClose();
|
||||
}
|
||||
m_pPgSQL = new DataBase;
|
||||
if( m_pPgSQL == NULL )
|
||||
{
|
||||
LOG(LERR, "Creating new Database has failed.");
|
||||
return false;
|
||||
}
|
||||
if( m_pPgSQL->PgOpenDB(m_szHost, m_nPort, m_szDBName, m_szAcct, m_szPasswd) == NULL )
|
||||
{
|
||||
LOG(LERR, "Connecting to Database has failed.");
|
||||
DbClose();
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// @breif DB close 함수.
|
||||
void CCompleteThread::DbClose()
|
||||
{
|
||||
if( m_pPgSQL != NULL )
|
||||
{
|
||||
delete m_pPgSQL;
|
||||
m_pPgSQL = NULL;
|
||||
}
|
||||
}
|
||||
|
||||
bool CCompleteThread::ThreadInit()
|
||||
{
|
||||
FUNC_BEGIN();
|
||||
|
||||
// 조회 정보를 저장할 Queue 에 대한 참조 포인터가 NULL 경우 오류 처리
|
||||
if( m_pQueueCompleteJob == NULL )
|
||||
{
|
||||
LOG(LERR, "FileInfo Queue Pointer is NULL");
|
||||
return false;
|
||||
}
|
||||
|
||||
// RCDB 접속 처리를 위한 객체 생성
|
||||
DataBase rcdb;
|
||||
|
||||
m_szHost = CProcessStatus::GetInstance()->GetRcdbIp();
|
||||
m_nPort = CProcessStatus::GetInstance()->GetRcdbPort();
|
||||
m_szDBName = CProcessStatus::GetInstance()->GetRcdbName();
|
||||
m_szAcct = CProcessStatus::GetInstance()->GetRcdbAcct();
|
||||
m_szPasswd = CProcessStatus::GetInstance()->GetRcdbAcctPw();
|
||||
|
||||
// 최초 초기화 시에는 DB연결 정보들이 제대로 되는것인지에 대한
|
||||
// 확인만 처리 한다.
|
||||
if (rcdb.PgOpenDB(m_szHost, m_nPort, m_szDBName, m_szAcct, m_szPasswd) == NULL )
|
||||
{
|
||||
LOG(LERR, "Connecting to Database has failed.");
|
||||
return false;
|
||||
}
|
||||
|
||||
// 접속 성공한 경우...
|
||||
LOG( LINF, "RCDB connection test ok..." );
|
||||
|
||||
// 서비스 table 분리된 신규 형상인지.. 구형 형상인지 체크하여
|
||||
// m_bServiceTableSeparate 변수 설정 처리.
|
||||
// 해당 변수 초기화는 생성자에서 1차로 수행함.
|
||||
char szQuery[1024];
|
||||
snprintf( szQuery, 1023,"SELECT * FROM pg_tables WHERE schemaname = 'public' AND tablename = 't_dav_resource' " );
|
||||
|
||||
rcdb.PgDoExec( szQuery );
|
||||
if( rcdb.PgResult( DataBase::NOT_CLEAR ) < 0 )
|
||||
{
|
||||
// Query 수행 결과 오류 발생시...
|
||||
// - pg_tables 가 존재하지 않을 경우 오류 발생 가능...
|
||||
// - 이는 RCDB 가 아직 적절하게 구성되지 않았다는 의미이므로... Init()함수를 오류로 처리한다.
|
||||
LOG( LERR, "RCDB t_dav_resource exist check failed.[%s][%s]", rcdb.GetErrorMessage().c_str(), szQuery );
|
||||
|
||||
rcdb.PgClear();
|
||||
rcdb.PgCloseDB();
|
||||
|
||||
return false;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Query 수행이 정상인 경우.
|
||||
int nResult = rcdb.GetNoTuples();
|
||||
if( nResult > 0 )
|
||||
{
|
||||
// t_dav_resource 테이블이 존재하는 경우...
|
||||
m_bServiceTableSeparate = false;
|
||||
_LOG( LINF, "CCompleteThread: t_dav_resource table exist.[Old RCDB Type]" );
|
||||
}
|
||||
else
|
||||
{
|
||||
// t_dav_resource 테이블이 존재하지 않는 서비스별 테이블 분리 형상인 경우.
|
||||
m_bServiceTableSeparate = true;
|
||||
_LOG( LINF, "CCompleteThread: t_dav_resource table not exist.[New RCDB Type]" );
|
||||
}
|
||||
}
|
||||
|
||||
// RCDB 조회 결과 set 를 clear 처리 후 RCDB 접속 해제.
|
||||
rcdb.PgClear();
|
||||
rcdb.PgCloseDB();
|
||||
|
||||
FUNC_END();
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
bool CCompleteThread::DeleteMeta()
|
||||
{
|
||||
FUNC_BEGIN();
|
||||
// Query 문장 저장을 위한 버퍼 생성
|
||||
char szQuery[DEFAULT_QUERY_BUFFER_SIZE];
|
||||
int nResult = 0;
|
||||
|
||||
if( m_pPgSQL == NULL )
|
||||
{
|
||||
LOG(LWAR, "Not initialized.");
|
||||
return false;
|
||||
}
|
||||
|
||||
while(1)
|
||||
{
|
||||
CFileInfo objDelFileInfo;
|
||||
std::string m_szURI;
|
||||
|
||||
if( m_pQueueCompleteJob->GetSize() <= 0 )
|
||||
{
|
||||
LOG(LDBG, "CompleteQueue Job is Empty...");
|
||||
sleep(1);
|
||||
continue;
|
||||
}
|
||||
|
||||
// 1. QueuePop
|
||||
objDelFileInfo = m_pQueueCompleteJob->Front();
|
||||
m_pQueueCompleteJob->Pop();
|
||||
|
||||
m_szURI = StringReplace(objDelFileInfo.m_szUri, "'", "''");
|
||||
|
||||
if(m_bServiceTableSeparate == false)
|
||||
{
|
||||
// 구형 DB 스키마 용
|
||||
if ( objDelFileInfo.m_nType == 0 )
|
||||
{
|
||||
|
||||
snprintf(szQuery, DEFAULT_QUERY_BUFFER_SIZE - 1,
|
||||
"DELETE FROM t_dav_resource "
|
||||
"WHERE host_name = '%s' AND uri = '%s' AND filename_hash = '%s' AND deleted_yn = 'Y'; "
|
||||
, objDelFileInfo.m_szHostName.c_str()
|
||||
, m_szURI.c_str()
|
||||
, objDelFileInfo.m_szFileNameHash.c_str() );
|
||||
}
|
||||
else
|
||||
{
|
||||
snprintf(szQuery, DEFAULT_QUERY_BUFFER_SIZE - 1,
|
||||
"DELETE FROM t_dav_resource "
|
||||
"WHERE host_name = '%s' AND uri = '%s' AND deleted_yn = 'Y'; "
|
||||
, objDelFileInfo.m_szHostName.c_str()
|
||||
, m_szURI.c_str() );
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// 신규형상.
|
||||
if ( objDelFileInfo.m_nType == 0 )
|
||||
{
|
||||
snprintf(szQuery, DEFAULT_QUERY_BUFFER_SIZE - 1,
|
||||
"DELETE FROM t_meta_%s "
|
||||
"WHERE host_name = '%s' AND uri = '%s' AND filename_hash = '%s' AND deleted_yn = 'Y'; "
|
||||
, objDelFileInfo.m_szSvcTranid.c_str()
|
||||
, objDelFileInfo.m_szHostName.c_str()
|
||||
, m_szURI.c_str()
|
||||
, objDelFileInfo.m_szFileNameHash.c_str() );
|
||||
}
|
||||
else
|
||||
{
|
||||
snprintf(szQuery, DEFAULT_QUERY_BUFFER_SIZE - 1,
|
||||
"DELETE FROM t_meta_%s "
|
||||
"WHERE host_name = '%s' AND uri = '%s' AND deleted_yn = 'Y'; "
|
||||
, objDelFileInfo.m_szSvcTranid.c_str()
|
||||
, objDelFileInfo.m_szHostName.c_str()
|
||||
, m_szURI.c_str() );
|
||||
}
|
||||
}
|
||||
|
||||
LOG( LDEV, "Delete Query : [%s]", szQuery );
|
||||
|
||||
// Query 실행
|
||||
m_pPgSQL->PgDoExec(szQuery);
|
||||
nResult = m_pPgSQL->PgResult( DataBase::CLEAR );
|
||||
if( nResult < 0 )
|
||||
{
|
||||
LOG(LWAR, "RCDB Query failed.[%d][%s]", nResult, m_pPgSQL->GetErrorMessage().c_str() );
|
||||
DbClose();
|
||||
// 실패 해도 변경 주기 만큼 슬립한다.
|
||||
return false;
|
||||
}
|
||||
|
||||
LOG(LDBG, "Delete!! sp_svc_tran_id = %s, host_name = %s, uri = %s, filename_hash = %s;",
|
||||
objDelFileInfo.m_szSvcTranid.c_str()
|
||||
, objDelFileInfo.m_szHostName.c_str()
|
||||
, objDelFileInfo.m_szUri.c_str()
|
||||
, objDelFileInfo.m_szFileNameHash.c_str() );
|
||||
}
|
||||
FUNC_END();
|
||||
return true;
|
||||
}
|
||||
|
||||
///@brief 이 함수에서 컨트롤 로직이 표현된다.
|
||||
void CCompleteThread::Execute()
|
||||
{
|
||||
FUNC_BEGIN();
|
||||
// 아래 함수에서 return false 가 되더라도 무시한다.
|
||||
// 본 쓰레드 내에서 계속 재시도 할 수 있도록 한다.
|
||||
// Notify : 해당 함수에서 로깅처리됨
|
||||
if ( DbConnect() == false){;}
|
||||
|
||||
while(1)
|
||||
{
|
||||
// 아래 함수에서 return false 가 되면 기존 세션에대해 정리한 후
|
||||
// DB Connection을 다시 요청한다.
|
||||
if( DeleteMeta() == false )
|
||||
{
|
||||
// 한 번더 정리한 후
|
||||
DbClose();
|
||||
LOG(LWAR, "RCDB DeleteMeta Failed.");
|
||||
|
||||
// 연결 재시도 함.
|
||||
if ( DbConnect() == false)
|
||||
{
|
||||
LOG(LWAR, "RCDB Connect Failed.");
|
||||
}
|
||||
sleep( 1 );
|
||||
continue;
|
||||
}
|
||||
sleep( DB_INFORMATION_UPDATE_INTERVAL );
|
||||
}
|
||||
|
||||
// 쓰레드 종료 될 때 DB 세션 정리 한다.
|
||||
DbClose();
|
||||
|
||||
LOG(LERR, "Thread create failed.: errno:%d errmsg:%s", errno, strerror(errno));
|
||||
FUNC_END();
|
||||
}
|
||||
|
||||
void* CCompleteThread::EntryPoint(void* arg)
|
||||
{
|
||||
CCompleteThread* pObject = reinterpret_cast<CCompleteThread *>(arg);
|
||||
pthread_detach( pthread_self() );
|
||||
|
||||
pthread_testcancel();
|
||||
pObject->Execute();
|
||||
pthread_testcancel();
|
||||
|
||||
// Thread 종료시 m_threadHandle 값을 초기화 처리.
|
||||
// - 소멸자에서 잘못된 Thread 를 종료할 수 있기 때문.
|
||||
pObject->m_threadHandle = 0;
|
||||
|
||||
delete pObject;
|
||||
return 0;
|
||||
}
|
||||
|
||||
bool CCompleteThread::Start()
|
||||
{
|
||||
int nRet = ::pthread_create(&m_threadHandle, 0, CCompleteThread::EntryPoint, this);
|
||||
|
||||
if( nRet )
|
||||
{
|
||||
LOG(LERR, "Thread create failed.: errno:%d errmsg:%s", errno, strerror(errno));
|
||||
return false;
|
||||
}
|
||||
LOG(LDBG, "Thread create succeed");
|
||||
sleep(0);
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
/***************************************************************************
|
||||
Replicate Work Class
|
||||
-----------------------------------------
|
||||
begin : 2012/10/14
|
||||
copyright : (C) 2010 SolutionBox Inc.
|
||||
author : Service 1 Team
|
||||
email : svc1@solbox.com
|
||||
version : 1.0
|
||||
|
||||
CopyRight(C) 2010 SolutionBox Inc. All Rights reserved.
|
||||
Redistribution and use in source and binary forms, with or with out
|
||||
modification, are not permitted in outside of SolutionBox Inc.
|
||||
***************************************************************************/
|
||||
|
||||
#ifndef __COMPELETE_THREAD__
|
||||
#define __COMPELETE_THREAD__
|
||||
|
||||
#include <pthread.h>
|
||||
#include <string>
|
||||
#include "Logger.h"
|
||||
#include "Data.h"
|
||||
#include "DataQueue.h"
|
||||
#include "ProcessStatus.h"
|
||||
#include "Database.h"
|
||||
|
||||
/// @brief
|
||||
class CCompleteThread
|
||||
{
|
||||
public:
|
||||
/// @brief 생성자
|
||||
/// @param [in] pLogger 로깅을 위한 클래스.
|
||||
CCompleteThread(CQueue<CFileInfo>* pQueueCompleteJob);
|
||||
~CCompleteThread();
|
||||
|
||||
/// @brief Thread를 생성하고, 이를 시작한다.
|
||||
/// @param none
|
||||
/// @return 성공은 return true 실패는 return false
|
||||
bool Start();
|
||||
|
||||
bool DbConnect();
|
||||
void DbClose();
|
||||
|
||||
/// @brief ProcessStatus 내의 RCDB 관련 설정값을 이용해 DB Connection을 한다.
|
||||
/// @param None
|
||||
/// @return 성공하면 return true 실패하면 return false
|
||||
bool ThreadInit();
|
||||
bool DeleteMeta();
|
||||
// Attributes
|
||||
private:
|
||||
DataBase* m_pPgSQL;
|
||||
|
||||
CQueue<CFileInfo>* m_pQueueCompleteJob;
|
||||
|
||||
std::string m_szHost;
|
||||
int m_nPort;
|
||||
std::string m_szDBName;
|
||||
std::string m_szAcct;
|
||||
std::string m_szPasswd;
|
||||
|
||||
bool m_bServiceTableSeparate;
|
||||
// 쓰레드 핸들
|
||||
pthread_t m_threadHandle;
|
||||
|
||||
// 쓰레드 시작 루틴이다.
|
||||
static void* EntryPoint(void* arg);
|
||||
|
||||
// 해당 함수의 내용은 수정하지 말것.
|
||||
void Execute();
|
||||
};
|
||||
#endif //__COMPELETE_THREAD__
|
||||
@@ -0,0 +1,43 @@
|
||||
/***************************************************************************
|
||||
Data Class
|
||||
-----------------------------------------
|
||||
begin : 2012/10/14
|
||||
copyright : (C) 2010 SolutionBox Inc.
|
||||
author : service 1 team
|
||||
email : svc1@solbox.com
|
||||
version : 1.0
|
||||
|
||||
CopyRight(C) 2010 SolutionBox Inc. All Rights reserved.
|
||||
Redistribution and use in source and binary forms, with or with out
|
||||
modification, are not permitted in outside of SolutionBox Inc.
|
||||
***************************************************************************/
|
||||
|
||||
#ifndef __DATA_H__
|
||||
#define __DATA_H__
|
||||
#include <list>
|
||||
#include <string>
|
||||
|
||||
/// @brief CPreserve class
|
||||
class CPreserve
|
||||
{
|
||||
public :
|
||||
/// @brief Service ID
|
||||
std::string m_szServiceID;
|
||||
/// @brief Service º¸Á¸ ±â°£
|
||||
int m_nPreserveDay;
|
||||
};
|
||||
|
||||
/// @brief CSourceData class
|
||||
class CFileInfo
|
||||
{
|
||||
public :
|
||||
std::string m_szSvcTranid;
|
||||
std::string m_szHostName;
|
||||
int m_nType;
|
||||
std::string m_szUri;
|
||||
std::string m_szFileNameHash;
|
||||
unsigned long long m_nContentLength;
|
||||
unsigned long long m_nLastModified;
|
||||
};
|
||||
|
||||
#endif //__DATA_H__
|
||||
@@ -0,0 +1,125 @@
|
||||
/***************************************************************************
|
||||
Queue Class
|
||||
-----------------------------------------
|
||||
begin : 2012/10/14
|
||||
copyright : (C) 2010 SolutionBox Inc.
|
||||
author : service 1 team
|
||||
email : svc1@solbox.com
|
||||
version : 1.0
|
||||
|
||||
CopyRight(C) 2010 SolutionBox Inc. All Rights reserved.
|
||||
Redistribution and use in source and binary forms, with or with out
|
||||
modification, are not permitted in outside of SolutionBox Inc.
|
||||
***************************************************************************/
|
||||
|
||||
|
||||
#include "DataQueue.h"
|
||||
#include "Data.h"
|
||||
|
||||
using namespace std;
|
||||
|
||||
#define MX_LOCK_DATA()\
|
||||
do \
|
||||
{\
|
||||
pthread_mutex_lock(&m_mxData);\
|
||||
} while( 0 )
|
||||
|
||||
#define MX_UNLOCK_DATA()\
|
||||
do \
|
||||
{\
|
||||
pthread_mutex_unlock(&m_mxData);\
|
||||
} while( 0 )
|
||||
#define MX_LOCK_MAXSIZE()\
|
||||
do \
|
||||
{\
|
||||
pthread_mutex_lock(&m_mxMaxSize);\
|
||||
} while( 0 )
|
||||
|
||||
#define MX_UNLOCK_MAXSIZE()\
|
||||
do \
|
||||
{\
|
||||
pthread_mutex_unlock(&m_mxMaxSize);\
|
||||
} while( 0 )
|
||||
|
||||
|
||||
template <class DataClass>
|
||||
CQueue<DataClass>::CQueue()
|
||||
//CQueue::CQueue()
|
||||
: m_nMaxSize(DEFAULT_MAX_QUEUE_SIZE)
|
||||
{
|
||||
pthread_mutex_init(&m_mxData, NULL);
|
||||
pthread_mutex_init(&m_mxMaxSize, NULL);
|
||||
}
|
||||
template <class DataClass>
|
||||
CQueue<DataClass>::~CQueue()
|
||||
{
|
||||
pthread_mutex_destroy(&m_mxData);
|
||||
pthread_mutex_destroy(&m_mxMaxSize);
|
||||
}
|
||||
|
||||
template <class DataClass>
|
||||
void CQueue<DataClass>::Clear(void)
|
||||
{
|
||||
//clear queue
|
||||
MX_LOCK_DATA();
|
||||
while ( !m_qData.empty() )
|
||||
{
|
||||
Pop();
|
||||
}
|
||||
MX_UNLOCK_DATA();
|
||||
}
|
||||
|
||||
template <class DataClass>
|
||||
bool CQueue<DataClass>::Push(DataClass& userData)
|
||||
{
|
||||
if ( GetCurrentMaxSize() != DEFAULT_MAX_QUEUE_SIZE && GetSize() >= GetCurrentMaxSize() )
|
||||
{
|
||||
return false;
|
||||
}
|
||||
MX_LOCK_DATA();
|
||||
m_qData.push(userData);
|
||||
MX_UNLOCK_DATA();
|
||||
return true;
|
||||
}
|
||||
template <class DataClass>
|
||||
bool CQueue<DataClass>::Pop(void)
|
||||
{
|
||||
if ( GetSize() < 0 )
|
||||
{
|
||||
return false;
|
||||
}
|
||||
MX_LOCK_DATA();
|
||||
m_qData.pop();
|
||||
MX_UNLOCK_DATA();
|
||||
return true;
|
||||
}
|
||||
|
||||
template <class DataClass>
|
||||
DataClass CQueue<DataClass>::Front(void)
|
||||
{
|
||||
return m_qData.front();
|
||||
}
|
||||
template <class DataClass>
|
||||
int CQueue<DataClass>::GetCurrentMaxSize(void)
|
||||
{
|
||||
return m_nMaxSize;
|
||||
}
|
||||
template <class DataClass>
|
||||
bool CQueue<DataClass>::SetCurrentMaxSize(int nMaxSize)
|
||||
{
|
||||
if (nMaxSize < 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
MX_LOCK_MAXSIZE();
|
||||
m_nMaxSize = nMaxSize;
|
||||
MX_UNLOCK_MAXSIZE();
|
||||
return true;
|
||||
}
|
||||
template <class DataClass>
|
||||
int CQueue<DataClass>::GetSize(void)
|
||||
{
|
||||
return m_qData.size();
|
||||
}
|
||||
|
||||
template class CQueue<CFileInfo>;
|
||||
@@ -0,0 +1,76 @@
|
||||
/***************************************************************************
|
||||
Queue Class
|
||||
-----------------------------------------
|
||||
begin : 2012/10/14
|
||||
copyright : (C) 2010 SolutionBox Inc.
|
||||
author : service 1 team
|
||||
email : svc1@solbox.com
|
||||
version : 1.0
|
||||
|
||||
CopyRight(C) 2010 SolutionBox Inc. All Rights reserved.
|
||||
Redistribution and use in source and binary forms, with or with out
|
||||
modification, are not permitted in outside of SolutionBox Inc.
|
||||
***************************************************************************/
|
||||
|
||||
#ifndef __DATA_QUEUE_H__
|
||||
#define __DATA_QUEUE_H__
|
||||
|
||||
#include <pthread.h>
|
||||
#include <queue>
|
||||
|
||||
#define DEFAULT_MAX_QUEUE_SIZE 0
|
||||
template <class DataClass>
|
||||
/// @brief CQueue class
|
||||
class CQueue
|
||||
{
|
||||
public :
|
||||
CQueue();
|
||||
~CQueue();
|
||||
/// @brief clear queue
|
||||
void Clear(void);
|
||||
|
||||
/// @brief push data
|
||||
/// @param userData [in] DataClass
|
||||
/// @return 성공은 return true, 그 외에는 return false
|
||||
bool Push(DataClass& userData);
|
||||
|
||||
/// @brief pop data ( just remove from queue )
|
||||
/// @return 성공은 return true, 그 외에는 return false
|
||||
bool Pop();
|
||||
|
||||
/// @brief GetDataClass, (it doesn't remove data from queue)
|
||||
/// @return 성공은 return true, 그 외에는 return false
|
||||
DataClass Front();
|
||||
|
||||
/// @brief get max queue size, default is 0 (0 means infinity)
|
||||
/// @return 성공은 0,+ 그 외에는 -
|
||||
int GetCurrentMaxSize(void);
|
||||
|
||||
/// @brief set max queue size, it have nothing to do with memory allocation in this class.
|
||||
// please use it for infinity queue size to limit the speed what job processing.
|
||||
/// @param userData [in] set 0 to infinity or positive integer( default: 0)
|
||||
/// @return 성공은 return true, 그 외에는 return false
|
||||
bool SetCurrentMaxSize(int nMaxSize);
|
||||
|
||||
/// @brief 현재 Queue의 Size를 리턴한다.
|
||||
/// @return stl queue의 size 값
|
||||
int GetSize(void);
|
||||
|
||||
private :
|
||||
std::queue <DataClass> m_qData;
|
||||
/// @brief 큐의 최대크기를 설정하는 변수
|
||||
int m_nMaxSize;
|
||||
/// @brief Data에 대한 뮤텍스 변수
|
||||
pthread_mutex_t m_mxData;
|
||||
/// @brief MaxSize에 대한 뮤텍스 변수
|
||||
pthread_mutex_t m_mxMaxSize;
|
||||
}; // ~class CQueue
|
||||
|
||||
// FIXABLE: if u need another type queue, add or remove type
|
||||
//template class CQueue<CFileInfo>;
|
||||
//template class CQueue<CRetryData>;
|
||||
//template class CQueue<CCompleteData>;
|
||||
//template class CQueue<CContentInfo>;
|
||||
//template class CQueue<CCompleteCacheData>;
|
||||
|
||||
#endif //__DATA_QUEUE_H__
|
||||
@@ -0,0 +1,185 @@
|
||||
/***************************************************************************
|
||||
Database Class
|
||||
-----------------------------------------
|
||||
begin : 2010/03/09
|
||||
copyright : (C) 2010 SolutionBox Inc.
|
||||
author : Service 1 Team
|
||||
email : svc1@solbox.com
|
||||
version : 1.0
|
||||
|
||||
CopyRight(C) 2010 SolutionBox Inc. All Rights reserved.
|
||||
Redistribution and use in source and binary forms, with or with out
|
||||
modification, are not permitted in outside of SolutionBox Inc.
|
||||
***************************************************************************/
|
||||
|
||||
#include <string.h>
|
||||
#include <stdlib.h>
|
||||
#include <sstream>
|
||||
#include "Database.h"
|
||||
#include "Logger.h"
|
||||
|
||||
|
||||
DataBase::~DataBase()
|
||||
{
|
||||
if(m_PGconn != NULL) {
|
||||
PgCloseDB();
|
||||
}
|
||||
}
|
||||
|
||||
PGconn *DataBase::PgOpenDB(string &strHost, int Port, string &strDBName, string &strAcct, string &strPasswd, int timeout)
|
||||
{
|
||||
ostringstream conninfo;
|
||||
|
||||
// CHG 2014-10-29 huibong
|
||||
// application_name add to logging RCDB
|
||||
|
||||
conninfo << "host=" << strHost << " port=" << Port << " dbname=" << strDBName <<
|
||||
" user=" << strAcct << " password=" << strPasswd << " connect_timeout=" << timeout <<
|
||||
" application_name=" << PROG_NAME;
|
||||
|
||||
#ifdef _USE_LIBPQ_KEEPALIVE
|
||||
// This option is supported by at least 9.1.2. and Currently supports Linux systems.
|
||||
conninfo <<" keepalives=1";
|
||||
#endif // _USE_LIBPQ_KEEPALIVE
|
||||
|
||||
//m_PGconn = PQsetdbLogin(strHost.c_str(), szPort, NULL, NULL, strDBName.c_str(), strAcct.c_str(), strPasswd.c_str());
|
||||
m_PGconn = PQconnectdb(conninfo.str().c_str());
|
||||
if(PQstatus(m_PGconn) == CONNECTION_BAD) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
return m_PGconn;
|
||||
}
|
||||
|
||||
PGconn *DataBase::PgOpenDB(const char *pszDBName)
|
||||
{
|
||||
m_PGconn = PQsetdb(NULL, NULL, NULL, NULL, pszDBName);
|
||||
if(PQstatus(m_PGconn) == CONNECTION_BAD) {
|
||||
return NULL;
|
||||
}
|
||||
return m_PGconn;
|
||||
}
|
||||
|
||||
void DataBase::PgCloseDB()
|
||||
{
|
||||
if(m_PGconn != NULL)
|
||||
{
|
||||
PQfinish(m_PGconn);
|
||||
m_PGconn = NULL;
|
||||
}
|
||||
}
|
||||
|
||||
int DataBase::PgResult(CFLAG flag)
|
||||
{
|
||||
int fRet = 0;
|
||||
int Result;
|
||||
|
||||
Result = PQresultStatus(m_pRes);
|
||||
switch(Result) {
|
||||
case PGRES_EMPTY_QUERY :
|
||||
fRet = -1;
|
||||
break;
|
||||
case PGRES_BAD_RESPONSE :
|
||||
fRet = -2;
|
||||
break;
|
||||
case PGRES_NONFATAL_ERROR :
|
||||
fRet = -3;
|
||||
break;
|
||||
case PGRES_FATAL_ERROR :
|
||||
fRet = -4;
|
||||
break;
|
||||
case PGRES_TUPLES_OK :
|
||||
fRet = 1;
|
||||
break;
|
||||
case PGRES_COMMAND_OK :
|
||||
fRet = 2;
|
||||
break;
|
||||
}
|
||||
if(fRet < 0) {
|
||||
m_ErrorMessage = PQresultErrorMessage(m_pRes);
|
||||
}
|
||||
m_ResultCode = Result;
|
||||
if(flag == CLEAR && m_pRes) {
|
||||
PQclear(m_pRes);
|
||||
m_pRes = NULL;
|
||||
}
|
||||
return fRet;
|
||||
}
|
||||
|
||||
string &DataBase::GetErrorMessage()
|
||||
{
|
||||
return m_ErrorMessage;
|
||||
}
|
||||
|
||||
int DataBase::GetCmdTuples()
|
||||
{
|
||||
//fprintf(stderr, "DataBase::GetCmdTuples PQcmdTuples %s\n", PQcmdTuples(m_pRes));
|
||||
return (int)atoi(PQcmdTuples(m_pRes));
|
||||
}
|
||||
|
||||
int DataBase::GetNoTuples()
|
||||
{
|
||||
return PQntuples(m_pRes);
|
||||
}
|
||||
|
||||
int DataBase::GetNoFields()
|
||||
{
|
||||
return PQnfields(m_pRes);
|
||||
}
|
||||
|
||||
PGresult *DataBase::GetRes()
|
||||
{
|
||||
return m_pRes;
|
||||
}
|
||||
|
||||
void DataBase::PgClear()
|
||||
{
|
||||
if(m_pRes)
|
||||
{
|
||||
PQclear(m_pRes);
|
||||
m_pRes = NULL;
|
||||
}
|
||||
}
|
||||
|
||||
char *DataBase::GetValue(int tuple, int field)
|
||||
{
|
||||
return PQgetvalue(m_pRes, tuple, field);
|
||||
}
|
||||
|
||||
int DataBase::PgDoExec(char *pszQuery)
|
||||
{
|
||||
return this->PgDoExec(pszQuery, NOT_CLEAR);
|
||||
}
|
||||
|
||||
int DataBase::PgDoExec(string &strQuery)
|
||||
{
|
||||
return this->PgDoExec((char *)strQuery.c_str(), NOT_CLEAR);
|
||||
}
|
||||
|
||||
int DataBase::PgDoExec(char *pszQuery, CFLAG flag)
|
||||
{
|
||||
if(m_PGconn == NULL) return -1;
|
||||
if(PQstatus(m_PGconn) != CONNECTION_OK) return -2;
|
||||
m_pRes = PQexec(m_PGconn, pszQuery);
|
||||
int r = PgResult(flag);
|
||||
return r;
|
||||
}
|
||||
|
||||
int DataBase::PgDoExecParams(char *pszQuery, int nParamCnt, const char * const *paramValues ,CFLAG flag)
|
||||
{
|
||||
if(m_PGconn == NULL) return -1;
|
||||
if(PQstatus(m_PGconn) != CONNECTION_OK) return -2;
|
||||
m_pRes = PQexecParams(m_PGconn, pszQuery, nParamCnt, NULL, paramValues, NULL, NULL, 0);
|
||||
int r = PgResult(flag);
|
||||
return r;
|
||||
|
||||
}
|
||||
|
||||
int DataBase::PgEscapeString(char *to, const char *from, size_t length)
|
||||
{
|
||||
int retval = 0;
|
||||
|
||||
//PQescapeStringConn(m_PGconn, to, from, length, &retval);
|
||||
PQescapeString(to, from, length);
|
||||
return retval;
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
/***************************************************************************
|
||||
Database Class
|
||||
-----------------------------------------
|
||||
begin : 2010/03/11
|
||||
copyright : (C) 2010 SolutionBox Inc.
|
||||
author : Service 1 Team
|
||||
email : svc1@solbox.com
|
||||
version : 1.0
|
||||
|
||||
CopyRight(C) 2010 SolutionBox Inc. All Rights reserved.
|
||||
Redistribution and use in source and binary forms, with or with out
|
||||
modification, are not permitted in outside of SolutionBox Inc.
|
||||
***************************************************************************/
|
||||
#ifndef __DATABASE_H__
|
||||
#define __DATABASE_H__
|
||||
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
|
||||
#include "libpq-fe.h"
|
||||
#define MaxSizeOfDBQuery 1024*9
|
||||
|
||||
using namespace std;
|
||||
class DataBase
|
||||
{
|
||||
public:
|
||||
enum CFLAG { CLEAR = 1, NOT_CLEAR };
|
||||
DataBase() { m_PGconn = NULL; m_pRes = NULL;}
|
||||
~DataBase();
|
||||
PGconn *PgOpenDB(string &strHost, int Port, string &strDBName, string &strAcct, string &strPasswd, int timeout = 10);
|
||||
PGconn *PgOpenDB(const char *pszDBName);
|
||||
void PgCloseDB();
|
||||
int PgResult(CFLAG flag);
|
||||
PGconn *GetPgConn(){ return m_PGconn;}
|
||||
PGresult *GetRes();
|
||||
void SetRes(PGresult * v) {m_pRes = v;}
|
||||
int GetCmdTuples();
|
||||
int GetNoTuples();
|
||||
int GetNoFields();
|
||||
int GetResultCode() { return m_ResultCode; }
|
||||
char *GetValue(int tuple, int field);
|
||||
void PgClear();
|
||||
int PgDoExec(string &strQuery);
|
||||
int PgDoExec(char *pszQuery);
|
||||
int PgDoExec(char *pszQuery, CFLAG flag);
|
||||
int PgDoExecParams(char *pszQuery, int nParamCnt, const char * const *paramValues ,CFLAG flag = NOT_CLEAR);
|
||||
int PgEscapeString(char *to, const char *from, size_t length);
|
||||
string &GetErrorMessage();
|
||||
private:
|
||||
int m_ResultCode;
|
||||
PGconn *m_PGconn;
|
||||
PGresult *m_pRes;
|
||||
string m_ErrorMessage;
|
||||
};
|
||||
|
||||
#endif // ~__DATABASE_H__
|
||||
@@ -0,0 +1,67 @@
|
||||
/***************************************************************************
|
||||
ftsd control interface ( File Replication & Cache & Move & Delete Control) Header ( FtsdProtocol.h )
|
||||
-----------------------------------------
|
||||
begin : 2010/03/09
|
||||
copyright : (C) 2005 SolutionBox Inc.
|
||||
author : Service 1 Team
|
||||
email : svc1@solbox.com
|
||||
version : 3.2.0.R0811
|
||||
|
||||
CopyRight(C) 2005 SolutionBox Inc. All Rights reserved.
|
||||
Redistribution and use in source and binary forms, with or with out
|
||||
modification, are not permitted in outside of SolutionBox Inc.
|
||||
***************************************************************************/
|
||||
|
||||
#ifndef __FTSD_PROTOCOL_H__
|
||||
#define __FTSD_PROTOCOL_H__
|
||||
|
||||
|
||||
struct FileTransferPacketHeader {
|
||||
|
||||
char stx; // Packet 유효성 관리 코드
|
||||
char type; // Request or Response 여부 ( 0x00: Request, 0x01: Response )
|
||||
char command[4]; // Command Code ( 4 Byte) : 0th control-ftsd, 1th ftsd-ftsd 사용.
|
||||
char result[4]; // Result Code ( 4 Byte )
|
||||
unsigned int data_length; // Packet Data 부분의 길이값 ( Network Byte Order 사용)
|
||||
char extend_code[2]; // 확장 및 Padding bits ( 2 Byte )
|
||||
};
|
||||
|
||||
|
||||
// Packet Header stx 코드
|
||||
#define HEADER_STX_CODE 0x02
|
||||
|
||||
// Packet Header type 구분코드
|
||||
#define HEADER_TYPE_REQUEST 0x00
|
||||
#define HEADER_TYPE_RESPONSE 0x01
|
||||
|
||||
|
||||
// Packet command 공통.
|
||||
#define COMMON_ALIVE_CHECK 0x7F
|
||||
|
||||
// Packet command : control 프로세스 <-> ftsd 통신 ( Command 첫번째 Byte 만 사용 )
|
||||
#define NOT_CONTROL_COMMAND 0x00 // Control 이 전송한 요청이 아닌 경우.
|
||||
#define CONTROL_FILE_REPLICATION 0x01 // Content 복제 생성 요청
|
||||
#define CONTROL_FILE_CACHE 0x02 // Content 에 대해 Cache 폴더로 복제 요청
|
||||
|
||||
#define CONTROL_FILE_CHECK 0x03 // Content 에 대한 존재 여부, Size 확인 및 Hash 추출 요청
|
||||
#define CONTROL_FILE_UNLINK 0x04 // Content 에 대한 unlink 처리 요청
|
||||
|
||||
// NEW 2016-05-04 huibong 토토디스크 지원용 기능 추가 (#27460)
|
||||
#define CONTROL_FILE_CHECK_TOTO 0x05 // 토토디스크 고객사 지원을 위한 MD5 Hash 추출 기능 (2016-05-03 추가)
|
||||
|
||||
|
||||
// Packet Result : type이 Reponse 인 경우에만 세팅됨.( 첫번째 Byte 만 사용시 )
|
||||
#define HEADER_RESULT_SUCCESS 0x00
|
||||
#define HEADER_RESULT_ERROR 0x01
|
||||
|
||||
|
||||
// 기타 정보
|
||||
#define LENGTH_FIELD_SIZE 4 // 가변데이터 형식 사용시 Length 필드의 메모리 크기 (unsigned int)
|
||||
|
||||
|
||||
// unlink 요청시 Mode 설정 정보
|
||||
#define UNLINK_MODE_NORMAL 0 // 해당 Content 가 존재하고 size 값이 정확한 경우에만 삭제, 나머지는 오류
|
||||
#define UNLINK_MODE_FORCE 1 // 해당 Content 가 존재하지 않거나.. Size 값이 틀려도 강제로 삭제 처리.. 오류로 처리되는 상황은 통신, 시스템 오류 발생시.
|
||||
|
||||
|
||||
#endif /* __FTSD_PROTOCOL_H__ */
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,304 @@
|
||||
/***************************************************************************
|
||||
ftsd control interface ( File Replication & Cache & Move & Delete Control) Header ( FtsdSocketControl.h )
|
||||
-----------------------------------------
|
||||
begin : 2010/03/09
|
||||
copyright : (C) 2005 SolutionBox Inc.
|
||||
author : Service 1 Team
|
||||
email : svc1@solbox.com
|
||||
version : 3.2.0.R0811
|
||||
|
||||
CopyRight(C) 2005 SolutionBox Inc. All Rights reserved.
|
||||
Redistribution and use in source and binary forms, with or with out
|
||||
modification, are not permitted in outside of SolutionBox Inc.
|
||||
***************************************************************************/
|
||||
|
||||
#ifndef __FTSD_SOCKET_CONTROL_H__
|
||||
#define __FTSD_SOCKET_CONTROL_H__
|
||||
|
||||
#include "BaseSocket.h"
|
||||
#include "FtsdProtocol.h"
|
||||
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
#include <map>
|
||||
|
||||
|
||||
///< BYTE 타입 정의
|
||||
#ifndef _BYTE_DEFINED
|
||||
#define _BYTE_DEFINED
|
||||
typedef unsigned char BYTE;
|
||||
#endif // _BYTE_DEFINED
|
||||
|
||||
|
||||
#define DEFAULT_SOCKET_TEMP_BUFFER_SIZE 1024 // SocketControl 에서 사용할 임시버퍼 크기.
|
||||
|
||||
class CFtsdSocketControl : public CBaseSocket
|
||||
{
|
||||
private:
|
||||
|
||||
/// @brief Packet Header 변수
|
||||
struct FileTransferPacketHeader m_packetHeader;
|
||||
|
||||
/// @brief m_packetHeader 구조체의 크기를 저장하기 위한 상수
|
||||
const int m_nPacketHeaderLen;
|
||||
|
||||
/// @brief Packet Header 에 저장된 Data 부분의 길이 정보값.
|
||||
unsigned int m_nPacketDataLen;
|
||||
|
||||
/// @brief Packet Data 부분의 수신처리시 임시로 사용할 버퍼.
|
||||
BYTE m_tempBuffer[DEFAULT_SOCKET_TEMP_BUFFER_SIZE];
|
||||
|
||||
|
||||
public:
|
||||
|
||||
/// @brief 생성자.
|
||||
CFtsdSocketControl();
|
||||
|
||||
/// @brief 소멸자.
|
||||
~CFtsdSocketControl();
|
||||
|
||||
|
||||
/// @brief 전달받은 Target 으로 Socket 접속을 수행
|
||||
/// @param szTarget [in] 접속 대상 Host name 또는 IP
|
||||
/// @param nPort [in] 접속 Port
|
||||
/// @return 접속 성공시 true, 실패시 false 반환. ( 오류 내역은 로깅처리됨.)
|
||||
bool ConnectTarget( const std::string& szTarget, int nPort );
|
||||
|
||||
|
||||
/// @brief 대상과 연결된 Socket 을 통해 ftsd 로 File Replication 명령 전송.
|
||||
/// @param szFileName [in] 복제할 원본 Source 파일명 (/stg/node0/186/abcde..)
|
||||
/// @param nFileSize [in] 복제할 원본 Source 파일의 크기.
|
||||
/// @param szTargetTranId [in] RC 간 복제 처리시 변경할 대상 Tran ID 정보 값.
|
||||
/// @param nFileHashCheckLevel [in] File 에 대한 Hash Check Level 정보 ( conf 파일에 지정됨)
|
||||
/// @param bUseInternalIp [in] 내부망을 이용하여 파일 송수신을 수행할지 여부 \n
|
||||
///< 해당값을 true 로 지정시 ftsd 상에서 내부망을 우선 사용하여 파일 복제 시도
|
||||
///< 만약 내부망 사용 불가시 자동으로 외부망 사용.
|
||||
///< RC-RC 간 처리시에는 사용하지 않도록 false 로 지정할 것.
|
||||
/// @param vecTargetFhs [in] 복제 대상 Target FHS Host Name 정보
|
||||
/// @return Replication 복제 요청 메시지 전송 성공시 true, 실패시 false 반환.
|
||||
bool SendFileReplicationRequest(const std::string& szFileName, unsigned long long nFileSize, int nFileHashCheckLevel, bool bUseInternalIp, std::vector< std::string >& vecTargetFhs);
|
||||
bool SendFileReplicationRequest(const std::string& szFileName, unsigned long long nFileSize, const std::string& szTargetTranId, int nFileHashCheckLevel, bool bUseInternalIp, std::vector< std::string >& vecTargetFhs);
|
||||
|
||||
|
||||
/// @brief File Replication 요청에 대한 처리 결과를 ftsd 로 부터 수신한다.
|
||||
/// @param nTimeout [in] 함수 호출에 대한 Blocking 을 방지하기 위한 Timeout 설정값. 단위( second )\n
|
||||
///< 지정된 시간동안 응답을 수신하지 못한 경우 0 을 반환.
|
||||
/// @param bSuccess [out] File Replication 이 정상적으로 수행되었는지 여부 \n
|
||||
///< trnsfer 상에서 오류가 발생한 경우 이 값은 false 가 되며 \n
|
||||
///< szErrorMessage 변수상에 오류내용이 저장됨. \n
|
||||
///< 정상적으로 처리된 경우 true 가 저장되며 \n
|
||||
///< mapSuccessFhs, mapFailFhs 상에 관련 정보가 저장됨.
|
||||
/// @param szErrorMessage [out] bSuccess == false 인 경우 발생된 오류메시지 정보를 저장
|
||||
/// @param mapSuccessFhs [out] bSuccess == true 인 경우 \n
|
||||
///< Replication 처리에 성공한 FHS 및 저장된 File 이름 정보를 저장
|
||||
/// @param mapFailFhs [out] bSuccess == true 인 경우 \n
|
||||
///< Replication 처리에 실패한 FHS Host Name 및 발생된 오류메시지 정보를 저장.
|
||||
///
|
||||
/// @return -1 : Socket 통신 관련 오류 발생하여 ftsd 와 연결이 끊어진 경우 \n
|
||||
///< => ftsd 와 연결이 끝어진것으로 판단하고 오류처리한다. \n
|
||||
///<
|
||||
///< 0 : 입력변수인 nTimeout 에 지정된 시간안에 ftsd 로부터
|
||||
///< Replication 에 대한 처리 결과 정보를 수신하지 못한 경우. \n
|
||||
///< 이 기능은 본 함수 호출시 Blocking 발생을 막기 위한 기능으로서 \n
|
||||
///< 이 값이 반환된 경우 추가 다른 작업을 진행한 후 본 함수를 다시 호출하여 \n
|
||||
///< 응답을 대기할 수 있다. \n
|
||||
///<
|
||||
///< 1 : 파일 복제 처리에 대한 응답을 수신한 경우, Output 인자인 bSuccess 를 확인하여 처리 결과 확인
|
||||
///<
|
||||
///< 2 : ftsd 로 부터 Data 을 수신하였으나 File Replication 요청에 대한 응답이 아닌 경우 \n
|
||||
///< 해당 정보는 본 클래스의 멤버변수 상에 내부적으로 저장된다. ( 단 Alive Packet 은 아님) \n
|
||||
///< 본 결과가 수신된 경우 무시 처리하고 계속 응답을 대기하면 된다.
|
||||
int GetFileReplicationResult( int nTimeout, bool& bSuccess, std::string& szErrorMessage, std::map< std::string, std::string>& mapSuccessFhs, std::map< std::string, std::string>& mapFailFhs );
|
||||
|
||||
|
||||
/// @brief 대상과 연결된 Socket 을 통해 ftsd 로 File Cache 명령 전송.
|
||||
/// @param szFileName [in] Cache 처리할 원본 Source 파일명 (/stg/node0/186/abcde..)
|
||||
/// @param nFileSize [in] Cache 처리할 원본 Source 파일의 크기.
|
||||
/// @param nFileHashCheckLevel [in] File 에 대한 Hash Check Level 정보 ( conf 파일에 지정됨)
|
||||
/// @param bUseInternalIp [in] 내부망을 이용하여 파일 송수신을 수행할지 여부 \n
|
||||
///< 해당값을 true 로 지정시 ftsd 상에서 내부망을 우선 사용하여 파일 복제 시도
|
||||
///< 만약 내부망 사용 불가시 자동으로 외부망 사용.
|
||||
/// @param vecTargetFhs [in] Cache 대상 Target FHS Host Name 정보
|
||||
/// @return Cache 요청 메시지 전송 성공시 true, 실패시 false 반환.
|
||||
bool SendFileCacheRequest(const std::string& szFileName, unsigned long long nFileSize, int nFileHashCheckLevel, bool bUseInternalIp, std::vector< std::string >& vecTargetFhs);
|
||||
|
||||
|
||||
/// @brief File Cache 요청에 대한 처리 결과를 ftsd 로 부터 수신한다.
|
||||
/// @param nTimeout [in] 함수 호출에 대한 Blocking 을 방지하기 위한 Timeout 설정값. 단위( second )\n
|
||||
///< 지정된 시간동안 응답을 수신하지 못한 경우 0 을 반환.
|
||||
/// @param bSuccess [out] File Cache 처리가 정상적으로 수행되었는지 여부 \n
|
||||
///< trnsfer 상에서 오류가 발생한 경우 이 값은 false 가 되며 \n
|
||||
///< szErrorMessage 변수상에 오류내용이 저장됨. \n
|
||||
///< 정상적으로 처리된 경우 true 가 저장되며 \n
|
||||
///< mapSuccessFhs, mapFailFhs 상에 관련 정보가 저장됨.
|
||||
/// @param szErrorMessage [out] bSuccess == false 인 경우 발생된 오류메시지 정보를 저장
|
||||
/// @param mapSuccessFhs [out] bSuccess == true 인 경우 \n
|
||||
///< Cache 처리에 성공한 FHS 및 저장된 File 이름 정보를 저장
|
||||
/// @param mapFailFhs [out] bSuccess == true 인 경우 \n
|
||||
///< Cache 처리에 실패한 FHS Host Name 및 발생된 오류메시지 정보를 저장.
|
||||
///
|
||||
/// @return -1 : Socket 통신 관련 오류 발생하여 ftsd 와 연결이 끊어진 경우 \n
|
||||
///< => ftsd 와 연결이 끝어진것으로 판단하고 오류처리한다. \n
|
||||
///<
|
||||
///< 0 : 입력변수인 nTimeout 에 지정된 시간안에 ftsd 로부터
|
||||
///< Cache 에 대한 처리 결과 정보를 수신하지 못한 경우. \n
|
||||
///< 이 기능은 본 함수 호출시 Blocking 발생을 막기 위한 기능으로서 \n
|
||||
///< 이 값이 반환된 경우 추가 다른 작업을 진행한 후 본 함수를 다시 호출하여 \n
|
||||
///< 응답을 대기할 수 있다. \n
|
||||
///<
|
||||
///< 1 : 파일 Cache 처리에 대한 응답을 수신한 경우, Output 인자인 bSuccess 를 확인하여 처리 결과 확인
|
||||
///<
|
||||
///< 2 : ftsd 로 부터 Data 을 수신하였으나 File Cache 요청에 대한 응답이 아닌 경우 \n
|
||||
///< 해당 정보는 본 클래스의 멤버변수 상에 내부적으로 저장된다. ( 단 Alive Packet 은 아님) \n
|
||||
///< 본 결과가 수신된 경우 무시 처리하고 계속 응답을 대기하면 된다.
|
||||
int GetFileCacheResult( int nTimeout, bool& bSuccess, std::string& szErrorMessage, std::map< std::string, std::string>& mapSuccessFhs, std::map< std::string, std::string>& mapFailFhs );
|
||||
|
||||
|
||||
/// @brief 대상과 연결된 Socket 을 통해 ftsd 로 Content Check 명령 전송.
|
||||
/// @param szFileName [in] 원본 Source 파일명 (/stg/node0/186/abcde..)
|
||||
/// @param bHashCheck [in] Hash 값을 추출할지 여부
|
||||
/// @param nHashCheckSize [in] Hash 값을 추출할 경우 Size 설정값 ( MByte 단위 )\n
|
||||
///< 0 : Content 에 대한 전체 Hash 값을 추출함.
|
||||
///< 숫자 : Content 의 앞 부분부터 지정된 크기 (MByte ) 까지 Hash 값을 추출
|
||||
/// @return Check 요청 메시지 전송 성공시 true, 실패시 false 반환.
|
||||
bool SendFileCheckRequest(const std::string& szFileName, bool bHashCheck, unsigned long long nHashCheckSize );
|
||||
|
||||
|
||||
|
||||
/// @brief File Check 요청에 대한 처리 결과를 ftsd 로 부터 수신한다.
|
||||
/// @param nTimeout [in] 함수 호출에 대한 Blocking 을 방지하기 위한 Timeout 설정값. 단위( second )\n
|
||||
///< 지정된 시간동안 응답을 수신하지 못한 경우 0 을 반환.
|
||||
/// @param bSuccess [out] File Check 처리가 정상적으로 수행되었는지 여부 \n
|
||||
///< ftsd 상에서 오류가 발생한 경우 이 값은 false 가 되며 \n
|
||||
///< szErrorMessage 변수상에 오류내용이 저장됨. \n
|
||||
///< 정상적으로 처리된 경우 true 가 저장되며 \n
|
||||
///< nFileSize, szHashValue 상에 결과 정보가 저장됨.
|
||||
/// @param szErrorMessage [out] bSuccess == false 인 경우 발생된 오류메시지 정보를 저장
|
||||
/// @param nFileSize [out] bSuccess == true 인 경우 요청한 Content 에 대한 file size 정보를 저장. ( Byte 단위 )
|
||||
/// @param szHashValue [out] bSuccess == true 이고... Hash 값 추출을 요청한 경우 추출된 Hash 값 정보를 저장.
|
||||
/// @return -1 : Socket 통신 관련 오류 발생하여 ftsd 와 연결이 끊어진 경우 \n
|
||||
///< => ftsd 와 연결이 끝어진것으로 판단하고 오류처리한다. \n
|
||||
///<
|
||||
///< 0 : 입력변수인 nTimeout 에 지정된 시간안에 ftsd 으로부터 처리 결과 정보를 수신하지 못한 경우. \n
|
||||
///< 이 기능은 본 함수 호출시 Blocking 발생을 막기 위한 기능으로서 \n
|
||||
///< 이 값이 반환된 경우 추가 다른 작업을 진행한 후 본 함수를 다시 호출하여 \n
|
||||
///< 응답을 대기할 수 있다. \n
|
||||
///<
|
||||
///< 1 : 파일 Check 처리에 대한 응답을 수신한 경우, Output 인자인 bSuccess 를 확인하여 처리 결과 확인
|
||||
///<
|
||||
///< 2 : ftsd 으로 부터 Data 을 수신하였으나 File Check 요청에 대한 응답이 아닌 경우 \n
|
||||
///< 해당 정보는 본 클래스의 멤버변수 상에 내부적으로 저장된다. ( 단 Alive Packet 은 아님) \n
|
||||
///< 본 결과가 수신된 경우 무시 처리하고 계속 응답을 대기하면 된다.
|
||||
int GetFileCheckResult( int nTimeout, bool& bSuccess, std::string& szErrorMessage, unsigned long long& nFileSize, std::string& szHashValue );
|
||||
|
||||
|
||||
/// @brief 대상과 연결된 Socket 을 통해 ftsd 로 Unlink 명령 전송.
|
||||
/// @param szFileName [in] 원본 Source 파일명 (/stg/node0/186/abcde..)
|
||||
/// @param nFileSize [in] 원본 파일의 크기 ( Byte 단위 )
|
||||
/// @param bForceUnlink [in] 강제 삭제 처리 여부 ( Defalult false )
|
||||
/// false : 일반모드 - 해당 파일이 존재하고 Size 값이 동일할 경우에만 삭제처리.. 나머지는 오류로 처리.
|
||||
/// true : 강제모드 - 해당 파일이 존재하지 않거나.. Size 가 틀려도 강제로 삭제 처리.. 오류는 통신, 시스템 오류 발생시에만
|
||||
/// @return Unlink 요청 메시지 전송 성공시 true, 실패시 false 반환.
|
||||
bool SendFileUnlinkRequest(const std::string& szFileName, unsigned long long nFileSize, bool bForceUnlink = false );
|
||||
|
||||
/// @brief File Unlink 요청에 대한 처리 결과를 ftsd 로 부터 수신한다.
|
||||
/// @param nTimeout [in] 함수 호출에 대한 Blocking 을 방지하기 위한 Timeout 설정값. 단위( second )\n
|
||||
///< 지정된 시간동안 응답을 수신하지 못한 경우 0 을 반환.
|
||||
/// @param bSuccess [out] File unlink 처리가 정상적으로 수행되었는지 여부 \n
|
||||
///< ftsd 상에서 오류가 발생한 경우 이 값은 false 가 되며 \n
|
||||
///< szErrorMessage 변수상에 오류내용이 저장됨. \n
|
||||
///< 정상적으로 처리된 경우 true 가 저장되며 따로 수신하는 Data 는 없음. \n
|
||||
/// @param szErrorMessage [out] bSuccess == false 인 경우 발생된 오류메시지 정보를 저장
|
||||
/// @return -1 : Socket 통신 관련 오류 발생하여 ftsd 와 연결이 끊어진 경우 \n
|
||||
///< => ftsd 와 연결이 끝어진것으로 판단하고 오류처리한다. \n
|
||||
///<
|
||||
///< 0 : 입력변수인 nTimeout 에 지정된 시간안에 ftsd 으로부터 처리 결과 정보를 수신하지 못한 경우. \n
|
||||
///< 이 기능은 본 함수 호출시 Blocking 발생을 막기 위한 기능으로서 \n
|
||||
///< 이 값이 반환된 경우 추가 다른 작업을 진행한 후 본 함수를 다시 호출하여 \n
|
||||
///< 응답을 대기할 수 있다. \n
|
||||
///<
|
||||
///< 1 : 파일 Unlink 처리에 대한 응답을 수신한 경우, Output 인자인 bSuccess 를 확인하여 처리 결과 확인
|
||||
///<
|
||||
///< 2 : ftsd 으로 부터 Data 을 수신하였으나 File Unlink 요청에 대한 응답이 아닌 경우 \n
|
||||
///< 해당 정보는 본 클래스의 멤버변수 상에 내부적으로 저장된다. ( 단 Alive Packet 은 아님) \n
|
||||
///< 본 결과가 수신된 경우 무시 처리하고 계속 응답을 대기하면 된다.
|
||||
int GetFileUnlinkResult( int nTimeout, bool& bSuccess, std::string& szErrorMessage );
|
||||
|
||||
|
||||
// NEW 2016-05-04 huibong 토토디스크 지원용 기능 추가 (#27460)
|
||||
/// @brief 대상과 연결된 Socket 을 통해 ftsd 로 Content Check 명령 전송. (토토디스크 지원용)
|
||||
/// @param szFileName [in] 원본 Source 파일명 (/stg/node0/186/abcde..)
|
||||
/// @return Check 요청 메시지 전송 성공시 true, 실패시 false 반환.
|
||||
bool SendFileCheckTOTORequest( const std::string& szFileName );
|
||||
|
||||
|
||||
// NEW 2016-05-04 huibong 토토디스크 지원용 기능 추가 (#27460, #27533)
|
||||
/// @brief File Check 요청에 대한 처리 결과를 ftsd 로 부터 수신한다.
|
||||
/// @param nTimeout [in] 함수 호출에 대한 Blocking 을 방지하기 위한 Timeout 설정값. 단위( second )\n
|
||||
///< 지정된 시간동안 응답을 수신하지 못한 경우 0 을 반환.
|
||||
/// @param bSuccess [out] File Check 처리가 정상적으로 수행되었는지 여부 \n
|
||||
///< ftsd 상에서 오류가 발생한 경우 이 값은 false 가 되며 \n
|
||||
///< szErrorMessage 변수상에 오류내용이 저장됨. \n
|
||||
///< 정상적으로 처리된 경우 true 가 저장되며 \n
|
||||
///< nFileSize, szHashValue 상에 결과 정보가 저장됨.
|
||||
/// @param szErrorMessage [out] bSuccess == false 인 경우 발생된 오류메시지 정보를 저장
|
||||
/// @param nFileSize [out] bSuccess == true 인 경우 요청한 Content 에 대한 file size 정보를 저장. ( Byte 단위 )
|
||||
/// @param szTotoMd5 [out] bSuccess == true 인 경우 추출된 totorasa 용 MD5 Hash 값 정보를 저장.
|
||||
/// @param szChecksum [out] bSuccess == true 인 경우 추출된 totorasa 용 Checksum 정보를 저장.
|
||||
/// @param szDnaCheckKey [out] bSuccess == true 인 경우 추출된 totorasa 용 DNA Check key 값 정보를 저장.
|
||||
/// @return -1 : Socket 통신 관련 오류 발생하여 ftsd 와 연결이 끊어진 경우 \n
|
||||
///< => ftsd 와 연결이 끝어진것으로 판단하고 오류처리한다. \n
|
||||
///<
|
||||
///< 0 : 입력변수인 nTimeout 에 지정된 시간안에 ftsd 으로부터 처리 결과 정보를 수신하지 못한 경우. \n
|
||||
///< 이 기능은 본 함수 호출시 Blocking 발생을 막기 위한 기능으로서 \n
|
||||
///< 이 값이 반환된 경우 추가 다른 작업을 진행한 후 본 함수를 다시 호출하여 \n
|
||||
///< 응답을 대기할 수 있다. \n
|
||||
///<
|
||||
///< 1 : 파일 Check 처리에 대한 응답을 수신한 경우, Output 인자인 bSuccess 를 확인하여 처리 결과 확인
|
||||
///<
|
||||
///< 2 : ftsd 으로 부터 Data 을 수신하였으나 File Check 요청에 대한 응답이 아닌 경우 \n
|
||||
///< 해당 정보는 본 클래스의 멤버변수 상에 내부적으로 저장된다. ( 단 Alive Packet 은 아님) \n
|
||||
///< 본 결과가 수신된 경우 무시 처리하고 계속 응답을 대기하면 된다.
|
||||
int GetFileCheckTOTOResult( int nTimeout, bool& bSuccess, std::string& szErrorMessage
|
||||
, unsigned long long& nFileSize, std::string& szTotoMd5, std::string& szChecksum, std::string& szDnaCheckKey );
|
||||
|
||||
|
||||
|
||||
/// @brief 연결된 Socket 통신을 이용하여 내부적으로 정의된 Alive Check 패킷 전송 \n
|
||||
///< => 해당 패킷에 대한 처리는 내부적으로 처리되어 결과값을 확인할 필요는 없다.
|
||||
/// @return Socket 연결 해제 또는 전송 관련 오류 발생시 false, 전송 성공시에는 true 반환.
|
||||
bool SendAliveCheck(void);
|
||||
|
||||
/// @brief Packet Header 정보를 Log 파일에 Logging 처리 ( Debug 처리를 위한 함수)
|
||||
void PrintHeaderToLog(void);
|
||||
|
||||
|
||||
protected:
|
||||
|
||||
/// @brief Packet Header 부분의 수신 처리를 위한 함수. Alive Check 요청 패킷은 자동으로 무시처리함.
|
||||
/// @param timeout [in] 대기시간.
|
||||
/// @retrun 성공시 true, 오류 발생및 실패시 fasle 반환.
|
||||
bool GetPacketHeader(int timeout = DEFAULT_DATA_RECEIVE_TIMEOUT);
|
||||
|
||||
/// @brief socket 에서 지정된 크기만큼의 데이터를 읽어 출력변수에 저장처리.
|
||||
/// @param size [in] read 할 데이터 크기
|
||||
/// @param value [out] 읽은 데이터를 저장할 string 변수
|
||||
/// @return On success return true, otherwise return false.
|
||||
bool GetPacketData( unsigned int& size, std::string& value );
|
||||
|
||||
/// @brief socket 에서 지정된 크기만큼의 데이터를 읽어 내부 임시버퍼인 m_tempBuffer 에 저장처리.
|
||||
/// @param size [in] read 할 데이터 크기
|
||||
/// @return On success return true, otherwise return false.
|
||||
bool GetPacketData( unsigned int size );
|
||||
|
||||
/// @brief pValue 에 저장된 데이터를 unsigned int 형으로 변환처리 및 Endian 변환
|
||||
unsigned int GetDataToUInt( BYTE * pValue, bool bConvertEndian = true );
|
||||
|
||||
/// @brief pValue 에 저장된 데이터를 unsigned long long (64Byte) 형으로 변환처리.
|
||||
unsigned long long GetDataToUInt64( BYTE * pValue );
|
||||
|
||||
|
||||
};
|
||||
|
||||
#endif /* __FTSD_SOCKET_CONTROL_H__ */
|
||||
|
||||
@@ -0,0 +1,214 @@
|
||||
#include "Config.h"
|
||||
#include "GcmdConfig.h"
|
||||
#include "ProcessStatus.h"
|
||||
#include <string.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
|
||||
#define DEFAULT_MAX_THREAD 100
|
||||
|
||||
using namespace std;
|
||||
|
||||
CGcmdConfig::CGcmdConfig( std::string szFilename, std::string szProgramName, std::string szProgramVersion )
|
||||
{
|
||||
m_szConfigFile = szFilename;
|
||||
m_szProgramName = szProgramName;
|
||||
m_szProgramVersion = szProgramVersion;
|
||||
m_szErrMessage = "";
|
||||
|
||||
/// COMMON Section
|
||||
m_szAppLogRoot = "";
|
||||
m_nLogLevel = 0;
|
||||
// end..
|
||||
|
||||
m_nMaxDeleteThread = 0;
|
||||
}
|
||||
|
||||
CGcmdConfig::~CGcmdConfig()
|
||||
{
|
||||
}
|
||||
|
||||
bool CGcmdConfig::LoadConfig()
|
||||
{
|
||||
string szValue;
|
||||
std::vector< std::string > vecValue;
|
||||
|
||||
/// Config 처리를 위한 객체 생성
|
||||
Config conf;
|
||||
|
||||
/// Config File open
|
||||
if( conf.Open( m_szConfigFile ) == false )
|
||||
{
|
||||
m_szErrMessage = "Config file open failed.[" + m_szConfigFile + "]";
|
||||
return false;
|
||||
}
|
||||
|
||||
// [COMMON] - RCDB_IP(multi string value)
|
||||
szValue.clear();
|
||||
if( conf.GetConfig( "COMMON", "RCDB_IP", szValue ) == false )
|
||||
{
|
||||
m_szErrMessage = "Config info get failed. [COMMON]->RCDB_IP";
|
||||
return false;
|
||||
}
|
||||
m_szRcdbIp = szValue;
|
||||
|
||||
// [COMMON] - RCDB_PORT (int)
|
||||
szValue.clear();
|
||||
if( conf.GetConfig( "COMMON", "RCDB_PORT", szValue ) == false )
|
||||
{
|
||||
m_szErrMessage = "Config info get failed. [COMMON]->RCDB_PORT";
|
||||
return false;
|
||||
}
|
||||
|
||||
m_nRcdbPort = atoi(szValue.c_str());
|
||||
// [COMMON] - RCDB_DB_NAME (string)
|
||||
szValue.clear();
|
||||
if( conf.GetConfig( "COMMON", "RCDB_DB_NAME", szValue ) == false )
|
||||
{
|
||||
m_szErrMessage = "Config info get failed. [COMMON]->RCDB_DB_NAME";
|
||||
return false;
|
||||
}
|
||||
m_szRcdbName = szValue;
|
||||
|
||||
// [COMMON] - RCDB_ACCT (string)
|
||||
szValue.clear();
|
||||
if( conf.GetConfig( "COMMON", "RCDB_ACCT", szValue ) == false )
|
||||
{
|
||||
m_szErrMessage = "Config info get failed. [COMMON]->RCDB_ACCT";
|
||||
return false;
|
||||
}
|
||||
m_szRcdbAcct = szValue;
|
||||
|
||||
// [COMMON] - RCDB_ACCT_PW (string)
|
||||
szValue.clear();
|
||||
if( conf.GetConfig( "COMMON", "RCDB_ACCT_PW", szValue ) == false )
|
||||
{
|
||||
m_szErrMessage = "Config info get failed. [COMMON]->RCDB_ACCT_PW";
|
||||
return false;
|
||||
}
|
||||
m_szRcdbAcctPw = szValue;
|
||||
|
||||
|
||||
|
||||
/// log path
|
||||
szValue.clear();
|
||||
if( conf.GetConfig( "rc_gcmd", "DEFAULT_LOG_DIR", szValue ) == false )
|
||||
{
|
||||
if( conf.GetConfig( "COMMON", "DEFAULT_LOG_DIR", szValue ) == false )
|
||||
{
|
||||
m_szErrMessage = "Config info get failed. [" + m_szProgramName + "]->LOG_DIR";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
m_szAppLogRoot = szValue;
|
||||
|
||||
// log level
|
||||
szValue.clear();
|
||||
if( conf.GetConfig( "rc_gcmd", "LOG_LEVEL", szValue ) == false )
|
||||
{
|
||||
if( conf.GetConfig( "COMMON", "LOG_LEVEL", szValue ) == false )
|
||||
{
|
||||
m_szErrMessage = "Config info get failed. [" + m_szProgramName + "]->LOG_LEVEL";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
m_nLogLevel = atoi( szValue.c_str() );
|
||||
|
||||
// max delete thread
|
||||
szValue.clear();
|
||||
if( conf.GetConfig( "rc_gcmd", "MAX_DELETE_THREAD", szValue ) == false )
|
||||
{
|
||||
m_szErrMessage = "Config info get failed. [" + m_szProgramName + "]->MAX_DELETE_THREAD";
|
||||
return false;
|
||||
}
|
||||
m_nMaxDeleteThread = atoi( szValue.c_str() );
|
||||
|
||||
if ( CheckConfig() == false )
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
/// 싱클톤 객체인 Process Satatus에 값을 저장해 둔다.
|
||||
// common section configure values
|
||||
CProcessStatus::GetInstance()->SetProgramName(m_szProgramName);
|
||||
CProcessStatus::GetInstance()->SetProgramVersion(m_szProgramVersion);
|
||||
CProcessStatus::GetInstance()->SetLogLevel(m_nLogLevel);
|
||||
CProcessStatus::GetInstance()->SetAppLogRoot(m_szAppLogRoot);
|
||||
|
||||
CProcessStatus::GetInstance()->SetRcdbIp(m_szRcdbIp);
|
||||
CProcessStatus::GetInstance()->SetRcdbPort(m_nRcdbPort);
|
||||
CProcessStatus::GetInstance()->SetRcdbName(m_szRcdbName);
|
||||
CProcessStatus::GetInstance()->SetRcdbAcct(m_szRcdbAcct);
|
||||
CProcessStatus::GetInstance()->SetRcdbAcctPw(m_szRcdbAcctPw);
|
||||
CProcessStatus::GetInstance()->SetMaxDeleteThread(m_nMaxDeleteThread);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CGcmdConfig::CheckConfig()
|
||||
{
|
||||
if( m_szRcdbIp.empty() )
|
||||
{
|
||||
m_szErrMessage = "[COMMON]->RCDB_IP is empty.";
|
||||
return false;
|
||||
}
|
||||
|
||||
if ( m_nRcdbPort <= 0 )
|
||||
{
|
||||
m_szErrMessage = "Config value not valid.[COMMON]->RCDB_PORT = [";
|
||||
m_szErrMessage += m_nRcdbPort;
|
||||
m_szErrMessage += "]";
|
||||
return false;
|
||||
}
|
||||
|
||||
if( m_szRcdbName.empty() )
|
||||
{
|
||||
m_szErrMessage = "[COMMON]->RCDB_DB_NAME is empty.";
|
||||
return false;
|
||||
}
|
||||
if( m_szRcdbAcct.empty() )
|
||||
{
|
||||
m_szErrMessage = "[COMMON]->RCDB_ACCT is empty.";
|
||||
return false;
|
||||
}
|
||||
if( m_szRcdbAcctPw.empty() )
|
||||
{
|
||||
m_szErrMessage = "[COMMON]->RCDB_ACCT_PW is empty.";
|
||||
return false;
|
||||
}
|
||||
|
||||
if ( m_nMaxDeleteThread <= 0 )
|
||||
{
|
||||
m_szErrMessage = "Config info get failed. [" + m_szProgramName + "]->MAX_DELETE_THREAD";
|
||||
m_szErrMessage += m_nMaxDeleteThread;
|
||||
m_szErrMessage += "]";
|
||||
return false;
|
||||
}
|
||||
if ( m_nMaxDeleteThread > DEFAULT_MAX_THREAD )
|
||||
{
|
||||
m_nMaxDeleteThread = DEFAULT_MAX_THREAD;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CGcmdConfig::CheckVector(std::vector< std::string > vecValue)
|
||||
{
|
||||
// Multi value 이므로 갯수 검사
|
||||
if( vecValue.size() <= 0 )
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// 각 데이터별 유효성 여부 검사.
|
||||
std::vector< std::string >::const_iterator it;
|
||||
for( it = vecValue.begin(); it != vecValue.end(); it++ )
|
||||
{
|
||||
if( it->size() <= 0 )
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
/***************************************************************************
|
||||
GcmdConfig.h
|
||||
-----------------------------------------
|
||||
begin : 2012/10/12
|
||||
copyright : (C) 2005 SolutionBox Inc.
|
||||
author : Service 1 Team
|
||||
email : svc1@solbox.com
|
||||
version : 1.0
|
||||
|
||||
CopyRight(C) 2005 SolutionBox Inc. All Rights reserved.
|
||||
Redistribution and use in source and binary forms, with or with out
|
||||
modification, are not permitted in outside of SolutionBox Inc.
|
||||
***************************************************************************/
|
||||
|
||||
#ifndef __RC_GCMD_CONFIG_H__
|
||||
#define __RC_GCMD_CONFIG_H__
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
class CGcmdConfig
|
||||
{
|
||||
// fuctions
|
||||
public:
|
||||
CGcmdConfig( std::string szFilename, std::string szProgramName, std::string szProgramVersion );
|
||||
~CGcmdConfig();
|
||||
/// @brief 설정 파일로부터 데이터를 읽어와서 해당 변수에 저장한다.
|
||||
bool LoadConfig();
|
||||
|
||||
/// @brief 설정 파일로부터 데이터를 읽어 들이다가 에러가 발생한 경우 에러 메시지를 반환 한다.
|
||||
std::string GetErrorMessage() { return m_szErrMessage; };
|
||||
|
||||
private:
|
||||
bool CheckConfig();
|
||||
bool CheckVector(std::vector< std::string > vecValue);
|
||||
|
||||
|
||||
// Attributes
|
||||
private:
|
||||
// gcmd section configure values
|
||||
// - for this class
|
||||
|
||||
std::string m_szConfigFile;
|
||||
std::string m_szProgramName;
|
||||
std::string m_szProgramVersion;
|
||||
std::string m_szErrMessage;
|
||||
|
||||
// common section configure values
|
||||
std::string m_szRcdbIp;
|
||||
int m_nRcdbPort;
|
||||
std::string m_szRcdbName;
|
||||
std::string m_szRcdbAcct;
|
||||
std::string m_szRcdbAcctPw;
|
||||
std::string m_szRcid;
|
||||
|
||||
int m_nMaxDeleteThread;
|
||||
|
||||
// - for log
|
||||
std::string m_szAppLogRoot;
|
||||
int m_nLogLevel;
|
||||
};
|
||||
|
||||
#endif // __RC_GCMD_CONFIG_H__
|
||||
@@ -0,0 +1,500 @@
|
||||
#include "GetContentListThread.h"
|
||||
|
||||
#include <unistd.h>
|
||||
#include <string.h>
|
||||
#include <errno.h>
|
||||
#include <limits.h>
|
||||
#include <sys/time.h>
|
||||
|
||||
using namespace std;
|
||||
|
||||
|
||||
|
||||
#define DB_INFORMATION_UPDATE_INTERVAL 300 // sec
|
||||
//#define DB_INFORMATION_UPDATE_INTERVAL 1 // sec
|
||||
#define DEFAULT_QUERY_BUFFER_SIZE 1024
|
||||
|
||||
#define GET_LAST_BOUNDARY_DAY 15 // Day
|
||||
#define USEC_PER_SEC (1000000LL)
|
||||
#define USEC_PER_DAY (24L*60L*60L*USEC_PER_SEC)
|
||||
#define QUERY_LIMIT_COUNT 2000
|
||||
|
||||
/// @brief 현재 시간 정보를 micro-second 단위로 계산하여 반환
|
||||
/// @return 1970년 1월 1일 이후부터의 현재시간을 micro-second(1/1,000,000) 단위로 반환처리, 오류발생시에는 -1 값을 반환.
|
||||
long long longtime_now()
|
||||
{
|
||||
struct timeval tv;
|
||||
|
||||
if( gettimeofday(&tv, NULL) == 0 )
|
||||
{
|
||||
// 성공시 micro-second 단위의 값을 반환
|
||||
return tv.tv_sec * USEC_PER_SEC + tv.tv_usec;
|
||||
}
|
||||
else
|
||||
{
|
||||
// 실패시 -1 값을 반환.
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
CGetContentListThread::CGetContentListThread(CQueue<CFileInfo>* pQueueFileInfo
|
||||
, CQueue<CFileInfo>* pQueueDeleteJob
|
||||
, CQueue<CFileInfo>* pQueueCompleteJob)
|
||||
:m_pQueueFileInfo(pQueueFileInfo)
|
||||
, m_pQueueDeleteJob(pQueueDeleteJob)
|
||||
, m_pQueueCompleteJob(pQueueCompleteJob)
|
||||
{
|
||||
m_pPgSQL = NULL;
|
||||
m_bExistCheck = false;
|
||||
m_bCurrent = false;
|
||||
m_bServiceTableSeparate = false;
|
||||
|
||||
// 멤버 변수 초기화
|
||||
m_threadHandle = 0;
|
||||
}
|
||||
|
||||
CGetContentListThread::~CGetContentListThread()
|
||||
{
|
||||
DbClose();
|
||||
// Thread 동작 정지 처리
|
||||
// - 만약 Thread 가 이미 종료된 경우 m_threadHandle 이 다른 Thread Handle 일 수 있으므로
|
||||
// 업무 Flow 수정시 주의할 것
|
||||
if( m_threadHandle != 0 )
|
||||
pthread_cancel( m_threadHandle );
|
||||
}
|
||||
|
||||
/// @brief DB 연결 함수.
|
||||
bool CGetContentListThread::DbConnect()
|
||||
{
|
||||
if( m_pPgSQL != NULL )
|
||||
{
|
||||
DbClose();
|
||||
}
|
||||
m_pPgSQL = new DataBase;
|
||||
if( m_pPgSQL == NULL )
|
||||
{
|
||||
LOG(LERR, "Creating new Database has failed.");
|
||||
return false;
|
||||
}
|
||||
if( m_pPgSQL->PgOpenDB(m_szHost, m_nPort, m_szDBName, m_szAcct, m_szPasswd) == NULL )
|
||||
{
|
||||
LOG(LERR, "Connecting to Database has failed.");
|
||||
DbClose();
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// @breif DB close 함수.
|
||||
void CGetContentListThread::DbClose()
|
||||
{
|
||||
if( m_pPgSQL != NULL )
|
||||
{
|
||||
delete m_pPgSQL;
|
||||
m_pPgSQL = NULL;
|
||||
}
|
||||
}
|
||||
|
||||
bool CGetContentListThread::ThreadInit()
|
||||
{
|
||||
FUNC_BEGIN();
|
||||
|
||||
// 조회 정보를 저장할 Queue 에 대한 참조 포인터가 NULL 경우 오류 처리
|
||||
if( m_pQueueFileInfo == NULL )
|
||||
{
|
||||
LOG(LERR, "FileInfo Queue Pointer is NULL");
|
||||
return false;
|
||||
}
|
||||
|
||||
// RCDB 접속 처리를 위한 객체 생성
|
||||
DataBase rcdb;
|
||||
|
||||
m_szHost = CProcessStatus::GetInstance()->GetRcdbIp();
|
||||
m_nPort = CProcessStatus::GetInstance()->GetRcdbPort();
|
||||
m_szDBName = CProcessStatus::GetInstance()->GetRcdbName();
|
||||
m_szAcct = CProcessStatus::GetInstance()->GetRcdbAcct();
|
||||
m_szPasswd = CProcessStatus::GetInstance()->GetRcdbAcctPw();
|
||||
|
||||
// 최초 초기화 시에는 DB연결 정보들이 제대로 되는것인지에 대한
|
||||
// 확인만 처리 한다.
|
||||
if (rcdb.PgOpenDB(m_szHost, m_nPort, m_szDBName, m_szAcct, m_szPasswd) == NULL )
|
||||
{
|
||||
LOG(LERR, "Connecting to Database has failed.");
|
||||
return false;
|
||||
}
|
||||
|
||||
// 접속 성공한 경우...
|
||||
LOG( LINF, "RCDB connection test ok..." );
|
||||
|
||||
// 서비스 table 분리된 신규 형상인지.. 구형 형상인지 체크하여
|
||||
// m_bServiceTableSeparate 변수 설정 처리.
|
||||
// 해당 변수 초기화는 생성자에서 1차로 수행함.
|
||||
char szQuery[1024];
|
||||
snprintf( szQuery, 1023,"SELECT * FROM pg_tables WHERE schemaname = 'public' AND tablename = 't_dav_resource' " );
|
||||
|
||||
rcdb.PgDoExec( szQuery );
|
||||
if( rcdb.PgResult( DataBase::NOT_CLEAR ) < 0 )
|
||||
{
|
||||
// Query 수행 결과 오류 발생시...
|
||||
// - pg_tables 가 존재하지 않을 경우 오류 발생 가능...
|
||||
// - 이는 RCDB 가 아직 적절하게 구성되지 않았다는 의미이므로... Init()함수를 오류로 처리한다.
|
||||
LOG( LERR, "RCDB t_dav_resource exist check failed.[%s][%s]", rcdb.GetErrorMessage().c_str(), szQuery );
|
||||
|
||||
rcdb.PgClear();
|
||||
rcdb.PgCloseDB();
|
||||
|
||||
return false;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Query 수행이 정상인 경우.
|
||||
int nResult = rcdb.GetNoTuples();
|
||||
if( nResult > 0 )
|
||||
{
|
||||
// t_dav_resource 테이블이 존재하는 경우...
|
||||
m_bServiceTableSeparate = false;
|
||||
_LOG( LINF, "CGetContentListThread: t_dav_resource table exist.[Old RCDB Type]" );
|
||||
}
|
||||
else
|
||||
{
|
||||
// t_dav_resource 테이블이 존재하지 않는 서비스별 테이블 분리 형상인 경우.
|
||||
m_bServiceTableSeparate = true;
|
||||
_LOG( LINF, "CGetContentListThread: t_dav_resource table not exist.[New RCDB Type]" );
|
||||
}
|
||||
}
|
||||
|
||||
// RCDB 조회 결과 set 를 clear 처리 후 RCDB 접속 해제.
|
||||
rcdb.PgClear();
|
||||
rcdb.PgCloseDB();
|
||||
|
||||
FUNC_END();
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CGetContentListThread::GetContentList()
|
||||
{
|
||||
FUNC_BEGIN();
|
||||
|
||||
std::list<CPreserve> listPreserve;
|
||||
std::list<CPreserve>::iterator it;
|
||||
|
||||
// 현재 시간정보를 구한다.( micro-second 단위)
|
||||
long long timeNow = longtime_now();
|
||||
long long timeStart;
|
||||
long long timeEnd, timeRealEnd;
|
||||
long long timeRealEndMin = LLONG_MAX;
|
||||
timeRealEnd = 0;
|
||||
|
||||
int nMaxPreserve = 0;
|
||||
|
||||
time_t tmStart, tmEnd;
|
||||
|
||||
if( m_pPgSQL == NULL )
|
||||
{
|
||||
LOG(LWAR, "Not initialized.");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Query 문장 저장을 위한 버퍼 생성
|
||||
char szQuery[DEFAULT_QUERY_BUFFER_SIZE];
|
||||
int nResult = 0;
|
||||
|
||||
// 조회 구간을 이동 할 것인지 아닌지 확인하는 flag 이다.
|
||||
// 기본은 구간을 이동하지만 특정 조건이 될때는 구간을 옮기지 않는다.
|
||||
// limit 수 만큼 쿼리가 된경우 false 로 세팅
|
||||
bool bSlide = true;
|
||||
|
||||
// 조회 구간의 시작시간이 현재 시간에서 보존기간보다 뺀 기간보다 짧은 경우
|
||||
// 다시 동일 시작 시점부터 조회 해야 하는지 확인 기간이다.
|
||||
bool bCheckSkip = true;
|
||||
|
||||
timeStart = m_timeStartPeriod;
|
||||
timeEnd = timeStart + (GET_LAST_BOUNDARY_DAY * USEC_PER_DAY);
|
||||
// GET_LAST_BOUNDARY_DAY 보다 작으면 timeEnd 는 현재시간으로...
|
||||
// 그렇지 않으면 timeStart에 GET_LAST_BOUNDARY_DAY 만큼 더해서 timeEnd 를 설정한다.
|
||||
if( (timeNow - timeStart) >= (GET_LAST_BOUNDARY_DAY * USEC_PER_DAY) )
|
||||
{
|
||||
LOG(LDBG, "Past......" );
|
||||
} else
|
||||
{
|
||||
LOG(LDBG, "Now...... now[%lld] start[%lld] ",timeNow, timeStart );
|
||||
timeEnd = timeNow;
|
||||
m_bCurrent = true;
|
||||
}
|
||||
|
||||
listPreserve = CProcessStatus::GetInstance()->GetPreserveList();
|
||||
for ( it=listPreserve.begin(); it != listPreserve.end(); it++ )
|
||||
{
|
||||
CPreserve objPreserve = *it;
|
||||
int nLimit = QUERY_LIMIT_COUNT;
|
||||
char buff1[20];
|
||||
char buff2[20];
|
||||
|
||||
//LOG( LINF, "start : %lld, time end : %lld, realend : %lld, now - preserve : %lld", timeStart, timeEnd, timeRealEnd, ( timeNow - (objPreserve.m_nPreserveDay * USEC_PER_DAY)) );
|
||||
|
||||
LOG( LDBG, "svc[%s] start[%lld] end[%lld] real_end[%lld], now - preserve =[%lld]"
|
||||
, objPreserve.m_szServiceID.c_str()
|
||||
, timeStart, timeEnd, timeRealEnd
|
||||
, (timeNow - (objPreserve.m_nPreserveDay * USEC_PER_DAY)) );
|
||||
|
||||
|
||||
//!! 조건에 따라 EndTime 을 구한다.
|
||||
//!! 또는 조건에 따라 쿼리를 하지 않기도 한다.
|
||||
|
||||
//1. 시작시간에서 보존 기간을 뺀 값이 마이너스인경우 해당 서비스는 스킵.
|
||||
if ( timeStart > (timeNow - (objPreserve.m_nPreserveDay * USEC_PER_DAY)) )
|
||||
{
|
||||
// skip 된 서비스가 하나라도 있으면 Start Period 를 옮기지 않는다.
|
||||
bCheckSkip = false;
|
||||
continue;
|
||||
}
|
||||
//2. 현재시간에서 보존기간을 뺀 값이 시작과 끝 시간 사이라면 timeEnd 를 조정해 준다.
|
||||
else if ( timeEnd > ( timeNow - (objPreserve.m_nPreserveDay * USEC_PER_DAY)) )
|
||||
{
|
||||
timeRealEnd = timeNow - (objPreserve.m_nPreserveDay * USEC_PER_DAY);
|
||||
// 테스트를 위함 -- 3분
|
||||
//timeRealEnd = timeNow - (180 * USEC_PER_SEC);
|
||||
}
|
||||
else
|
||||
{
|
||||
timeRealEnd = timeEnd;
|
||||
}
|
||||
//3. 그렇지 않으면 그냥 기존 시간대로 진행... ( 현재시간과 가깝지 않다는 뜻..)
|
||||
|
||||
// 가장 작은 실제 엔드 값을 구한다.
|
||||
// 이는 조회 구간 조정시 사용 된다.
|
||||
if ( timeRealEnd < timeRealEndMin )
|
||||
{
|
||||
timeRealEndMin = timeRealEnd;
|
||||
}
|
||||
//4. 시간값 로깅 처리
|
||||
tmStart = timeStart/USEC_PER_SEC;
|
||||
tmEnd = timeRealEnd/USEC_PER_SEC;
|
||||
strftime(buff1, 20, "%Y-%m-%d %H:%M:%S", localtime(&tmStart));
|
||||
strftime(buff2, 20, "%Y-%m-%d %H:%M:%S", localtime(&tmEnd));
|
||||
|
||||
_LOG( LINF, "content check: svc[%s] start[%s] end[%s]", objPreserve.m_szServiceID.c_str(), buff1, buff2);
|
||||
LOG( LDEV, "GetList Query : [%s]", szQuery );
|
||||
|
||||
//!! webting 수정 필요
|
||||
if(m_bServiceTableSeparate == false)
|
||||
{
|
||||
// 구형 DB 스키마 용
|
||||
// 실제 쿼리
|
||||
snprintf(szQuery, DEFAULT_QUERY_BUFFER_SIZE - 1,
|
||||
"SELECT sp_svc_tran_id, host_name, resource_type, uri, filename_hash, get_content_length, get_lastmodified "
|
||||
"FROM t_dav_resource "
|
||||
"WHERE sp_svc_tran_id = %s AND get_lastmodified >= %lld AND get_lastmodified < %lld AND deleted_yn = 'Y' LIMIT %d; "
|
||||
, objPreserve.m_szServiceID.c_str()
|
||||
, timeStart
|
||||
, timeRealEnd
|
||||
, nLimit );
|
||||
}
|
||||
else
|
||||
{
|
||||
// 실제 쿼리
|
||||
snprintf(szQuery, DEFAULT_QUERY_BUFFER_SIZE - 1,
|
||||
"SELECT sp_svc_tran_id, host_name, resource_type, uri, filename_hash, get_content_length, get_lastmodified "
|
||||
"FROM t_meta_%s "
|
||||
"WHERE sp_svc_tran_id = %s AND get_lastmodified >= %lld AND get_lastmodified < %lld AND deleted_yn = 'Y' LIMIT %d; "
|
||||
, objPreserve.m_szServiceID.c_str()
|
||||
, objPreserve.m_szServiceID.c_str()
|
||||
, timeStart
|
||||
, timeRealEnd
|
||||
, nLimit );
|
||||
}
|
||||
|
||||
// Query 실행
|
||||
m_pPgSQL->PgDoExec(szQuery);
|
||||
nResult = m_pPgSQL->PgResult( DataBase::NOT_CLEAR );
|
||||
if( nResult < 0 )
|
||||
{
|
||||
if( m_pPgSQL != NULL )
|
||||
{
|
||||
LOG(LWAR, "RCDB Query failed.[%d][%s]", nResult, m_pPgSQL->GetErrorMessage().c_str() );
|
||||
|
||||
m_pPgSQL->PgClear();
|
||||
DbClose();
|
||||
}
|
||||
|
||||
// 실패 해도 변경 주기 만큼 슬립한다.
|
||||
return false;
|
||||
}
|
||||
|
||||
nResult = m_pPgSQL->GetNoTuples();
|
||||
|
||||
if( nResult >= 1 )
|
||||
{
|
||||
m_bExistCheck = true;
|
||||
}
|
||||
|
||||
if( nResult >= QUERY_LIMIT_COUNT )
|
||||
{
|
||||
bSlide = false;
|
||||
}
|
||||
|
||||
_LOG( LINF, "delete target: svc[%s] count[%d]", objPreserve.m_szServiceID.c_str(), nResult);
|
||||
// Replication 을 수행할 고객사가 존재하는 경우.
|
||||
// 조회된 정보를 내부 멤버변수에 저장처리.
|
||||
for( int i =0 ; i< nResult; i++ )
|
||||
{
|
||||
CFileInfo objFileInfo;
|
||||
objFileInfo.m_szSvcTranid = m_pPgSQL->GetValue(i, 0);
|
||||
objFileInfo.m_szHostName = m_pPgSQL->GetValue(i, 1);
|
||||
objFileInfo.m_nType =atoi(m_pPgSQL->GetValue(i, 2));
|
||||
objFileInfo.m_szUri = m_pPgSQL->GetValue(i, 3);
|
||||
objFileInfo.m_szFileNameHash = m_pPgSQL->GetValue(i, 4);
|
||||
objFileInfo.m_nContentLength = atoll(m_pPgSQL->GetValue(i, 5));
|
||||
objFileInfo.m_nLastModified = atoll(m_pPgSQL->GetValue(i, 6));
|
||||
|
||||
m_pQueueFileInfo->Push(objFileInfo);
|
||||
}
|
||||
|
||||
// Query Result set Clear.
|
||||
m_pPgSQL->PgClear();
|
||||
}
|
||||
|
||||
//!! 쿼리 결과가 limit 수 보다 모두 적은 경우는 startPeriod 를 옮겨 준다.
|
||||
if( bSlide == true && bCheckSkip == true )
|
||||
{
|
||||
m_timeStartPeriod = timeRealEndMin;
|
||||
}
|
||||
|
||||
FUNC_END();
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
///@brief 이 함수에서 컨트롤 로직이 표현된다.
|
||||
void CGetContentListThread::Execute()
|
||||
{
|
||||
FUNC_BEGIN();
|
||||
|
||||
// 시작 모드를 결정한다.
|
||||
|
||||
std::string szStartPeriod = CProcessStatus::GetInstance()->GetStartPeriod();
|
||||
|
||||
// 설정 값이 있다면 그 시간을 시작으로 잡고...
|
||||
if ( szStartPeriod.size() == 8 )
|
||||
{
|
||||
struct tm sTime= {0,};
|
||||
sTime.tm_year = atoi(szStartPeriod.substr(0,4).c_str()) - 1900;
|
||||
sTime.tm_mon = atoi(szStartPeriod.substr(4,2).c_str()) - 1;
|
||||
sTime.tm_mday = atoi(szStartPeriod.substr(6,2).c_str());
|
||||
|
||||
time_t time_tee = mktime(&sTime);
|
||||
m_timeStartPeriod = time_tee * USEC_PER_SEC;
|
||||
}
|
||||
else
|
||||
{
|
||||
// 설정값이 없다면 기본 boundary 의 두배 만큼 현재 시간에서 과거로 돌려서.. 시작.
|
||||
m_timeStartPeriod = longtime_now() - (GET_LAST_BOUNDARY_DAY * USEC_PER_DAY *2);
|
||||
}
|
||||
|
||||
while(1)
|
||||
{
|
||||
std::list<CPreserve> listPreserve;
|
||||
listPreserve = CProcessStatus::GetInstance()->GetPreserveList();
|
||||
m_bExistCheck = false;
|
||||
m_bCurrent = false;
|
||||
if ( listPreserve.size() <= 0 )
|
||||
{
|
||||
LOG(LWAR, "listPreserve is Not initialized.");
|
||||
sleep(1);
|
||||
continue;
|
||||
}
|
||||
if ( DbConnect() == false)
|
||||
{
|
||||
// 한 번더 정리한 후
|
||||
DbClose();
|
||||
|
||||
sleep( DB_INFORMATION_UPDATE_INTERVAL );
|
||||
// 연결 재시도
|
||||
continue;
|
||||
}
|
||||
// 아래 함수에서 return false 가 되면 기존 세션에대해 정리한 후
|
||||
// DB Connection을 다시 요청한다.
|
||||
if( GetContentList() == false )
|
||||
{
|
||||
// 한 번더 정리한 후
|
||||
DbClose();
|
||||
sleep( DB_INFORMATION_UPDATE_INTERVAL );
|
||||
// 연결 재시도
|
||||
continue;
|
||||
}
|
||||
|
||||
// 일단 DB 연결을 해제한다.
|
||||
DbClose();
|
||||
// 끝날때까지 대기 한다.
|
||||
while(1)
|
||||
{
|
||||
_LOG(LINF, "Job cheking ...");
|
||||
_LOG(LINF, " List Queue[%d], Delete Queue[%d], Delete Thread[%d], Complete Queue[%d]"
|
||||
, m_pQueueFileInfo->GetSize(), m_pQueueDeleteJob->GetSize()
|
||||
, CProcessStatus::GetInstance()->GetDeleteThreadCount()
|
||||
, m_pQueueCompleteJob->GetSize() );
|
||||
|
||||
|
||||
if( m_pQueueFileInfo->GetSize() <= 0 &&
|
||||
m_pQueueDeleteJob->GetSize() <= 0 &&
|
||||
m_pQueueCompleteJob->GetSize() <= 0 &&
|
||||
CProcessStatus::GetInstance()->GetDeleteThreadCount() <= 0 )
|
||||
{
|
||||
break;
|
||||
}
|
||||
sleep(1);
|
||||
}
|
||||
//sleep(DB_INFORMATION_UPDATE_INTERVAL);
|
||||
|
||||
//
|
||||
if( m_bExistCheck == true )
|
||||
{
|
||||
sleep(1);
|
||||
} else {
|
||||
if( m_bCurrent == false )
|
||||
{
|
||||
sleep(1);
|
||||
} else
|
||||
{
|
||||
sleep(DB_INFORMATION_UPDATE_INTERVAL);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 쓰레드 종료 될 때 DB 세션 정리 한다.
|
||||
DbClose();
|
||||
|
||||
LOG(LERR, "Thread create failed.: errno:%d errmsg:%s", errno, strerror(errno));
|
||||
FUNC_END();
|
||||
}
|
||||
|
||||
void* CGetContentListThread::EntryPoint(void* arg)
|
||||
{
|
||||
CGetContentListThread* pObject = reinterpret_cast<CGetContentListThread *>(arg);
|
||||
pthread_detach( pthread_self() );
|
||||
|
||||
pthread_testcancel();
|
||||
pObject->Execute();
|
||||
pthread_testcancel();
|
||||
|
||||
// Thread 종료시 m_threadHandle 값을 초기화 처리.
|
||||
// - 소멸자에서 잘못된 Thread 를 종료할 수 있기 때문.
|
||||
pObject->m_threadHandle = 0;
|
||||
|
||||
delete pObject;
|
||||
return 0;
|
||||
}
|
||||
|
||||
bool CGetContentListThread::Start()
|
||||
{
|
||||
int nRet = ::pthread_create(&m_threadHandle, 0, CGetContentListThread::EntryPoint, this);
|
||||
|
||||
if( nRet )
|
||||
{
|
||||
LOG(LERR, "Thread create failed.: errno:%d errmsg:%s", errno, strerror(errno));
|
||||
return false;
|
||||
}
|
||||
LOG(LDBG, "Thread create succeed");
|
||||
sleep(0);
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
/***************************************************************************
|
||||
Replicate Work Class
|
||||
-----------------------------------------
|
||||
begin : 2012/10/14
|
||||
copyright : (C) 2010 SolutionBox Inc.
|
||||
author : Service 1 Team
|
||||
email : svc1@solbox.com
|
||||
version : 1.0
|
||||
|
||||
CopyRight(C) 2010 SolutionBox Inc. All Rights reserved.
|
||||
Redistribution and use in source and binary forms, with or with out
|
||||
modification, are not permitted in outside of SolutionBox Inc.
|
||||
***************************************************************************/
|
||||
|
||||
#ifndef __CONTENT_LIST_THREAD__
|
||||
#define __CONTENT_LIST_THREAD__
|
||||
|
||||
#include <pthread.h>
|
||||
#include <string>
|
||||
#include "Logger.h"
|
||||
#include "Data.h"
|
||||
#include "DataQueue.h"
|
||||
#include "ProcessStatus.h"
|
||||
#include "Database.h"
|
||||
|
||||
/// @brief
|
||||
class CGetContentListThread
|
||||
{
|
||||
public:
|
||||
/// @brief 생성자
|
||||
/// @param [in] pLogger 로깅을 위한 클래스.
|
||||
CGetContentListThread(CQueue<CFileInfo>* pQueueFileInfo
|
||||
, CQueue<CFileInfo>* pQueueDeleteJob
|
||||
, CQueue<CFileInfo>* pQueueCompleteJob);
|
||||
~CGetContentListThread();
|
||||
|
||||
/// @brief Thread를 생성하고, 이를 시작한다.
|
||||
/// @param none
|
||||
/// @return 성공은 return true 실패는 return false
|
||||
bool Start();
|
||||
|
||||
bool DbConnect();
|
||||
void DbClose();
|
||||
|
||||
/// @brief ProcessStatus 내의 RCDB 관련 설정값을 이용해 DB Connection을 한다.
|
||||
/// @param None
|
||||
/// @return 성공하면 return true 실패하면 return false
|
||||
bool ThreadInit();
|
||||
bool GetContentList();
|
||||
// Attributes
|
||||
private:
|
||||
DataBase* m_pPgSQL;
|
||||
bool m_bExistCheck;
|
||||
bool m_bCurrent;
|
||||
|
||||
CQueue<CFileInfo>* m_pQueueFileInfo;
|
||||
CQueue<CFileInfo>* m_pQueueDeleteJob;
|
||||
CQueue<CFileInfo>* m_pQueueCompleteJob;
|
||||
|
||||
std::string m_szHost;
|
||||
int m_nPort;
|
||||
std::string m_szDBName;
|
||||
std::string m_szAcct;
|
||||
std::string m_szPasswd;
|
||||
|
||||
bool m_bServiceTableSeparate;
|
||||
|
||||
unsigned long long m_timeStartPeriod;
|
||||
|
||||
// 쓰레드 핸들
|
||||
pthread_t m_threadHandle;
|
||||
|
||||
// 쓰레드 시작 루틴이다.
|
||||
static void* EntryPoint(void* arg);
|
||||
|
||||
// 해당 함수의 내용은 수정하지 말것.
|
||||
void Execute();
|
||||
};
|
||||
#endif //__CONTENT_LIST_THREAD__
|
||||
@@ -0,0 +1,83 @@
|
||||
#****************************************************************************
|
||||
# Makefile for RC Content Check daemon
|
||||
# -----------------------------------------
|
||||
#
|
||||
# begin : 2012/10/12
|
||||
# copyright : (C) 2012 SolutionBox Inc.
|
||||
# author : Service 1 Team
|
||||
# email : svc1@solbox.com
|
||||
# version : 3.2.0
|
||||
#
|
||||
# CopyRight(C) 2005 SolutionBox Inc. All Rights reserved.
|
||||
# Redistribution and use in source and binary forms, with or with out
|
||||
# modification, are not permitted in outside of SolutionBox Inc.
|
||||
#*****************************************************************************
|
||||
|
||||
# Program info
|
||||
PROG_NAME = rc_gcmd
|
||||
REVISION = 1370
|
||||
BUILD_DATE = `date +%Y%m%d%H%M%S`
|
||||
PROG_VERSION = 3.5.0.$(REVISION)-$(BUILD_DATE)
|
||||
DEFAULT_CONFIG_FILE = /user/service/etc/rcts.conf
|
||||
|
||||
|
||||
INSTALL_BIN = /user/service/bin
|
||||
INSTALL_CONF = /user/service/etc
|
||||
|
||||
# Compiler info
|
||||
CC = /usr/bin/g++
|
||||
|
||||
CFLAGS = -Wall -O3 -g -Wreturn-type -Wunused -Wuninitialized\
|
||||
-Wparentheses -Wshadow -Wpointer-arith -Woverloaded-virtual\
|
||||
-fno-rtti -D_THREAD_SAFE -D_REENTRANT -D_PTHREADS -Wno-unused -Wno-non-virtual-dtor
|
||||
|
||||
LFLAGS = -lpthread
|
||||
|
||||
# DEBUG or RELEASE Mode select
|
||||
ifeq ($(DEBUG), yes)
|
||||
PROG_VERSION = 3.3.0.$(REVISION)D-$(BUILD_DATE)
|
||||
|
||||
CFLAGS = -Wall -O0 -g -Wreturn-type -Wunused -Wuninitialized\
|
||||
-Wparentheses -Wshadow -Wpointer-arith -Woverloaded-virtual\
|
||||
-fno-rtti -D_THREAD_SAFE -D_REENTRANT -D_PTHREADS -Wno-unused -Wno-non-virtual-dtor
|
||||
|
||||
DFLAGS = -D_DEBUG -DPROG_NAME=\"$(PROG_NAME)\" -DPROG_VERSION=\"$(PROG_VERSION)\" -DDEFAULT_CONFIG_FILE=\"$(DEFAULT_CONFIG_FILE)\"
|
||||
else
|
||||
DFLAGS = -DPROG_NAME=\"$(PROG_NAME)\" -DPROG_VERSION=\"$(PROG_VERSION)\" -DDEFAULT_CONFIG_FILE=\"$(DEFAULT_CONFIG_FILE)\"
|
||||
endif
|
||||
|
||||
|
||||
# Application Enviroment
|
||||
APP = $(PROG_NAME)
|
||||
|
||||
DIR_LIB = -L../lib
|
||||
|
||||
DIR_INCLUDE = -I./. -I../lib -I/user/db/pgsql/include
|
||||
LIBS = ../lib/libInterCommon.a /user/db/pgsql/lib/libpq.a
|
||||
|
||||
OBJ = main.o GcmdConfig.o ProcessStatus.o Worker.o \
|
||||
Database.o DataQueue.o PreserveUpdater.o GetContentListThread.o \
|
||||
CategorizeThread.o PhysicalDeleteThread.o FtsdSocketControl.o CompleteThread.o
|
||||
|
||||
############################
|
||||
|
||||
all:$(APP)
|
||||
sync
|
||||
|
||||
%.o: %.cpp
|
||||
$(CC) $(CFLAGS) -o $@ -c $^ $(DFLAGS) $(DIR_INCLUDE)
|
||||
|
||||
$(PROG_NAME): $(OBJ)
|
||||
$(CC) $(LFLAGS) -o $@ $^ $(DFLAGS) $(DIR_LIB) $(LIBS)
|
||||
|
||||
clean:
|
||||
-rm -f *.o core *.out *.log
|
||||
-rm -f $(APP)
|
||||
sync
|
||||
|
||||
|
||||
install : $(APP)
|
||||
-cp $(APP) $(INSTALL_BIN)/$(APP)
|
||||
sync
|
||||
|
||||
# End of Makefile
|
||||
@@ -0,0 +1,165 @@
|
||||
|
||||
#include "PhysicalDeleteThread.h"
|
||||
#include "FtsdSocketControl.h"
|
||||
|
||||
#include <string.h>
|
||||
#include <errno.h>
|
||||
#include <list>
|
||||
|
||||
using namespace std;
|
||||
|
||||
#define TRANSFER_LISTEN_PORT 14001 // ftsd 의 Listen Port
|
||||
|
||||
CPhysicalDeleteThread::CPhysicalDeleteThread(CFileInfo objDelFileInfo
|
||||
, CQueue<CFileInfo>* pQueueCompleteJob)
|
||||
: m_pQueueCompleteJob(pQueueCompleteJob)
|
||||
{
|
||||
m_objDelFileInfo = objDelFileInfo;
|
||||
|
||||
// 멤버 변수 초기화
|
||||
m_threadHandle = 0;
|
||||
}
|
||||
|
||||
CPhysicalDeleteThread::~CPhysicalDeleteThread()
|
||||
{
|
||||
// Thread 동작 정지 처리
|
||||
// - 만약 Thread 가 이미 종료된 경우 m_threadHandle 이 다른 Thread Handle 일 수 있으므로
|
||||
// 업무 Flow 수정시 주의할 것
|
||||
if( m_threadHandle != 0 )
|
||||
pthread_cancel( m_threadHandle );
|
||||
|
||||
}
|
||||
|
||||
bool CPhysicalDeleteThread::PhysicalDelete()
|
||||
{
|
||||
|
||||
////////////// 결과값을 저장할 변수 //////////////////
|
||||
// 오류 메시지
|
||||
std::string szErrorMessage;
|
||||
|
||||
// 요청에 대한 응답 대기
|
||||
int nTimeout = 5; // 응답 대기 시간 ( sec )
|
||||
int nResult = 0;
|
||||
bool bResultSuccess; // 처리 결과의 성공/실패 여부를 저장하기 위한 변수.
|
||||
|
||||
// ftsd 와 통신을 처리할 Socket Control 객체 생성 및 접속
|
||||
CFtsdSocketControl ftsdSocket;
|
||||
if( ftsdSocket.ConnectTarget( m_objDelFileInfo.m_szHostName, TRANSFER_LISTEN_PORT ) == false )
|
||||
{
|
||||
// Source ftsd 으로 접속 실패시
|
||||
_LOG( LERR, "Source FHS connect fail. [%s][%d]", m_objDelFileInfo.m_szHostName.c_str(), TRANSFER_LISTEN_PORT );
|
||||
return false;
|
||||
}
|
||||
// ftsd 로 파일에 대한 Check 요청 전달
|
||||
// SendFileCheckRequest() 함수는 FtsdSocketControl.h 파일 참조.
|
||||
if( ftsdSocket.SendFileUnlinkRequest( m_objDelFileInfo.m_szFileNameHash, m_objDelFileInfo.m_nContentLength, true ) == false )
|
||||
{
|
||||
// Source ftsd 로 전송 실패시
|
||||
_LOG( LERR, "Unlink Request send fail.[%s][%s]", m_objDelFileInfo.m_szHostName.c_str(), m_objDelFileInfo.m_szFileNameHash.c_str());
|
||||
return false;
|
||||
}
|
||||
// 루프를 돌면서 요청에 대한 응답을 대기
|
||||
while(1)
|
||||
{
|
||||
// nTimeout 에 지정된 시간동안 응답대기 시도
|
||||
// GetFileCheckResult() 함수는 SocketControl.h 파일 참고.
|
||||
nResult = ftsdSocket.GetFileUnlinkResult( nTimeout, bResultSuccess, szErrorMessage);
|
||||
|
||||
if( nResult == -1 )
|
||||
{
|
||||
// Socket 통신 관련 오류 또는 접속 종료가 발생한 경우.
|
||||
// 해당 내역 로깅 및 루프 종료
|
||||
_LOG( LERR, "ftsd Response wait fail by socket [%s][%s]", m_objDelFileInfo.m_szHostName.c_str(), m_objDelFileInfo.m_szFileNameHash.c_str() );
|
||||
break;
|
||||
}
|
||||
else if( nResult == 0 )
|
||||
{
|
||||
// 지정된 시간 동안 응답대기 중 처리 결과 정보가 아직 수신되지 않은 경우 => Allive Check 패킷 한번 쏘고 다시 Loop 로
|
||||
|
||||
if( ftsdSocket.SendAliveCheck() == false )
|
||||
{
|
||||
// Alive 전송 실패시 => Socket 종료 및 오류가 발생한 경우임.
|
||||
_LOG( LERR, "ftsd Response wait fail by socket2 [%s][%s]", m_objDelFileInfo.m_szHostName.c_str(), m_objDelFileInfo.m_szFileNameHash.c_str() );
|
||||
break;
|
||||
}
|
||||
// 정상적인 경우 다시 응답대기.
|
||||
continue;
|
||||
|
||||
}
|
||||
else if( nResult == 1 )
|
||||
{
|
||||
// 요청에 대한 처리결과 정보가 수신된 경우.
|
||||
// 해당 정보 로깅처리.
|
||||
|
||||
if( bResultSuccess == true )
|
||||
{
|
||||
// 요청에 대한 처리가 정상적으로 처리된 경우
|
||||
//_LOG( LINF, "[%s] Result SUCCESS [%llu][%s]", szFileName.c_str(), nFileSize, szHashValue.c_str());
|
||||
|
||||
_LOG( LDBG, "Unlink result SUCCESS.");
|
||||
}
|
||||
else
|
||||
{
|
||||
// 오류 발생시
|
||||
_LOG( LWAR, "[%s][%s] Result ERROR (%s)", m_objDelFileInfo.m_szFileNameHash.c_str(), m_objDelFileInfo.m_szHostName.c_str(), szErrorMessage.c_str() );
|
||||
}
|
||||
|
||||
break; // 응답을 받았으니 응답 대기 루프 종료
|
||||
}
|
||||
else
|
||||
{
|
||||
// Replication 요청에 대한 응답패킷이 아닌 경우.
|
||||
// 해당 패킷은 무시하고 다시 Loop 로
|
||||
continue;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
///@brief 이 함수에서 컨트롤 로직이 표현된다.
|
||||
void CPhysicalDeleteThread::Execute()
|
||||
{
|
||||
FUNC_BEGIN();
|
||||
|
||||
// 해당 함수 내에서 필요한 로깅은 모두 처리한다.
|
||||
PhysicalDelete();
|
||||
// 어떤 결과가 나오더라도 Meta 정보가 삭제 될 수 있도록
|
||||
m_pQueueCompleteJob->Push(m_objDelFileInfo);
|
||||
// 쓰레드 수 감소.
|
||||
CProcessStatus::GetInstance()->SubtractJobThreadCount();
|
||||
FUNC_END();
|
||||
}
|
||||
|
||||
void* CPhysicalDeleteThread::EntryPoint(void* arg)
|
||||
{
|
||||
CPhysicalDeleteThread* pObject = reinterpret_cast<CPhysicalDeleteThread *>(arg);
|
||||
pthread_detach( pthread_self() );
|
||||
|
||||
pthread_testcancel();
|
||||
pObject->Execute();
|
||||
pthread_testcancel();
|
||||
|
||||
// Thread 종료시 m_threadHandle 값을 초기화 처리.
|
||||
// - 소멸자에서 잘못된 Thread 를 종료할 수 있기 때문.
|
||||
pObject->m_threadHandle = 0;
|
||||
|
||||
delete pObject;
|
||||
|
||||
FUNC_END();
|
||||
return 0;
|
||||
}
|
||||
|
||||
bool CPhysicalDeleteThread::Start()
|
||||
{
|
||||
int nRet = ::pthread_create(&m_threadHandle, 0, CPhysicalDeleteThread::EntryPoint, this);
|
||||
|
||||
if( nRet )
|
||||
{
|
||||
LOG(LERR, "Thread create failed.: errno:%d errmsg:%s", errno, strerror(errno));
|
||||
return false;
|
||||
}
|
||||
CProcessStatus::GetInstance()->AddJobThreadCount();
|
||||
LOG(LDBG, "Thread create succeed");
|
||||
sleep(0);
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
/***************************************************************************
|
||||
Replicate Work Class
|
||||
-----------------------------------------
|
||||
begin : 2012/10/14
|
||||
copyright : (C) 2010 SolutionBox Inc.
|
||||
author : Service 1 Team
|
||||
email : svc1@solbox.com
|
||||
version : 1.0
|
||||
|
||||
CopyRight(C) 2010 SolutionBox Inc. All Rights reserved.
|
||||
Redistribution and use in source and binary forms, with or with out
|
||||
modification, are not permitted in outside of SolutionBox Inc.
|
||||
***************************************************************************/
|
||||
|
||||
#ifndef __PHSYCAL_DELETE_THREAD__
|
||||
#define __PHSYCAL_DELETE_THREAD__
|
||||
|
||||
#include <pthread.h>
|
||||
#include <string>
|
||||
#include "Logger.h"
|
||||
#include "Data.h"
|
||||
#include "DataQueue.h"
|
||||
#include "ProcessStatus.h"
|
||||
|
||||
/// @brief
|
||||
class CPhysicalDeleteThread
|
||||
{
|
||||
public:
|
||||
/// @brief 생성자
|
||||
/// @param [in] pLogger 로깅을 위한 클래스.
|
||||
CPhysicalDeleteThread(CFileInfo objDelFileInfo, CQueue<CFileInfo>* pQueueCompleteJob);
|
||||
~CPhysicalDeleteThread();
|
||||
|
||||
/// @brief Thread를 생성하고, 이를 시작한다.
|
||||
/// @param none
|
||||
/// @return 성공은 return true 실패는 return false
|
||||
bool Start();
|
||||
|
||||
/// @brief ProcessStatus 내의 RCDB 관련 설정값을 이용해 DB Connection을 한다.
|
||||
/// @param None
|
||||
/// @return 성공하면 return true 실패하면 return false
|
||||
bool ThreadInit();
|
||||
|
||||
// Attributes
|
||||
private:
|
||||
CQueue<CFileInfo>* m_pQueueCompleteJob;
|
||||
CFileInfo m_objDelFileInfo;
|
||||
// 쓰레드 핸들
|
||||
pthread_t m_threadHandle;
|
||||
|
||||
// 쓰레드 시작 루틴이다.
|
||||
static void* EntryPoint(void* arg);
|
||||
bool PhysicalDelete();
|
||||
// 해당 함수의 내용은 수정하지 말것.
|
||||
void Execute();
|
||||
|
||||
|
||||
};
|
||||
#endif //__PHSYCAL_DELETE_THREAD__
|
||||
@@ -0,0 +1,224 @@
|
||||
|
||||
#include "PreserveUpdater.h"
|
||||
|
||||
#include <unistd.h>
|
||||
#include <string.h>
|
||||
#include <errno.h>
|
||||
#include <list>
|
||||
|
||||
using namespace std;
|
||||
|
||||
#define DB_INFORMATION_UPDATE_INTERVAL 300 // sec
|
||||
//#define DB_INFORMATION_UPDATE_INTERVAL 1 // sec
|
||||
#define DEFAULT_QUERY_BUFFER_SIZE 1024
|
||||
#define DEFAULT_PRESERVE_DAY 3
|
||||
|
||||
CPreserveUpdater::CPreserveUpdater( )
|
||||
{
|
||||
m_pPgSQL = NULL;
|
||||
}
|
||||
|
||||
CPreserveUpdater::~CPreserveUpdater()
|
||||
{
|
||||
DbClose();
|
||||
pthread_cancel(m_threadHandle);
|
||||
}
|
||||
|
||||
/// @brief DB 연결 함수.
|
||||
bool CPreserveUpdater::DbConnect()
|
||||
{
|
||||
if( m_pPgSQL != NULL )
|
||||
{
|
||||
DbClose();
|
||||
}
|
||||
m_pPgSQL = new DataBase;
|
||||
if( m_pPgSQL == NULL )
|
||||
{
|
||||
LOG(LERR, "Creating new Database has failed.");
|
||||
return false;
|
||||
}
|
||||
if( m_pPgSQL->PgOpenDB(m_szHost, m_nPort, m_szDBName, m_szAcct, m_szPasswd) == NULL )
|
||||
{
|
||||
LOG(LERR, "Connecting to Database has failed.");
|
||||
DbClose();
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// @breif DB close 함수.
|
||||
void CPreserveUpdater::DbClose()
|
||||
{
|
||||
if( m_pPgSQL != NULL )
|
||||
{
|
||||
delete m_pPgSQL;
|
||||
m_pPgSQL = NULL;
|
||||
}
|
||||
}
|
||||
|
||||
bool CPreserveUpdater::ThreadInit()
|
||||
{
|
||||
FUNC_BEGIN();
|
||||
DataBase * pPgSQL = new DataBase;
|
||||
if (pPgSQL == NULL)
|
||||
{
|
||||
LOG(LERR, "Creating new Database has failed.");
|
||||
return false;
|
||||
}
|
||||
|
||||
m_szHost = CProcessStatus::GetInstance()->GetRcdbIp();
|
||||
m_nPort = CProcessStatus::GetInstance()->GetRcdbPort();
|
||||
m_szDBName = CProcessStatus::GetInstance()->GetRcdbName();
|
||||
m_szAcct = CProcessStatus::GetInstance()->GetRcdbAcct();
|
||||
m_szPasswd = CProcessStatus::GetInstance()->GetRcdbAcctPw();
|
||||
|
||||
// 최초 초기화 시에는 DB연결 정보들이 제대로 되는것인지에 대한
|
||||
// 확인만 처리 한다.
|
||||
if (pPgSQL->PgOpenDB(m_szHost, m_nPort, m_szDBName, m_szAcct, m_szPasswd) == NULL )
|
||||
{
|
||||
LOG(LERR, "Connecting to Database has failed.");
|
||||
if (pPgSQL != NULL)
|
||||
{
|
||||
delete pPgSQL;
|
||||
pPgSQL = NULL;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
if (pPgSQL != NULL)
|
||||
{
|
||||
delete pPgSQL;
|
||||
pPgSQL = NULL;
|
||||
}
|
||||
|
||||
FUNC_END();
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CPreserveUpdater::PreserveUpdate()
|
||||
{
|
||||
FUNC_BEGIN();
|
||||
std::list<CPreserve> listPreserve;
|
||||
|
||||
if( m_pPgSQL == NULL )
|
||||
{
|
||||
LOG(LWAR, "Not initialized.");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Query 문장 저장을 위한 버퍼 생성
|
||||
char szQuery[DEFAULT_QUERY_BUFFER_SIZE];
|
||||
int nResult = 0;
|
||||
|
||||
snprintf(szQuery, DEFAULT_QUERY_BUFFER_SIZE - 1,
|
||||
"SELECT sp_svc_tran_id, del_file_keep_time "
|
||||
"FROM t_sms_sp_svc_product; "
|
||||
);
|
||||
|
||||
LOG( LDEV, "Preserve Query : [%s]", szQuery );
|
||||
|
||||
// Query 실행
|
||||
m_pPgSQL->PgDoExec(szQuery);
|
||||
nResult = m_pPgSQL->PgResult( DataBase::NOT_CLEAR );
|
||||
|
||||
if( nResult < 0 )
|
||||
{
|
||||
// RCDB t_sms_sp_svc_product 테이블상에 preserv_day 컬럼이 존재하지 않는 경우
|
||||
// Replication 처리를 당장 수행할 필요가 없으므로 루프 대기처리후 다음에 다시 조회처리.
|
||||
if( m_pPgSQL != NULL )
|
||||
{
|
||||
LOG(LWAR, "RCDB t_sms_sp_svc_product, del_file_keep_time column get failed.[%d][%s]", nResult, m_pPgSQL->GetErrorMessage().c_str() );
|
||||
|
||||
m_pPgSQL->PgClear();
|
||||
DbClose();
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
nResult = m_pPgSQL->GetNoTuples();
|
||||
|
||||
// 조회된 정보를 listPreserve 에 저장처리.
|
||||
for( int i =0 ; i< nResult; i++ )
|
||||
{
|
||||
CPreserve objPreserve;
|
||||
|
||||
LOG( LDBG, "sp_svc_tran_id [%d], preserve_day[%d] ", atoi( m_pPgSQL->GetValue(i,0)), atoi( m_pPgSQL->GetValue(i,1)) );
|
||||
objPreserve.m_szServiceID = m_pPgSQL->GetValue(i,0);
|
||||
objPreserve.m_nPreserveDay = atoi( m_pPgSQL->GetValue(i,1) );
|
||||
if( objPreserve.m_nPreserveDay <= 0 )
|
||||
{
|
||||
objPreserve.m_nPreserveDay = DEFAULT_PRESERVE_DAY;
|
||||
}
|
||||
|
||||
listPreserve.push_back(objPreserve);
|
||||
}
|
||||
|
||||
// ProcessStatus 객체에 값을 넣어 준다.
|
||||
CProcessStatus::GetInstance()->SetPreserveList(listPreserve);
|
||||
|
||||
// Query Result set Clear.
|
||||
m_pPgSQL->PgClear();
|
||||
|
||||
FUNC_END();
|
||||
return true;
|
||||
}
|
||||
|
||||
///@brief 이 함수에서 컨트롤 로직이 표현된다.
|
||||
void CPreserveUpdater::Execute()
|
||||
{
|
||||
FUNC_BEGIN();
|
||||
// 아래 함수에서 return false 가 되더라도 무시한다.
|
||||
// 본 쓰레드 내에서 계속 재시도 할 수 있도록 한다.
|
||||
// Notify : 해당 함수에서 로깅처리됨
|
||||
|
||||
|
||||
while(1)
|
||||
{
|
||||
// 아래 함수에서 return false 가 되면 기존 세션에대해 정리한 후
|
||||
// DB Connection을 다시 요청한다.
|
||||
if ( DbConnect() == false){;}
|
||||
if( PreserveUpdate() == false )
|
||||
{
|
||||
// 한 번더 정리한 후
|
||||
DbClose();
|
||||
sleep( 1 );
|
||||
continue;
|
||||
}
|
||||
DbClose();
|
||||
sleep( DB_INFORMATION_UPDATE_INTERVAL );
|
||||
}
|
||||
|
||||
// 쓰레드 종료 될 때 DB 세션 정리 한다.
|
||||
DbClose();
|
||||
|
||||
LOG(LERR, "Thread create failed.: errno:%d errmsg:%s", errno, strerror(errno));
|
||||
FUNC_END();
|
||||
}
|
||||
|
||||
void* CPreserveUpdater::EntryPoint(void* arg)
|
||||
{
|
||||
CPreserveUpdater* pObject = reinterpret_cast<CPreserveUpdater *>(arg);
|
||||
pthread_detach( pthread_self() );
|
||||
|
||||
pthread_testcancel();
|
||||
pObject->Execute();
|
||||
pthread_testcancel();
|
||||
|
||||
FUNC_END();
|
||||
return 0;
|
||||
}
|
||||
|
||||
bool CPreserveUpdater::Start()
|
||||
{
|
||||
int nRet = ::pthread_create(&m_threadHandle, 0, CPreserveUpdater::EntryPoint, this);
|
||||
|
||||
if( nRet )
|
||||
{
|
||||
LOG(LERR, "Thread create failed.: errno:%d errmsg:%s", errno, strerror(errno));
|
||||
return false;
|
||||
}
|
||||
LOG(LDBG, "Thread create succeed");
|
||||
sleep(0);
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
/***************************************************************************
|
||||
Replicate Work Class
|
||||
-----------------------------------------
|
||||
begin : 2012/10/14
|
||||
copyright : (C) 2010 SolutionBox Inc.
|
||||
author : Service 1 Team
|
||||
email : svc1@solbox.com
|
||||
version : 1.0
|
||||
|
||||
CopyRight(C) 2010 SolutionBox Inc. All Rights reserved.
|
||||
Redistribution and use in source and binary forms, with or with out
|
||||
modification, are not permitted in outside of SolutionBox Inc.
|
||||
***************************************************************************/
|
||||
|
||||
#ifndef __PRESERVE_UPDATER_THREAD__
|
||||
#define __PRESERVE_UPDATER_THREAD__
|
||||
|
||||
#include <pthread.h>
|
||||
#include <string>
|
||||
#include "Logger.h"
|
||||
#include "Data.h"
|
||||
#include "DataQueue.h"
|
||||
#include "ProcessStatus.h"
|
||||
#include "Database.h"
|
||||
|
||||
/// @brief
|
||||
class CPreserveUpdater
|
||||
{
|
||||
public:
|
||||
/// @brief 생성자
|
||||
/// @param [in] pLogger 로깅을 위한 클래스.
|
||||
CPreserveUpdater();
|
||||
~CPreserveUpdater();
|
||||
|
||||
/// @brief Thread를 생성하고, 이를 시작한다.
|
||||
/// @param none
|
||||
/// @return 성공은 return true 실패는 return false
|
||||
bool Start();
|
||||
|
||||
bool DbConnect();
|
||||
void DbClose();
|
||||
|
||||
/// @brief ProcessStatus 내의 RCDB 관련 설정값을 이용해 DB Connection을 한다.
|
||||
/// @param None
|
||||
/// @return 성공하면 return true 실패하면 return false
|
||||
bool ThreadInit();
|
||||
|
||||
bool PreserveUpdate();
|
||||
|
||||
// Attributes
|
||||
private:
|
||||
DataBase* m_pPgSQL;
|
||||
std::string m_szHost;
|
||||
int m_nPort;
|
||||
std::string m_szDBName;
|
||||
std::string m_szAcct;
|
||||
std::string m_szPasswd;
|
||||
|
||||
// 쓰레드 핸들
|
||||
pthread_t m_threadHandle;
|
||||
|
||||
// 쓰레드 시작 루틴이다.
|
||||
static void* EntryPoint(void* arg);
|
||||
|
||||
// 해당 함수의 내용은 수정하지 말것.
|
||||
void Execute();
|
||||
|
||||
|
||||
};
|
||||
#endif //__PRESERVE_UPDATER_THREAD__
|
||||
@@ -0,0 +1,171 @@
|
||||
|
||||
#include "ProcessStatus.h"
|
||||
#include "Logger.h"
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
|
||||
// static º¯¼ö ÃʱâÈ.
|
||||
CProcessStatus* CProcessStatus::m_pInstance = NULL;
|
||||
|
||||
|
||||
CProcessStatus::CProcessStatus()
|
||||
{
|
||||
m_szAppLogRoot = "";
|
||||
m_nPhysicalDeleteThreadCount = 0;
|
||||
m_szStartPeriod = "";
|
||||
}
|
||||
|
||||
CProcessStatus::~CProcessStatus()
|
||||
{
|
||||
}
|
||||
|
||||
void CProcessStatus::Init()
|
||||
{
|
||||
if( CProcessStatus::m_pInstance == NULL )
|
||||
{
|
||||
CProcessStatus::m_pInstance = new CProcessStatus();
|
||||
}
|
||||
}
|
||||
|
||||
CProcessStatus * CProcessStatus::GetInstance()
|
||||
{
|
||||
return CProcessStatus::m_pInstance;
|
||||
}
|
||||
|
||||
void CProcessStatus::Exit()
|
||||
{
|
||||
if( CProcessStatus::m_pInstance != NULL )
|
||||
{
|
||||
delete CProcessStatus::m_pInstance;
|
||||
CProcessStatus::m_pInstance = NULL;
|
||||
}
|
||||
}
|
||||
|
||||
void CProcessStatus::SetProgramName(std::string szProgramName)
|
||||
{
|
||||
m_szProgramName = szProgramName;
|
||||
}
|
||||
void CProcessStatus::SetProgramVersion(std::string szProgramVersion)
|
||||
{
|
||||
m_szProgramVersion = szProgramVersion;
|
||||
}
|
||||
|
||||
void CProcessStatus::SetLogLevel(unsigned int nLogLevel)
|
||||
{
|
||||
m_nLogLevel = nLogLevel;
|
||||
}
|
||||
|
||||
void CProcessStatus::SetRcdbIp(std::string szRcdbIp)
|
||||
{
|
||||
m_szRcdbIp = szRcdbIp;
|
||||
}
|
||||
void CProcessStatus::SetRcdbPort(int nRcdbPort)
|
||||
{
|
||||
m_nRcdbPort = nRcdbPort;
|
||||
}
|
||||
void CProcessStatus::SetRcdbName(std::string szRcdbName)
|
||||
{
|
||||
m_szRcdbName = szRcdbName;
|
||||
}
|
||||
void CProcessStatus::SetRcdbAcct(std::string szRcdbAcct)
|
||||
{
|
||||
m_szRcdbAcct = szRcdbAcct;
|
||||
}
|
||||
void CProcessStatus::SetRcdbAcctPw(std::string szRcdbAcctPw)
|
||||
{
|
||||
m_szRcdbAcctPw = szRcdbAcctPw;
|
||||
}
|
||||
|
||||
void CProcessStatus::SetAppLogRoot(std::string szAppLogRoot)
|
||||
{
|
||||
m_szAppLogRoot = szAppLogRoot;
|
||||
}
|
||||
|
||||
void CProcessStatus::SetMaxDeleteThread(int nDeletenMaxThreadCount)
|
||||
{
|
||||
m_nDeletenMaxThreadCount = nDeletenMaxThreadCount;
|
||||
}
|
||||
|
||||
void CProcessStatus::SetPreserveList( std::list<CPreserve> listPreserve)
|
||||
{
|
||||
//!! Lock ÇÊ¿ä
|
||||
m_listPreserve = listPreserve;
|
||||
}
|
||||
|
||||
void CProcessStatus::SetStartPeriod(std::string szStartPeriod)
|
||||
{
|
||||
m_szStartPeriod = szStartPeriod;
|
||||
}
|
||||
|
||||
std::string CProcessStatus::GetVectorValues(std::vector<std::string> vecParam)
|
||||
{
|
||||
std::string szResult;
|
||||
szResult.clear();
|
||||
std::vector< std::string >::const_iterator it;
|
||||
|
||||
for( it = vecParam.begin(); it != vecParam.end(); it++ )
|
||||
{
|
||||
if( it != vecParam.begin() )
|
||||
{
|
||||
szResult += ", ";
|
||||
}
|
||||
szResult += *it;
|
||||
}
|
||||
return szResult;
|
||||
}
|
||||
|
||||
void CProcessStatus::LoggingConf()
|
||||
{
|
||||
std::string szResult;
|
||||
|
||||
_LOG( LINF, "***********************************************************" );
|
||||
_LOG( LINF, "%s (Garbage Content Manager Demon) Start . Version : %s", GetProgramName().c_str(), GetProgramVersion().c_str() );
|
||||
_LOG( LINF, "***********************************************************" );
|
||||
|
||||
_LOG( LINF, "Log : %s", GetAppLogRoot().c_str() );
|
||||
_LOG( LINF, "Log Level : %d", GetLogLevel() );
|
||||
_LOG( LINF, "RCDB : %s %d %s %s", GetRcdbIp().c_str()
|
||||
, GetRcdbPort()
|
||||
, GetRcdbName().c_str()
|
||||
, GetRcdbAcct().c_str() );
|
||||
|
||||
_LOG( LINF, "Max Delete Thread Count : %d", GetMaxDeleteThread() );
|
||||
_LOG( LINF, "Start Period : %s", GetStartPeriod().c_str() );
|
||||
_LOG( LINF, "***********************************************************" );
|
||||
}
|
||||
|
||||
|
||||
void CProcessStatus::SetWorkerPid(int nWokerPid)
|
||||
{
|
||||
m_nWokerPid = nWokerPid;
|
||||
}
|
||||
|
||||
bool CProcessStatus::AddJobThreadCount()
|
||||
{
|
||||
pthread_mutex_lock(&m_mxPhysicalDeleteThreadCount);
|
||||
|
||||
if ( m_nPhysicalDeleteThreadCount+1 > m_nDeletenMaxThreadCount )
|
||||
{
|
||||
pthread_mutex_unlock(&m_mxPhysicalDeleteThreadCount);
|
||||
return false;
|
||||
}
|
||||
m_nPhysicalDeleteThreadCount++;
|
||||
pthread_mutex_unlock(&m_mxPhysicalDeleteThreadCount);
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
bool CProcessStatus::SubtractJobThreadCount()
|
||||
{
|
||||
pthread_mutex_lock(&m_mxPhysicalDeleteThreadCount);
|
||||
if ( m_nPhysicalDeleteThreadCount - 1 < 0 )
|
||||
{
|
||||
pthread_mutex_unlock(&m_mxPhysicalDeleteThreadCount);
|
||||
return false;
|
||||
}
|
||||
m_nPhysicalDeleteThreadCount--;
|
||||
pthread_mutex_unlock(&m_mxPhysicalDeleteThreadCount);
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
/***************************************************************************
|
||||
Process Statuis Class
|
||||
-----------------------------------------
|
||||
begin : 2011/11/14
|
||||
copyright : (C) 2005 SolutionBox Inc.
|
||||
author : Service 1 Team
|
||||
email : svc1@solbox.com
|
||||
version : 1.0
|
||||
|
||||
CopyRight(C) 2005 SolutionBox Inc. All Rights reserved.
|
||||
Redistribution and use in source and binary forms, with or with out
|
||||
modification, are not permitted in outside of SolutionBox Inc.
|
||||
***************************************************************************/
|
||||
|
||||
#ifndef _RC_GCMD_PROCESS_STATUS_
|
||||
#define _RC_GCMD_PROCESS_STATUS_
|
||||
|
||||
#include <string.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <list>
|
||||
|
||||
#include "Data.h"
|
||||
|
||||
|
||||
class CProcessStatus
|
||||
{
|
||||
// Attributes
|
||||
private:
|
||||
// Instance
|
||||
static CProcessStatus* m_pInstance;
|
||||
|
||||
|
||||
// common section configure values
|
||||
std::string m_szProgramName;
|
||||
std::string m_szProgramVersion;
|
||||
|
||||
// for DB
|
||||
std::string m_szRcdbIp;
|
||||
int m_nRcdbPort;
|
||||
std::string m_szRcdbName;
|
||||
std::string m_szRcdbAcct;
|
||||
std::string m_szRcdbAcctPw;
|
||||
std::string m_szAppLogRoot;
|
||||
|
||||
std::string m_szStartPeriod;
|
||||
|
||||
unsigned int m_nLogLevel;
|
||||
|
||||
pthread_mutex_t m_mxPhysicalDeleteThreadCount;
|
||||
int m_nPhysicalDeleteThreadCount;
|
||||
|
||||
int m_nDeletenMaxThreadCount;
|
||||
|
||||
std::string GetVectorValues(std::vector<std::string> vecParam);
|
||||
|
||||
|
||||
public:
|
||||
|
||||
/// @brief constructor
|
||||
CProcessStatus();
|
||||
|
||||
/// @brief destructor
|
||||
~CProcessStatus();
|
||||
|
||||
/// @brief 싱글톤 객체 생성
|
||||
static void Init();
|
||||
|
||||
/// @brief 싱글톤 객체 삭제
|
||||
static void Exit();
|
||||
|
||||
/// @brief 싱글톤 객체를 얻는다.
|
||||
static CProcessStatus * GetInstance();
|
||||
|
||||
/// @brief 각 항목의 값들을 로그파일에 기록한다.
|
||||
void LoggingConf();
|
||||
|
||||
//---------------------------------------------------------------------
|
||||
// Configuration values START
|
||||
// common section configure values
|
||||
void SetProgramName(std::string szProgramName);
|
||||
void SetProgramVersion(std::string szProgramVersion);
|
||||
void SetLogLevel(unsigned int nLogLevel);
|
||||
void SetAppLogRoot(std::string szAppLogRoot);
|
||||
|
||||
void SetRcdbIp(std::string vecRcdbIp);
|
||||
void SetRcdbPort(int nRcdbPort);
|
||||
void SetRcdbName(std::string szRcdbName);
|
||||
void SetRcdbAcct(std::string szRcdbAcct);
|
||||
void SetRcdbAcctPw(std::string szRcdbAcctPw);
|
||||
void SetMaxDeleteThread(int nDeletenMaxThreadCount);
|
||||
|
||||
void SetPreserveList( std::list<CPreserve> listPreserve);
|
||||
|
||||
void SetStartPeriod(std::string szStartPeriod);
|
||||
|
||||
bool AddJobThreadCount();
|
||||
bool SubtractJobThreadCount();
|
||||
|
||||
// common section configure values
|
||||
std::string GetProgramName() {return m_szProgramName; }
|
||||
std::string GetProgramVersion() {return m_szProgramVersion; }
|
||||
std::string GetAppLogRoot() {return m_szAppLogRoot; }
|
||||
unsigned int GetLogLevel() { return m_nLogLevel; }
|
||||
|
||||
std::string GetRcdbIp() {return m_szRcdbIp; }
|
||||
int GetRcdbPort() {return m_nRcdbPort; }
|
||||
std::string GetRcdbName() {return m_szRcdbName; }
|
||||
std::string GetRcdbAcct() {return m_szRcdbAcct; }
|
||||
std::string GetRcdbAcctPw() {return m_szRcdbAcctPw; }
|
||||
|
||||
std::string GetStartPeriod() {return m_szStartPeriod; }
|
||||
|
||||
int GetMaxDeleteThread() {return m_nDeletenMaxThreadCount; }
|
||||
int GetDeleteThreadCount() {return m_nPhysicalDeleteThreadCount; }
|
||||
std::list<CPreserve> GetPreserveList() {return m_listPreserve; }
|
||||
// Configuration values END
|
||||
//---------------------------------------------------------------------
|
||||
|
||||
private:
|
||||
int m_nWokerPid;
|
||||
|
||||
std::list<CPreserve> m_listPreserve;
|
||||
|
||||
|
||||
public:
|
||||
void SetWorkerPid(int nWokerPid);
|
||||
int GetWorkerPid(){return m_nWokerPid; }
|
||||
};
|
||||
|
||||
|
||||
#endif //_RC_GCMD_PROCESS_STATUS_
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
#include "Worker.h"
|
||||
|
||||
#include <signal.h>
|
||||
#include <stdlib.h>
|
||||
#include <time.h>
|
||||
|
||||
#include "Logger.h"
|
||||
#include "ProcessRename.h"
|
||||
#include "ProcessStatus.h"
|
||||
#include "PreserveUpdater.h"
|
||||
#include "GetContentListThread.h"
|
||||
#include "DataQueue.h"
|
||||
#include "CategorizeThread.h"
|
||||
#include "PhysicalDeleteThread.h"
|
||||
#include "CompleteThread.h"
|
||||
|
||||
/// @brief Worker Process 의 main 함수
|
||||
int WorkerMain( )
|
||||
{
|
||||
// Set Signal Handler
|
||||
SetSignalWorker();
|
||||
|
||||
// Process Rename..
|
||||
set_ps_display( PROG_NAME": Worker", false );
|
||||
|
||||
|
||||
//-- singleton 객체들을 모두 생성 하도록 한다.
|
||||
//0. 명시적으로 처리하기 위해서..
|
||||
// Global
|
||||
CQueue<CFileInfo> queueFileInfo;
|
||||
queueFileInfo.SetCurrentMaxSize(10000);
|
||||
|
||||
CQueue<CFileInfo> queueDeleteJob;
|
||||
queueFileInfo.SetCurrentMaxSize(10000);
|
||||
|
||||
CQueue<CFileInfo> queueCompleteJob;
|
||||
queueFileInfo.SetCurrentMaxSize(10000);
|
||||
|
||||
// 1. 각 전역 변수 초기화 및 관련 Thread 기동 처리
|
||||
//-- 각 객체에 대해 초기화 및 시작 할 수 있는지 먼저 확인한다.
|
||||
CPreserveUpdater objPreserveUpdater;
|
||||
if ( objPreserveUpdater.ThreadInit() == false )
|
||||
{
|
||||
LOG( LERR, "CPreserveUpdater initialize failed." );
|
||||
exit( EXIT_FAILURE ); // EXIT_FAILURE 를 반환하여 재생성 처리 방지.
|
||||
}
|
||||
|
||||
CGetContentListThread objContentList(&queueFileInfo, &queueDeleteJob, &queueCompleteJob);
|
||||
if ( objContentList.ThreadInit() == false )
|
||||
{
|
||||
LOG( LERR, "CGetContentListThread initialize failed." );
|
||||
exit( EXIT_FAILURE ); // EXIT_FAILURE 를 반환하여 재생성 처리 방지.
|
||||
}
|
||||
|
||||
CCategorizeThread objCategorize(&queueFileInfo, &queueDeleteJob, &queueCompleteJob);
|
||||
if ( objCategorize.ThreadInit() == false )
|
||||
{
|
||||
LOG( LERR, "CCategorizeThread initialize failed." );
|
||||
exit( EXIT_FAILURE ); // EXIT_FAILURE 를 반환하여 재생성 처리 방지.
|
||||
}
|
||||
|
||||
CCompleteThread objCompleteThread(&queueCompleteJob);
|
||||
if ( objCompleteThread.ThreadInit() == false )
|
||||
{
|
||||
LOG( LERR, "CCategorizeThread initialize failed." );
|
||||
exit( EXIT_FAILURE ); // EXIT_FAILURE 를 반환하여 재생성 처리 방지.
|
||||
}
|
||||
|
||||
//-- 각 객체에 대해 검증이 끝났으므로 각 쓰레드를 구동 시킨다.
|
||||
if( objPreserveUpdater.Start() == false )
|
||||
{
|
||||
LOG( LERR, "Worker[%d]: CPreserveUpdater Start() failed. => Worker Exit", getpid() );
|
||||
exit( EXIT_FAILURE ); // EXIT_FAILURE 를 반환하여 재생성 처리 방지.
|
||||
}
|
||||
|
||||
if( objContentList.Start() == false )
|
||||
{
|
||||
LOG( LERR, "Worker[%d]: CGetContentListThread Start() failed. => Worker Exit", getpid() );
|
||||
exit( EXIT_FAILURE ); // EXIT_FAILURE 를 반환하여 재생성 처리 방지.
|
||||
}
|
||||
|
||||
if( objCategorize.Start() == false )
|
||||
{
|
||||
LOG( LERR, "Worker[%d]: CGetContentListThread Start() failed. => Worker Exit", getpid() );
|
||||
exit( EXIT_FAILURE ); // EXIT_FAILURE 를 반환하여 재생성 처리 방지.
|
||||
}
|
||||
|
||||
if( objCompleteThread.Start() == false )
|
||||
{
|
||||
LOG( LERR, "Worker[%d]: CGetContentListThread Start() failed. => Worker Exit", getpid() );
|
||||
exit( EXIT_FAILURE ); // EXIT_FAILURE 를 반환하여 재생성 처리 방지.
|
||||
}
|
||||
|
||||
// Job Control.....
|
||||
while(1)
|
||||
{
|
||||
CFileInfo objDelFileInfo;
|
||||
_LOG(LDBG , "DeleteThreadCount[Max: %d, Cur: %d]", CProcessStatus::GetInstance()->GetMaxDeleteThread(), CProcessStatus::GetInstance()->GetDeleteThreadCount() ) ;
|
||||
|
||||
if( CProcessStatus::GetInstance()->GetDeleteThreadCount() >= CProcessStatus::GetInstance()->GetMaxDeleteThread())
|
||||
{
|
||||
sleep(1);
|
||||
continue;
|
||||
}
|
||||
if( queueDeleteJob.GetSize() <= 0 )
|
||||
{
|
||||
LOG(LDBG, "DeleteJobQueue is Empty...");
|
||||
sleep(1);
|
||||
continue;
|
||||
}
|
||||
// 1. QueuePop
|
||||
objDelFileInfo = queueDeleteJob.Front();
|
||||
// Front 는 참조만하고 실제 pop은 Pop() 함수를 통해 한다.
|
||||
queueDeleteJob.Pop();
|
||||
|
||||
CPhysicalDeleteThread* pPhysicalDeleteTrhead = new CPhysicalDeleteThread(objDelFileInfo, &queueCompleteJob);
|
||||
// 쓰레드 수 증가.
|
||||
|
||||
if( pPhysicalDeleteTrhead == NULL || pPhysicalDeleteTrhead->Start() == false )
|
||||
{
|
||||
LOG( LERR, "Worker[%d]: CPhysicalDeleteThread Start() failed. => Worker Exit", getpid() );
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// 생성된 Thread 의 Join 처리 ???
|
||||
while( 1 )
|
||||
{
|
||||
// 그냥 시그널 대기
|
||||
pause();
|
||||
}
|
||||
|
||||
// Process 종료 처리.
|
||||
LOG( LWAR, "Worker Process[%d] exit.. Good Bye..", getpid());
|
||||
|
||||
CLogger::Exit();
|
||||
CProcessStatus::Exit();
|
||||
|
||||
//잠시 대기 후 종료처리.
|
||||
// CHG 2015-09-22 webting
|
||||
// - #24369 usleep -> nanosleep 으로 변경 처리.
|
||||
struct timespec sleep;
|
||||
sleep.tv_sec = 0;
|
||||
sleep.tv_nsec = 500000000; // 0.5 sec
|
||||
nanosleep( &sleep, NULL );
|
||||
// exit( EXIT_SUCCESS );
|
||||
|
||||
return EXIT_SUCCESS; // fork 를 수행한 함수에서 exit 함수 호출을 통한 종료처리
|
||||
}
|
||||
|
||||
/// @brief Worker Process 종료 Signal 을 전달받은 경우 이를 처리하기 위한 함수.
|
||||
/// @param nSignalNumber [in] 발생한 시그널 Number
|
||||
/// @return void
|
||||
static void SigTermWorker( int nSignalNumber )
|
||||
{
|
||||
// Signal Number 에 따른 로깅처리.
|
||||
if( nSignalNumber == SIGTERM )
|
||||
{
|
||||
LOG( LWAR, "Worker Process[%d] exit job start by user signal [SIGTERM]", getpid() );
|
||||
}
|
||||
else
|
||||
{
|
||||
LOG( LWAR, "Worker Process[%d] exit job start by abnormal signal [%d]", getpid(), nSignalNumber );
|
||||
}
|
||||
|
||||
LOG( LWAR, "Worker Process[%d] exit job end. Good Bye..", getpid());
|
||||
|
||||
|
||||
// CHG 2015-09-22 webting
|
||||
// - #24369 usleep -> nanosleep 으로 변경 처리.
|
||||
struct timespec sleep;
|
||||
sleep.tv_sec = 0;
|
||||
sleep.tv_nsec = 500000000; // 0.5 sec
|
||||
nanosleep( &sleep, NULL );
|
||||
exit( EXIT_SUCCESS );
|
||||
}
|
||||
|
||||
|
||||
/// @brief Worker 프로세스 signal 처리 설정을 위한 함수
|
||||
/// @return void
|
||||
void SetSignalWorker( void )
|
||||
{
|
||||
sigset_t set;
|
||||
struct sigaction act;
|
||||
|
||||
sigfillset( &set );
|
||||
sigprocmask( SIG_SETMASK, &set, NULL );
|
||||
|
||||
memset( &act, 0x00, sizeof(act) );
|
||||
sigfillset( &act.sa_mask );
|
||||
|
||||
/* 무시할 신호 목록 */
|
||||
act.sa_handler = SIG_IGN;
|
||||
sigaction( SIGPIPE, &act, NULL); /* 파이프 디스크립터 오류 발생시 Process가 죽는 것은 방지하기 위하여 설정 */
|
||||
sigaction( SIGHUP , &act, NULL); /* Process를 기동시킨 관리자의 로그아웃시 발생 시그널 */
|
||||
sigaction( SIGINT , &act, NULL); /* ^C 키를 누른 경우 받는 신호 => demon 으로 기동되기 땜시 이 신호 못받음 */
|
||||
sigaction( SIGQUIT, &act, NULL); /* 키보드에 의한 Abort 신호 처리 => ? */
|
||||
|
||||
// Worker 프로세스는 자식 프로세스가 존재하지 않으므로 그냥 무시처리함.
|
||||
//act.sa_handler = SigChldWorker;
|
||||
sigaction( SIGCHLD, &act, NULL);
|
||||
|
||||
/* 각종 에러나 사용자의 종료 신호 처리 */
|
||||
act.sa_handler = SigTermWorker;
|
||||
sigaction( SIGTERM, &act, NULL); /* kill -TERM 에 의한 프로세스 종료시 */
|
||||
|
||||
sigemptyset(&set); /* 신호 처리기 처리 설정 위한 블록 해제 */
|
||||
sigprocmask(SIG_SETMASK, &set, NULL);
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
/***************************************************************************
|
||||
rc_gcmd Header ( Worker.h )
|
||||
-----------------------------------------
|
||||
begin : 2012/10/12
|
||||
copyright : (C) 2005 SolutionBox Inc.
|
||||
author : Service 1 Team
|
||||
email : svc1@solbox.com
|
||||
version : 1.0
|
||||
|
||||
CopyRight(C) 2005 SolutionBox Inc. All Rights reserved.
|
||||
Redistribution and use in source and binary forms, with or with out
|
||||
modification, are not permitted in outside of SolutionBox Inc.
|
||||
***************************************************************************/
|
||||
|
||||
#ifndef __WORKER_PROCESS_H__
|
||||
#define __WORKER_PROCESS_H__
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/// @brief Worker Process 의 main 함수
|
||||
/// @return
|
||||
int WorkerMain( void );
|
||||
|
||||
/// @brief Worker 프로세스 signal 처리 설정을 위한 함수
|
||||
/// @return void
|
||||
void SetSignalWorker( void );
|
||||
|
||||
/* Signal 처리를 위한 각 Signal Handler 함수는
|
||||
* 다른 Code 에서 Include 처리시 Static 관련 문제로 인해
|
||||
* 본 Header 에서 선언처리 하지 않음. cpp 에만 존재
|
||||
*/
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* __WORKER_PROCESS_H__ */
|
||||
|
||||
|
||||
@@ -0,0 +1,462 @@
|
||||
/***************************************************************************
|
||||
main.cpp
|
||||
-----------------------------------------
|
||||
begin : 2012/10/12
|
||||
copyright : (C) 2005 SolutionBox Inc.
|
||||
author : Service 1 Team
|
||||
email : svc1@solbox.com
|
||||
version : 1.0
|
||||
|
||||
CopyRight(C) 2005 SolutionBox Inc. All Rights reserved.
|
||||
Redistribution and use in source and binary forms, with or with out
|
||||
modification, are not permitted in outside of SolutionBox Inc.
|
||||
***************************************************************************/
|
||||
|
||||
#include <unistd.h>
|
||||
#include <errno.h>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <signal.h>
|
||||
#include <sys/wait.h>
|
||||
#include <time.h>
|
||||
|
||||
#include "Logger.h"
|
||||
#include "Config.h"
|
||||
#include "ProcessRename.h"
|
||||
#include "ProcessStatus.h"
|
||||
#include "Worker.h"
|
||||
#include "GcmdConfig.h"
|
||||
|
||||
using namespace std;
|
||||
|
||||
/// @brief std 상에 trim 함수가 없어서 직접 구현 아니면 boost/algorithm/string.hpp 상의 boost::trim 함수 사용
|
||||
/// @return void
|
||||
void Trim( string & str )
|
||||
{
|
||||
if( str.length() == 0 )
|
||||
return ;
|
||||
|
||||
// 문자열 뒤의 공백, TAB, CR 등의 문자 제거처리.
|
||||
string::size_type pos = str.find_last_not_of(" \a\b\f\n\r\t\v");
|
||||
if( pos != string::npos )
|
||||
str.erase( pos + 1 );
|
||||
|
||||
// 문자열 앞의 공백, TAB, CR 등의 문자 제거처리.
|
||||
pos = str.find_first_not_of(" \a\b\f\n\r\t\v");
|
||||
if( pos != string::npos )
|
||||
str.erase( 0, pos );
|
||||
}
|
||||
|
||||
|
||||
// 프로세스 종료 전 처리할 종료 관련 각 작업을 일괄로 처리하기 위한 함수.
|
||||
void ReadyToExit()
|
||||
{
|
||||
// 프로세스 상태 모듈 종료 처리.
|
||||
CProcessStatus::Exit();
|
||||
|
||||
// Logger 객체 종료 처리.
|
||||
CLogger::Exit();
|
||||
}
|
||||
|
||||
|
||||
/// @brief 현재 Process가 기동중인지 여부를 판단하기 위한 함수( 프로세스 중복 실행 체크)
|
||||
/// @return 이미 해당 프로세스가 기동 중인 경우 true 반환, 그렇지 않으면 false 반환.
|
||||
bool IsCurrentProcessRun()
|
||||
{
|
||||
char tempBuffer[512];
|
||||
FILE * fd = NULL;
|
||||
bool bRun = false;
|
||||
|
||||
snprintf( tempBuffer, sizeof(tempBuffer), "pgrep -x %s | sort", PROG_NAME );
|
||||
|
||||
fd = popen( tempBuffer, "r" );
|
||||
if( fd == NULL )
|
||||
{
|
||||
cerr << "[error] Process duplication check failed.[popen error][" << strerror(errno) << "]" << endl;
|
||||
|
||||
// 오류 발생시 true 반환하여 프로세스 실행 방지처리
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
memset( tempBuffer, 0x00, sizeof(tempBuffer) );
|
||||
while( fgets( tempBuffer, sizeof(tempBuffer)-1, fd) != NULL )
|
||||
{
|
||||
string tempPid( tempBuffer );
|
||||
Trim(tempPid);
|
||||
|
||||
if( atoi( tempPid.c_str() ) != getpid() )
|
||||
{
|
||||
cout << "[info] Process duplication found. pid[" << atoi( tempPid.c_str() ) << "]" << endl;
|
||||
|
||||
bRun = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
pclose( fd );
|
||||
return bRun;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// @brief Main Process 종료 Signal 을 전달받은 경우 이를 처리하기 위한 함수.
|
||||
/// @param nSignalNumber [in] 발생한 시그널 Number
|
||||
/// @return void
|
||||
static void SignalMainTerminate( int nSignalNumber )
|
||||
{
|
||||
// Signal Number 에 따른 로깅처리.
|
||||
if( nSignalNumber == SIGTERM )
|
||||
{
|
||||
LOG(LWAR,"Main Process[%d] exit job start by user signal [SIGTERM]", getpid());
|
||||
}
|
||||
else
|
||||
{
|
||||
LOG(LWAR, "Main Process[%d] exit job start by abnormal signal [%d]", getpid(), nSignalNumber);
|
||||
}
|
||||
|
||||
// Process 종료관련 작업 추가
|
||||
LOG(LWAR, "Main Process[%d] exit job end. Good Bye..", getpid());
|
||||
|
||||
// CHG 2015-09-22 webting
|
||||
// - #24369 usleep -> nanosleep 으로 변경 처리.
|
||||
struct timespec sleep;
|
||||
sleep.tv_sec = 0;
|
||||
sleep.tv_nsec = 500000000; // 0.5 sec
|
||||
nanosleep( &sleep, NULL );
|
||||
|
||||
exit( EXIT_SUCCESS );
|
||||
}
|
||||
|
||||
|
||||
/// @brief Worker Process 생성(fork) 처리 함수
|
||||
/// @return 생성 성공시 true, 실패시에는 false 를 반환.
|
||||
bool MakeProcessWorker()
|
||||
{
|
||||
pid_t processId;
|
||||
|
||||
// Worker 프로세스 fork
|
||||
processId = fork();
|
||||
if( processId < 0 ) // Fork fail
|
||||
{
|
||||
int errorNum = errno;
|
||||
LOG(LERR, "Worker Process create failed. [%d][%s]", errorNum, strerror(errorNum) );
|
||||
return false;
|
||||
}
|
||||
else if( processId == 0 ) // Child Process => Worker Process
|
||||
{
|
||||
int iResult;
|
||||
|
||||
|
||||
// Worker Process Main 함수 호출 및 종료처리.
|
||||
iResult = WorkerMain();
|
||||
|
||||
ReadyToExit();
|
||||
|
||||
exit( iResult );
|
||||
}
|
||||
else
|
||||
{
|
||||
CProcessStatus::GetInstance()->SetWorkerPid((int)processId);
|
||||
// Parent Process => Logging
|
||||
LOG(LNOT, "Worker Process create success. PID[%d]" , processId);
|
||||
|
||||
// 잠시 대기
|
||||
// CHG 2015-09-22 webting
|
||||
// - #24369 usleep -> nanosleep 으로 변경 처리.
|
||||
struct timespec sleep;
|
||||
sleep.tv_sec = 0;
|
||||
sleep.tv_nsec = 100000000; // 0.1 sec
|
||||
nanosleep( &sleep, NULL );
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
static void SignalWorkerDead( int nSignalNumber )
|
||||
{
|
||||
pid_t killPid;
|
||||
int nKillStatus;
|
||||
|
||||
while( ( killPid = waitpid( -1, &nKillStatus, WNOHANG ) ) > 0 )
|
||||
{
|
||||
// 자식 프로세스가 Signal 에 의해 종료되었는지 검사.
|
||||
if( WIFSIGNALED( nKillStatus ) )
|
||||
{
|
||||
LOG(LWAR, "Worker process[%d] killed by signal[%d]", killPid, WTERMSIG( nKillStatus ) );
|
||||
}
|
||||
else
|
||||
{
|
||||
LOG(LWAR, "Worker process[%d] killed. Not signal", killPid );
|
||||
|
||||
// Worker 프로세스가 EXIT_FAILURE 반환 ( 초기화 실패시 )
|
||||
// 해당 내역을 화면 및 로그 상에 출력하고
|
||||
// 자식 프로세스를 재생성 처리하지 않는다.
|
||||
|
||||
if( WIFEXITED( nKillStatus ) )
|
||||
{
|
||||
if( WEXITSTATUS( nKillStatus ) == EXIT_FAILURE )
|
||||
{
|
||||
LOG(LERR, "Worker Process[%d] initilaize failed.", killPid );
|
||||
LOG(LERR, "Main Process[%d] exit by worker. Good Bye..", getpid());
|
||||
|
||||
cerr << "[error] " << PROG_NAME << ": Process exit by worker process initialize failed. check log file." << endl;
|
||||
|
||||
ReadyToExit();
|
||||
|
||||
// CHG 2015-09-22 webting
|
||||
// - #24369 usleep -> nanosleep 으로 변경 처리.
|
||||
struct timespec sleep;
|
||||
sleep.tv_sec = 0;
|
||||
sleep.tv_nsec = 500000000; // 0.5 sec
|
||||
nanosleep( &sleep, NULL );
|
||||
|
||||
exit( EXIT_SUCCESS );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Worker Process 재생성 처리.
|
||||
if( MakeProcessWorker() == false )
|
||||
{
|
||||
// Worker Process 재성성 실패시 => 그냥 로깅
|
||||
LOG(LERR, "Worker process recreate failed.");
|
||||
}
|
||||
else
|
||||
{
|
||||
LOG(LNOT, "Worker process recreate success by SIGCHLD");
|
||||
}
|
||||
}
|
||||
|
||||
// 오류 발생시 해당 내역 로깅
|
||||
if( killPid < 0 )
|
||||
{
|
||||
int errorNum = errno;
|
||||
LOG(LERR, "Main process error: SIG_CHLD receive but waitpid return error[%d][%s]", errorNum, strerror(errorNum));
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
/// @brief Main 프로세스 signal 처리 설정을 위한 함수
|
||||
/// @return void
|
||||
void SetSignalMain()
|
||||
{
|
||||
sigset_t set;
|
||||
struct sigaction act;
|
||||
|
||||
memset( &act, 0x00, sizeof( act ) );
|
||||
sigfillset( &set );
|
||||
sigprocmask( SIG_SETMASK, &set, NULL );
|
||||
sigfillset( &act.sa_mask );
|
||||
|
||||
// 무시 처리 signal
|
||||
act.sa_handler = SIG_IGN;
|
||||
sigaction( SIGPIPE, &act, NULL); /* 파이프 디스크립터 오류 발생시 Process가 죽는 것은 방지하기 위하여 설정 */
|
||||
sigaction( SIGHUP , &act, NULL); /* Process를 기동시킨 관리자의 로그아웃시 발생 시그널 */
|
||||
sigaction( SIGINT , &act, NULL); /* ^C 키를 누른 경우 받는 신호 => demon 으로 기동되기 땜시 이 신호 못받음 */
|
||||
sigaction( SIGQUIT, &act, NULL); /* 키보드에 의한 Abort 신호 처리 => ? */
|
||||
|
||||
// Worker child process 종료에 대한 처리기 설정.
|
||||
act.sa_handler = SignalWorkerDead;
|
||||
sigaction( SIGCHLD, &act, NULL);
|
||||
|
||||
// 사용자의 종료 또는 에러 관련 신호 처리.
|
||||
act.sa_handler = SignalMainTerminate;
|
||||
sigaction( SIGTERM, &act, NULL); /* kill -TERM 에 의한 프로세스 종료시 */
|
||||
|
||||
sigemptyset(&set); /* 신호 처리기 처리 설정 위한 블록 해제 */
|
||||
sigprocmask(SIG_SETMASK, &set, NULL);
|
||||
}
|
||||
|
||||
|
||||
|
||||
// 버전 정보 표시
|
||||
void PrintVersion()
|
||||
{
|
||||
fprintf( stderr, "\n" );
|
||||
fprintf( stderr, PROG_NAME " version: " PROG_VERSION "\n\n" );
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// 사용방법 표시
|
||||
void PrintUsage()
|
||||
{
|
||||
fprintf( stderr, "\n" );
|
||||
fprintf( stderr, "Usage: " PROG_NAME " [-h] [-v] [-c {file}] [-s yyyymmdd] \n" );
|
||||
fprintf( stderr, "Options: \n" );
|
||||
fprintf( stderr, " -h Display help information \n" );
|
||||
fprintf( stderr, " -v Display version \n" );
|
||||
fprintf( stderr, " -c {file} Use {file} as config file \n" );
|
||||
fprintf( stderr, " -s yyyymmdd Set start date (ex: -s 20160518) \n" );
|
||||
|
||||
fprintf( stderr, "\n" );
|
||||
fprintf( stderr, PROG_NAME " is Solbox Cloud Storage module.\n" );
|
||||
fprintf( stderr, " - deleted content and folder check. \n" );
|
||||
fprintf( stderr, " - delete physical files, folder that exceed the retention period.\n" );
|
||||
fprintf( stderr, "\n" );
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
// CHG 2016-05-18 유희곤
|
||||
// - help 처리 관련 기능 추가 (#27605)
|
||||
// - 유효하지 않는 기능, 변수 정리.
|
||||
// - 전반적으로 main 프로세스 구조 정리...
|
||||
int main( int argc, char * argv[] )
|
||||
{
|
||||
std::string szConfFilename = DEFAULT_CONFIG_FILE;
|
||||
std::string szStartPeriod = "";
|
||||
|
||||
// linux 에서 프로세스를 Titile 변경을 지원을 위해서 argv 메모리에 저장
|
||||
argv = save_ps_display_args( argc, argv );
|
||||
|
||||
|
||||
// 전달 받은 옵션 여부 확인 및 처리
|
||||
if( argc >= 2 )
|
||||
{
|
||||
int opt;
|
||||
while( (opt = getopt( argc, argv, "hvc:s:" )) != -1 ) // 옵션 끝까지 파싱처리
|
||||
{
|
||||
switch( opt )
|
||||
{
|
||||
case 'h':
|
||||
case '?': // 정의되지 않은 문자가 나타날 경우 getopt 에 자동반환. 도움말 표시 처리.
|
||||
PrintUsage();
|
||||
return EXIT_SUCCESS;
|
||||
|
||||
case 'v':
|
||||
PrintVersion();
|
||||
return EXIT_SUCCESS;
|
||||
|
||||
case 'c':
|
||||
szConfFilename = optarg;
|
||||
fprintf( stderr, PROG_NAME " use user define conf[%s]\n", szConfFilename.c_str() );
|
||||
break;
|
||||
|
||||
case 's':
|
||||
szStartPeriod = optarg;
|
||||
break;
|
||||
|
||||
default: // 본 조건절은 getopt 특성상 동작하지 않지만...업무 Flow 이해(?)를 위해 유지한다.
|
||||
fprintf( stderr, "Unknown options[%c] used. program terminated.\n\n", opt );
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 사용자 Start 지정 옵션 검증.
|
||||
if( szStartPeriod.length() > 0 )
|
||||
{
|
||||
// 사용자가 -s 옵션을 사용하여 start 날짜를 지정한 경우...
|
||||
|
||||
// 날짜 길이값이 부정확한 경우...
|
||||
if( szStartPeriod.length() != 8 )
|
||||
{
|
||||
fprintf( stderr, PROG_NAME " terminated. -s %s format not vaild. use -s yyyymmdd format. \n\n", szStartPeriod.c_str() );
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
|
||||
// 설정값이 모두 숫자이어야 함.
|
||||
for( unsigned int i = 0; i < szStartPeriod.length(); i++ )
|
||||
{
|
||||
char ch = szStartPeriod.at( i );
|
||||
|
||||
if( ch < 48 || ch > 57 )
|
||||
{
|
||||
fprintf( stderr, PROG_NAME " terminated. -s %s format not vaild. use -s yyyymmdd format. \n\n", szStartPeriod.c_str() );
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
}
|
||||
|
||||
fprintf( stderr, PROG_NAME " use uer define start time [%s]\n", szStartPeriod.c_str() );
|
||||
}
|
||||
|
||||
|
||||
|
||||
// 프로그램 중복 실행 체크
|
||||
if( IsCurrentProcessRun() == true )
|
||||
{
|
||||
fprintf( stderr, "[warning] Process [" PROG_NAME "] is already running....\n" );
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
|
||||
|
||||
// process status Singleton 객체 생성.
|
||||
CProcessStatus::Init();
|
||||
CProcessStatus::GetInstance()->SetStartPeriod(szStartPeriod);
|
||||
|
||||
|
||||
// conf 파일 로드 및 항목별 검증
|
||||
// - 내부적으로 설정 관련 값을 CProcessStatus 객체에 저장토록 되어 있음.
|
||||
CGcmdConfig objConf(szConfFilename, PROG_NAME, PROG_VERSION );
|
||||
if ( objConf.LoadConfig() == false )
|
||||
{
|
||||
fprintf( stderr, "[ERR] %s\n\n", objConf.GetErrorMessage().c_str() );
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
|
||||
|
||||
// Log 객체 생성
|
||||
if( CLogger::Init( PROG_NAME, CProcessStatus::GetInstance()->GetAppLogRoot(), LINF ) == false )
|
||||
{
|
||||
fprintf( stderr, "[ERR] Log module initialize failed.[%s]\n\n", CProcessStatus::GetInstance()->GetAppLogRoot().c_str() );
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
|
||||
// Daemonize...
|
||||
if( daemon( 1, 0 ) == -1 ) // nochdir: true(작업 디렉토리 변경 안함), noclose: false (표준 입출력, 에러를 /dev/null 로 리디렉트 처리)
|
||||
{
|
||||
fprintf( stderr, "[ERR] Process daemonize failed.[%s]\n\n", strerror( errno ) );
|
||||
|
||||
ReadyToExit();
|
||||
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
|
||||
// Signal 처리기 설정
|
||||
SetSignalMain();
|
||||
|
||||
// 기동시 설정 정보 관련 로깅
|
||||
CProcessStatus::GetInstance()->LoggingConf();
|
||||
|
||||
|
||||
// Log Level 재설정. -> conf 설정대로 변경 처리.
|
||||
#ifdef _DEBUG_
|
||||
CLogger::GetInstance()->SetLogLevel( LDBG );
|
||||
#else
|
||||
CLogger::GetInstance()->SetLogLevel( CProcessStatus::GetInstance()->GetLogLevel() );
|
||||
#endif
|
||||
|
||||
|
||||
// Worker Process 생성
|
||||
if( MakeProcessWorker() == false )
|
||||
{
|
||||
LOG(LERR, "Worker process make failed. => Main process exit. Good Bye.");
|
||||
cerr << "Worker process make failed. => Main process exit. Good Bye." << endl;
|
||||
|
||||
ReadyToExit();
|
||||
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
|
||||
|
||||
// Process Rename..
|
||||
set_ps_display( PROG_NAME": Main", false );
|
||||
|
||||
|
||||
// Main Process : 그냥 대기
|
||||
while( 1 )
|
||||
{
|
||||
// Main Process 는 할 일이 없다.
|
||||
// => Worker 프로세스 종료시 SIGCHLD 신호로 인해 신호처리기에서 Worker Process 재성성 수행함.
|
||||
// => 따라서 그냥 시그널 대기
|
||||
pause();
|
||||
}
|
||||
|
||||
// 다음의 코드는 Daemon 으로 동작하기 때문에 수행되지 않는다.
|
||||
ReadyToExit();
|
||||
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
Reference in New Issue
Block a user