You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

604 lines
23 KiB

//----------------------------------------------------------------------------
// Dr.Frucht Systems Ltd.
// Copyright © 2000-2022. All Rights Reserved.
// Version 1.0 11/19/2022
// Last modification: 11/19/2022
// PROJECT:
// SUBSYSTEM:
// FILE: mojoKernel.cpp
// AUTHOR: gagua
// OVERVIEW
// ~~~~~~~~
// LRF_Kernel.cpp
//----------------------------------------------------------------------------
//
#include "servaKernel.h"
#include "../data/json/json_tool.h"
#include <strings.h>
#include <sys/time.h>
#include <time.h>
#include <json/value.h>
#include <json/writer.h>
#include <json/reader.h>
//#include "../common/kernelEventFilterAPF.h"
//#include "../common/kernelEventFilterTrain.h"
//#include "../common/kernelModuleEmbedVideo.h"
#include "../common/serverMySQL_dataBinder.h"
#include "servaModBusManager.h"
#define LOG( X ) kernelPrototype::m_pLog->Log( "KRNL", this, X )
#ifdef DEBUG
#define LOG_ERROR( X ) {\
char _tBfrErrMSG234[256];\
sprintf( _tBfrErrMSG234, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\
kernelPrototype::m_pLog->Log( "KRNL", this, _LOG_ERROR, _tBfrErrMSG234 );\
}
#else
#define LOG_ERROR( X ) kernelPrototype::m_pLog->Log( "KRNL", this, _LOG_ERROR, X );
#endif
servaKernel *servaKernel::_instance = NULL;
servaKernel *servaKernel::getInstance( config_setting_t *ptr ){
if ( _instance == NULL ) {
_instance = new servaKernel( ptr );
};
return _instance;
};
servaKernel::servaKernel( config_setting_t *ptr ):kernelPrototype( ptr ){
//m_pEventHeap = basicEventHeap::getInstance();
// memset( &m_sSysInfo, 0, sizeof( DBC_SYS_LOAD_INFO ));
//m_pShadow = NULL;
//m_pSystemAnchor = NULL;
// m_bSessionStarted = false;
// m_bWorkWithRemoteServer = false;
// m_bKeepLocalReport = true;
// m_bMediaMode = 0;
m_pLifeMonitor = servaLifeMonitoring::getInstance();
m_pSM = NULL;
m_pRPC = NULL;//??
m_pModBus = NULL;
memset( &m_sServaConfig, 0, sizeof( DBC_SERVA_CONFIG ));
setWM( WM_NONE );
};
servaKernel::~servaKernel(){
WaitFinish( true );
//stopSession( false );
//while(1){
// char tB[200];
// sprintf( tB, "[%d] Seconds Till System Restart", timeout );
// LOG( "BopBop!" );
// SLEEP(1000);
//};
if ( m_pModBus ) {
delete( (servaModBusManager *) m_pModBus );
};
#ifdef LINUX_KERNEL_WATCHDOG
LOG("Disable WD!");
if( m_iWatchdogFd > -1 ) {
char tB[64];
sprintf( tB, "-1\n" );
//ToDo: Make Error Handling here!
write( m_iWatchdogFd, &tB, strlen( tB ) );
};
LOG("WatchDog turned Off!");
#endif
_instance = NULL;
};
bool servaKernel::create(){
if( m_pSettings != NULL ) {
config_setting_t * pSetting;
int tVal;
const char * tBuf;
char tBuffer[128];
LOG("Getting Settings ...");
/*if( !config_setting_lookup_string( m_pSettings, MOJO_KERNEL_TAG_SERVER_IDENTITY, &tBuf ) ){
char * tVar;
char * tTS;
tTS = getTStr(NULL);
tVar = MD5String(tTS);
free(tTS);
sprintf( m_sIdentity, tVar );
pSetting = config_setting_add( m_pSettings, MOJO_KERNEL_TAG_SERVER_IDENTITY, CONFIG_TYPE_STRING );
config_setting_set_string( pSetting, tVar );
free( tVar );
basicSettingsProvider::getInstance()->compromise();
LOG("Server Identity not defined - generating new!");
} else {
sprintf( m_sIdentity, tBuf );
sprintf( tBuffer, "Server Identity Read From Settings: %s", tBuf );
LOG( tBuffer );
};
if( !config_setting_lookup_int( m_pSettings, MOJO_KERNEL_TAG_SITE_ID, &tVal ) ){
tVal = m_nInstanceID = 1;
pSetting = config_setting_add( m_pSettings, MOJO_KERNEL_TAG_SITE_ID, CONFIG_TYPE_INT );
config_setting_set_int( pSetting, tVal );
basicSettingsProvider::getInstance()->compromise();
LOG("Site ID not defined - using [1] as number!");
} else {
m_nInstanceID = tVal;
sprintf( tBuffer, "App Instance ID Read From Settings: %d", m_nInstanceID );
LOG( tBuffer );
};*/
basicSettingsProvider::getInstance()->validate();
} else {
LOG_ERROR("Failed Read Config Settings!");
return false;
};
LOG("Register Server ... ");
registerServA();
m_pSM = servaSessionManager::getInstance( m_pSettings );
if ( m_pSM ){
cleanUpMess();
if ( m_pSM->create() ) {
LOG("Session Manager Created");
servaModBusManager * tModBus = servaModBusManager::getInstance();
if( tModBus ){
LOG("Have ModBus Instance");
if( tModBus->create() ){
LOG("Modbus Created");
m_pModBus = (void *) tModBus;
} else delete( tModBus );
};
/* Test Composer */
//servaVideoComposer *tVC = new servaVideoComposer( 49 );
//if ( tVC ) {
// tVC->compose();
//};
m_pRPC = servaRemoteClient::getInstance(this);
if ( m_pRPC ) {
if( m_pRPC->start() ) return init();
};
};
};
return false;
};
void servaKernel::m_fThreadProc( void ){
time_t tTimeTSeconds = 0;
time_t cTimeTSeconds = 0;
m_bThreadStatus = TH_WORKING;
LOG("ServA Started!");
while ( m_bThreadStatus < TH_ENDED ) {
if( DBC_RPC_WEB_CMD * tCMD = m_pDBC->fetchWebCmd( 0 ) ) {
m_pDBC->updateWebCmdStatus( tCMD->id, DBC_CMD_STARTED );
switch( tCMD->cmd ){
case CMD_KRNL_RELOAD:{
LOG("Reload ServA Node!");
m_bThreadStatus = TH_ENDED;
setExitCause( EXIT_CODE_RELOAD_SERVICES );
break;
};
case CMD_KRNL_RESTART:{
LOG("Restart ServA Node!");
m_bThreadStatus = TH_ENDED;
setExitCause( EXIT_CODE_KERNEL_CLEAR );
break;
};
case CMD_KRNL_FACTORY_RESET:{
LOG("Restart ServA -> Factory Reset!");
m_bThreadStatus = TH_ENDED;
setExitCause( EXIT_CODE_FACTORY_RESET );
break;
};
case CMD_NODES_RELOAD:{
//if( m_pNodeFactory != NULL ) {
// m_pNodeFactory->reloadNodes();
//};
break;
};
case CMD_NODE_RELOAD:{
uint32_t tNodeID = atoi( tCMD->param );
//if( m_pNodeFactory != NULL ) {
// m_pNodeFactory->reloadNode( tNodeID );
//};
break;
};
case CMD_KRNL_PNP:{
//if( m_pHardwareManager!= NULL ) {
// LOG_ERROR( "Restart and Detect HardWare!" );
// // Must be shutdowned all service that uses hardware prior to detection!
// m_bThreadStatus = TH_ENDED;
// setExitCause( EXIT_CODE_DETECT_HARDWARE ); // Go -> Detect Hardware in BACKEND
//};
break;
};
case CMD_KRNL_UPDATE_IDENT:{
//LOG("Restart Mojo -> Update Ident!");
//sprintf( m_sIdentity, tCMD->PARAM );
//config_setting_remove ( m_pSettings, MOJO_KERNEL_TAG_SERVER_IDENTITY );
//config_setting_t *pSetting = config_setting_add( m_pSettings, MOJO_KERNEL_TAG_SERVER_IDENTITY, CONFIG_TYPE_STRING );
//config_setting_set_string( pSetting, tCMD->PARAM );
//basicSettingsProvider::getInstance()->compromise();
//basicSettingsProvider::getInstance()->validate();
//m_pDBC->updateServerIdentity( m_nServerID, m_sIdentity );
m_bThreadStatus = TH_ENDED;
setExitCause( EXIT_CODE_KERNEL_CLEAR );
break;
};
case CMD_KRNL_REPLACE_DATABASE:{
LOG("Restart Mojo -> Replace Database!");
//CSTR tNAME = m_pDBC->getDataParam( 0 );
//CSTR tUSER = m_pDBC->getDataParam( 1 );
//CSTR tGROUP = m_pDBC->getDataParam( 2 );
//if ( tNAME ) {
// char tB[256];
// sprintf( tB,"./data/%s.db", tCMD->PARAM );
// if ( fileExist( tB )) {
// LOG("Restart Mojo -> Close Database!");
//Closing Database
// delete( m_pDBC );
// m_pDBC = NULL;
// LOG("Restart Mojo -> Delete Database!");
// //unlink( tNAME );
// LOG("Restart Mojo -> Copy Database!");
// fileCopy( tB, tNAME );
// LOG("Restart Mojo -> Chown Database!");
// ch_chown( tNAME, tUSER, tGROUP );
// LOG("Restart Mojo -> Delete Old Database!");
// unlink( tB );
// m_bThreadStatus = TH_ENDED;
// LOG("Restart Mojo -> Exit!");
// setExitCause( EXIT_CODE_NO_DATABASE );//EXIT_CODE_RELOAD_SERVICES );
// m_bThreadStatus = TH_ENDED;
// } else {
// LOG_ERROR("New Database Does not Exists!");
// };
//free( tNAME );
//free( tUSER );
//free( tGROUP );
//};
break;
};
case CMD_KRNL_SYNC_TIME:{
uint32_t uts = atoi( tCMD->param );
if( uts ){
#if ( __GLIBC__ < 3 ) && ( __GLIBC_MINOR__ < 31 )
time_t ts = (time_t)uts;
if( stime( &ts ) == 0 ){
// Restert Server;
m_bThreadStatus = TH_ENDED;
setExitCause( EXIT_CODE_KERNEL_CLEAR );
};
#else
timespec ts;
ts.tv_sec = (time_t)uts;
ts.tv_nsec = 0;
if( clock_settime( CLOCK_REALTIME, &ts ) == 0 ){
// Restert Server;
m_bThreadStatus = TH_ENDED;
setExitCause( EXIT_CODE_KERNEL_CLEAR );
};
#endif
};
break;
};
case CMD_KRNL_SYSTEM_TASK:{
break;
};
case CMD_KRNL_PURGE_SESSION:{
if ( tCMD->aux_id ) {
LOG("Purge Session");
if (m_pSM) m_pSM->eraseSession( tCMD->aux_id );
};
break;
};
case CMD_KRNL_SET_SESSION_HZL:{
uint8_t tLVL = atoi( tCMD->param );
if ( tCMD->aux_id ) {
LOG("Life Session Hazard Level Updated by Operator");
/* Actual DataBase change done in WebApp Here we just making internal Event */
SESSION_RATE_DATA *tData = (SESSION_RATE_DATA *) malloc( sizeof( SESSION_RATE_DATA ) );
if ( tData ) {
tData->level = tLVL;
tData->track_id = tCMD->aux_id;
EVENT_CONTAINER * tEvt = createBasicEvent( 0, EVT_CLASS_SYSTEM, EVT_SRV_SESSION_RATED, NULL, NULL, tData );
if ( tEvt ) {
basicEventHeap::getInstance()->broadcast( tEvt );
} else {
free( tData );
};
};
};
break;
};
case CMD_KRNL_TEST_MODBUS:{
MODBUS_TEST_DATA *tData = (MODBUS_TEST_DATA *) malloc( sizeof( MODBUS_TEST_DATA ) );
if ( tData ) {
tData->id = tCMD->aux_id;
tData->c_OutBits = atoi( tCMD->param );
EVENT_CONTAINER * tEvt = createBasicEvent( 0, EVT_CLASS_SYSTEM, EVT_SRV_MODBUS_TEST_M, NULL, NULL, tData );
if ( tEvt ) {
basicEventHeap::getInstance()->broadcast( tEvt );
} else {
free( tData );
};
};
break;
};
case CMD_KRN_COMPOSE_SESSION_VIDEOS:{
uint64_t session_id = tCMD->aux_id;
if ( session_id ) {
char tB[256];
sprintf( tB, "Ordered Compose of session %lld", session_id );
LOG( tB );
servaVideoComposer *tCMP = new servaVideoComposer( session_id );
if ( tCMP ) {
if ( tCMP->compose() ) {
m_vComposersPool.push_back(tCMP);
} else {
LOG("Disengage Composer!");
};
};
};
break;
};
case CMD_KRN_SCADA_SNOOZE_POST_MESSAGE:{
uint64_t message_id = tCMD->aux_id;
if ( message_id ) {
#ifdef DEBUG
char tB[256];
sprintf( tB, "Ordered Snooze %lld SCADA Message", message_id );
LOG( tB );
#endif
MODBUS_POST_DATA *tData = m_pDBC->getScadaPostData( message_id );
if ( tData ) {
m_pDBC->updateScadaPostStatus( message_id, 1 );
EVENT_CONTAINER * tEvt = createBasicEvent( 0, EVT_CLASS_SYSTEM, EVT_SRV_MODBUS_S_POSTBOX, NULL, NULL, tData );
if ( tEvt ) {
basicEventHeap::getInstance()->broadcast( tEvt );
} else {
free( tData );
};
};
};
break;
};
case CMD_KRN_SCADA_DISMISS_POST_MESSAGE:{
uint64_t message_id = tCMD->aux_id;
if ( message_id ) {
#ifdef DEBUG
char tB[256];
sprintf( tB, "Ordered Dismiss %lld SCADA Message", message_id );
LOG( tB );
#endif
MODBUS_POST_DATA *tData = m_pDBC->getScadaPostData( message_id );
if ( tData ) {
m_pDBC->deleteScadaPost( message_id );
EVENT_CONTAINER * tEvt = createBasicEvent( 0, EVT_CLASS_SYSTEM, EVT_SRV_MODBUS_D_POSTBOX, NULL, NULL, tData );
if ( tEvt ) {
basicEventHeap::getInstance()->broadcast( tEvt );
} else {
free( tData );
};
};
};
break;
};
//Debug Functionality from Platform View
case CMD_KRN_SCADA_DISMISS_ALRM_PLATFORM:{
uint64_t platform_id = tCMD->aux_id;
if( platform_id ) {
#ifdef DEBUG
char tB[256];
sprintf( tB, "Ordered Dismiss %lld SCADA Platform ALARMS", platform_id );
LOG( tB );
#endif
EVENT_CONTAINER * tEvt = createBasicEvent( platform_id, EVT_CLASS_SYSTEM, EVT_SRV_MODBUS_CLEAR_S );
if ( tEvt ) {
basicEventHeap::getInstance()->broadcast( tEvt );
} else {
// free( tData );
};
};
break;
};
case CMD_KRN_SCADA_DISMISS_TOTT_PLATFORM:{
uint64_t platform_id = tCMD->aux_id;
if( platform_id ) {
#ifdef DEBUG
char tB[256];
sprintf( tB, "Ordered Dismiss %lld SCADA Platform ALL", platform_id );
LOG( tB );
#endif
EVENT_CONTAINER * tEvt = createBasicEvent( platform_id, EVT_CLASS_SYSTEM, EVT_SRV_MODBUS_CLEAR_P );
if ( tEvt ) {
basicEventHeap::getInstance()->broadcast( tEvt );
} else {
//free( tData );
};
};
break;
};
};
m_pDBC->updateWebCmdStatus( tCMD->id, DBC_CMD_READY_TO_CLEAN );
free( tCMD );
};
cTimeTSeconds = time( NULL );
if( cTimeTSeconds != tTimeTSeconds ){ //Each Second
tTimeTSeconds = cTimeTSeconds;
#ifdef LINUX_KERNEL_WATCHDOG
if( m_iWatchdogFd > -1 ) {
char tB[64];
sprintf( tB, "2000\n" );
//ToDo: Make Error Handling here!
write( m_iWatchdogFd, &tB, strlen( tB ) );
};
#endif
m_pDBC->cleanWebCmd();
updateStatus();
if ( m_vEncodersPool.size() ) {
for ( V_MEDIA_ENCODERS::iterator idx = m_vEncodersPool.begin(); idx < m_vEncodersPool.end(); ) {
if ( (*idx)->getStatus() == ENCODER_FINISHED ) {
handleEncodedVideo( *idx );
m_vEncodersPool.erase( idx );
} else idx++;
};
};
if ( m_vComposersPool.size() ) {
for ( V_VIDEO_COMPOSERS::iterator idx = m_vComposersPool.begin(); idx< m_vComposersPool.end(); ) {
if ( (*idx)->isFinished() ) {
delete( *idx );
m_vComposersPool.erase( idx );
} else idx++;
};
};
if ( m_sServaConfig.encoderLimit ) {
if (m_vEncodersPool.size() < m_sServaConfig.encoderLimit) {
if (uint64_t new_id = m_pDBC->getRecentMediaId()) {
LOG("New Encoder!");
if ( processVideoFile( new_id ) ) {
updateEncodeStatus( new_id, MEDIA_ENCODE_PROGRESS, 0 );
} else {
LOG_ERROR("Cannot Encode Queued Video -> Removing Task!");
m_pDBC->removeRemoteMediaInfo( new_id );
};
};
};
} else LOG_ERROR("Video Encoders Disabled??");
if ( m_pSM ) m_pSM->validate();
if ( m_pLifeMonitor ) m_pLifeMonitor->validate();
if ( m_pModBus ) ((servaModBusManager *)m_pModBus)->validate();
//m_pHardwareManager->updateSysInfo( &m_sSysInfo );
if ( m_pVideoComposer == NULL ) {
uint64_t tSID = m_pDBC->getSessionWithUnmergedVideo( m_sServaConfig.composerProceedDelay );
if ( tSID ) {
m_pVideoComposer = new servaVideoComposer( tSID );
if ( m_pVideoComposer ) {
if( !m_pVideoComposer->compose() ){
delete( m_pVideoComposer );
m_pVideoComposer = NULL;
};
};
};
};
};
SLEEP(SLEEP_KERNEL_INTERVAL);
};
};
void servaKernel::updateEncodeStatus( uint64_t dbid, uint8_t status, uint8_t perc ){
m_pDBC->updateEncodeStatus( dbid, status, perc );
};
bool servaKernel::processVideoFile( uint64_t dbid ){
if ( dbid == 0 ) return false;
DBC_RPC_MEDIA_INFO *NFO = m_pDBC->getRemoteMediaInfo( dbid );
if ( NFO ) {
if ( strcmp( NFO->fmt, "mp4" ) == 0 ) {
#ifdef DEBUG
LOG("Skip Convertion of MP4");
#endif
DBC_RPC_MEDIA_INFO_EX *tP = m_pDBC->getRemoteMediaInfoEx( dbid );
if ( tP ) {
if( !m_pSM->addVideo( tP )){
LOG_ERROR("Cannot Add to session Media Info!");
};
#ifdef DEBUG
LOG("Delete Extended Info");
#endif
free( tP );
} else {
LOG_ERROR("Cannot get Extended Encoder Queue Media Info!");
};
free( NFO );
return false;
};
servaMediaEncoder *ptr = new servaMediaEncoder(dbid);
if ( ptr ) {
#ifdef DEBUG
LOG("Encoder Constructed!");
#endif
char tA[MAX_PATH];
char tB[MAX_PATH];
//Todo -> Instead GetSessionBase -> calc Base based on TS of video
CSTR BASE = m_pSM->getSessionBase( NFO->session_id );
if( BASE ){
sprintf( tA,"%s/%s.%s", BASE, NFO->uuid, NFO->fmt );
LOG(tA);
sprintf( tB,"%s/%s.mp4", BASE, NFO->uuid );
LOG(tB);
free(BASE);
if ( ptr->create( tA, tB, NFO->fps ) ) {
#ifdef DEBUG
LOG("Encoder Created!");
#endif
m_vEncodersPool.push_back( ptr );
return true;
};
};
delete( ptr );
};
free( NFO );
} else LOG("No Video Info!!");
return false;
};
void servaKernel::handleEncodedVideo( servaMediaEncoder *ptr ){
if ( ptr ) {
m_pDBC->updateEncodeFormat( ptr->getDBID(), ptr->getDstFormat() );
DBC_RPC_MEDIA_INFO_EX *tP = m_pDBC->getRemoteMediaInfoEx( ptr->getDBID() );
if ( tP ) {
if( m_pSM->addVideo( tP )){
m_pDBC->removeRemoteMediaInfo( ptr->getDBID() );
} else {
LOG_ERROR("Cannot Add to session Media Info!");
};
LOG("Delete Extended Info");
free( tP );
} else {
LOG_ERROR("Cannot get Extended Encoder Queue Media Info!");
};
LOG("Delete Encoder");
delete( ptr );
LOG("Done");
};
};
bool servaKernel::dispatchEvent( EVENT_CONTAINER *Evt ){
if ( Evt == NULL ) return false;
/*
switch ( Evt->m_eClass ) {
case EVT_CLASS_VIDEO:{
switch ( Evt->m_eType ) {
case EVT_SRV_VIDEO_CHUNK:{
SERVA_VIDEO_TRANSFER_INFO *tData = ( SERVA_VIDEO_TRANSFER_INFO * ) Evt->m_pEvtData;
if ( tData ){
if ( tData->status == MEDIA_STORED ) {
updateEncodeStatus(tData->db_id, tData->status, tData->perc);
};
};
return false; // Kernel is Final Destination for that Event
};
};
break;
};
};*/
return true;
};
//Todo -> Startup Cleanup Media Encoder Queue (with ability to finish unfinishing jobs -> Drop just unsucessful transfers
// Make Treshold of Running Encoders to a server
#undef LOG
#undef LOG_ERROR