base
This commit is contained in:
@@ -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