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.
 
 
 
 
 
 

1492 lines
58 KiB

#include "hardwareManager.h"
#include <sys/types.h>
#include <sys/sysinfo.h>
#include <sys/statvfs.h>
#include <time.h>
#ifdef USE_MYSQL
#include "MySQL_dataBinder.h"
#else
#include "SQLite_dataBinder.h"
#endif
//#include "rgooseKernel.h"
//#include "rgooseDBConnector.h"
#include "hardwareResourceSerialProvider.h"
#include "hardwareResourceNetworkProvider.h"
#include "hardwareResourceVideoProvider.h"
#include "../hardware/hid/hid_dc.h"
#include "../alg/generic/heapDebug.h"
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <hidapi/hidapi.h>
#include <ifaddrs.h>
#include <linux/serial.h>
#include <linux/videodev2.h>
//#define NO_EXEC_EXTERNALS
#define LOG( X ) m_pLog->Log( "HWM", this, X )
#ifdef DEBUG
#define LOG_ERROR( X ) {\
char _tBfrErrMSG2w34[256];\
sprintf( _tBfrErrMSG2w34, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\
m_pLog->Log( "HWM", this, _LOG_ERROR, _tBfrErrMSG2w34 );\
}
#else
#define LOG_ERROR( X ) m_pLog->Log( "HWM", this, _LOG_ERROR, X );
#endif
hardwareManager *hardwareManager::_instance = NULL;
/**
* Returns the single instance of the object.
*/
hardwareManager* hardwareManager::getInstance( bool cold_start ) {
// check if the instance has been created yet
if( 0 == _instance ){
// if not, then create it
_instance = new hardwareManager( cold_start );
};
// return the single instance
return _instance;
};
hardwareManager::hardwareManager( bool cold_start ){
m_pLog = basicLogCollection::getInstance();
//m_bHardwareEnumerated = false;
m_nServerNodeID = 0;
m_nServerID = 0;
m_nSiteID = 0;
m_bCacheCleanCounter = 1;
memset( &m_sSYS_INFO, 0, sizeof(DBC_SYS_INFO) );
strncpy( m_sSYS_INFO.SW_INFO, _BUILD_STRING_, 128 );
config_setting_t * m_pSettings = basicSettingsProvider::getInstance()->getSubNode( NULL, "HARDWARE" );
if ( m_pSettings ) {
config_setting_t * pSetting;
long long int tVal;
const char * tBuf;
char tBuffer[128];
if( !config_setting_lookup_int64( m_pSettings, "MEMORY_LIMIT", &tVal ) ){
tVal = m_nMemoryLimitHeapSize = MEMORY_CONSUMPTION_LIMIT;
pSetting = config_setting_add( m_pSettings, "MEMORY_LIMIT", CONFIG_TYPE_INT64 );
config_setting_set_int64( pSetting, tVal );
basicSettingsProvider::getInstance()->compromise();
LOG("MEMORY LIMIT NOT DEFINED - Using 2Gb Default!");
} else {
m_nMemoryLimitHeapSize = tVal;
sprintf( tBuffer, "MEMORY LIMIT Read From Settings: %lld bytes", m_nMemoryLimitHeapSize );
LOG( tBuffer );
};
basicSettingsProvider::getInstance()->validate();
} else {
m_nMemoryLimitHeapSize = MEMORY_CONSUMPTION_LIMIT;
};
#ifndef NO_EXEC_EXTERNALS
FILE *fd = popen("/bin/uname -s -r -v -m","r");
if( fd!= NULL ) {
fgets( m_sSYS_INFO.OS_INFO, 127, fd);
m_sSYS_INFO.OS_INFO[127] = (char)0;
trim( m_sSYS_INFO.OS_INFO );
memset( m_sSYS_INFO.HW_INFO, 0, 128 );
fclose( fd );
fd = NULL;
};
#else
FILE *fd = NULL;
#endif
fd = fopen("/proc/cpuinfo","r");
if ( fd!= NULL ) {
char tBB[1024];
bool bARM = false;
while( !feof( fd ) ) {
fgets( tBB, 1024, fd );
trim( tBB );
if( strcasestr(tBB, "model") != NULL ) {
if( strcasestr(tBB, "model name") != NULL ) {
if ( !bARM ) {
if( strcasestr( tBB, "ARM" ) != NULL){
bARM = true;
} else {
CArray *tA = explode(':', tBB );
if ( tA ) {
strncpy( m_sSYS_INFO.HW_INFO, tA->at(1), 127 );
delete tA;
};
break;
};
};
} else {
if( bARM ) {
CArray *tA = explode(':', tBB);
if ( tA ) {
strncpy( m_sSYS_INFO.HW_INFO, tA->at(1), 127 );
delete tA;
};
break;
};
};
};
};
m_sSYS_INFO.HW_INFO[127] = (char)0;
trim( m_sSYS_INFO.HW_INFO );
fclose( fd );
fd = NULL;
};
#ifdef USE_MYSQL
m_pDBC = mysqlDBC::getInstance();
#else
m_pDBC = sqliteDBC::getInstance();
#endif
if( m_pDBC == NULL ) {
LOG_ERROR( "Failure to get DBC Instance -> Forced HW Enumeration!" );
enumerateHardware();
} else {
char tB[128];
struct rlimit rl={0};
getrlimit( RLIMIT_STACK, &rl );
sprintf( tB, "Stack Size: %d", rl.rlim_cur ); //RLIM_INFINITY
LOG( tB );
sprintf( tB, "MAX Stack Size: %d", rl.rlim_max );
LOG( tB );
//enumerateHardware( !cold_start );
enumerateNIFS();
#ifdef DEBUG
LOG("Load Ressources...");
#endif
loadResources();
#ifdef DEBUG
LOG("Load Resources Done");
#endif
};
};
hardwareManager::~hardwareManager(){
#ifdef DEBUG
LOG("Destructor Begin");
#endif
unloadResources();
#ifdef DEBUG
LOG("Destructor End");
#endif
_instance = NULL;
};
void hardwareManager::unloadResources( void ){
#ifdef DEBUG
LOG("Unload Resources ...");
#endif
//m_mVectorProtector.lock();
if( m_vResources.size() ) {
for( VECTOR_HW_RESOURCES::iterator idx = m_vResources.begin(); idx < m_vResources.end(); idx++ ) {
switch( (*idx)->getHardwareType() ) {
case HARDWARE_UART:
case HARDWARE_IP_UART: delete( ( hardwareResourceSerialProvider*)(*idx) ); break;
case HARDWARE_NIF_LOOPBACK:
case HARDWARE_NIF_ETHERNET:
case HARDWARE_NIF_WIFI:
case HARDWARE_NIF_VIRTUAL:
case HARDWARE_NIF_TUNEL: delete( ( hardwareResourceNetwork*)(*idx) ); break;
};
};
m_vResources.clear();
};
//m_mVectorProtector.unlock();
#ifdef DEBUG
LOG("Unload Resources Done");
#endif
};
void hardwareManager::loadResources( void ){
if( m_pDBC == NULL ) return;
DBC_INT_LIST *tVal;
tVal = m_pDBC->listResources( );//load whole site resources
//tVal = m_pDBC->listResources( m_nServerNodeID );//Load Only Server Node resources
if( tVal!= NULL ) {
if( tVal->size() ) {
for (DBC_INT_LIST::iterator index = tVal->begin(); index < tVal->end(); index++) {
DBC_RESOURCE_DATA *tData = m_pDBC->getResourceData( *index );
if( tData != NULL ) {
hardwareResource *tPtr = NULL;
switch( tData->type ){
case HARDWARE_UART:{
#ifdef DEBUG
LOG("Construct HW UART");
#endif
hardwareResourceSerialProvider *tRes = new hardwareResourceSerialProvider( tData->id );
if( tRes != NULL ) {
if( tRes->create() ) {
tPtr = ( hardwareResource *) tRes;
} else {
LOG_ERROR("Error Creating HW UART!");
delete( tRes );
};
};
break;
};
case HARDWARE_NIF_LOOPBACK:
case HARDWARE_NIF_ETHERNET:
case HARDWARE_NIF_WIFI:
case HARDWARE_NIF_VIRTUAL:
case HARDWARE_NIF_TUNEL:{
#ifdef DEBUG
LOG("Construct NetIF");
#endif
hardwareResourceNetwork *tRes = new hardwareResourceNetwork( tData->id );
if( tRes != NULL ) {
if( tRes->create() ) {
tPtr = ( hardwareResource *) tRes;
} else {
LOG_ERROR("Error Creating Network Ressource!");
delete( tRes );
};
};
break;
};
case HARDWARE_IP_UART:{
#ifdef DEBUG
LOG("Construct IP UART");
#endif
hardwareResourceSerialProvider *tRes = new hardwareResourceSerialProvider( tData->id );
if( tRes != NULL ) {
if( tRes->create() ) {
tPtr = ( hardwareResource *) tRes;
} else {
LOG_ERROR("Error Creating IP UART!");
delete( tRes );
};
};
break;
};
case HARDWARE_ANALOG_VIDEO_IN:
case HARDWARE_DIGITAL_VIDEO_IN:{
#ifdef DEBUG
LOG("Construct VIDEO IN");
#endif
hardwareResourceVideoProvider *tRes = new hardwareResourceVideoProvider( tData->id );
if( tRes != NULL ) {
if( tRes->create() ) {
tPtr = ( hardwareResource *) tRes;
} else {
LOG_ERROR("Error Creating Video IN!");
delete( tRes );
};
};
break;
};
#ifdef DEBUG
default:{
char tB[128];
sprintf( tB, "Unknown Ressource[%d] Type[%d]!", *index, tData->type );
LOG_ERROR(tB);
break;
};
#endif
};
if( tPtr!= NULL ) {
#ifdef DEBUG
LOG("Resource Sucessfully Created!");
#endif
m_mVectorProtector.lock();
m_vResources.push_back( tPtr );
m_mVectorProtector.unlock();
m_pDBC->setRessourceActive( *index );
} else {
m_pDBC->setRessourceActive( *index, false );
};
} else {
LOG_ERROR("Can not fetch Resource Data from Database!");
};
};
#ifdef DEBUG
} else {
LOG("Fetched Empty List!");
#endif
};
tVal->clear();
delete( tVal );
#ifdef DEBUG
} else {
LOG("Fetched NULL!");
#endif
};
};
bool hardwareManager::validate( void ){
bool RetVal = true;
m_mVectorProtector.lock();
if( m_vResources.size() ) {
for( VECTOR_HW_RESOURCES::iterator idx = m_vResources.begin(); idx < m_vResources.end(); idx++ ) {
if( !(*idx)->validate() ) {
// recreate Resource
LOG_ERROR( "HW Resource Invalid!" );
m_pDBC->setRessourceActive( (*idx)->getDbId(), false );
#ifdef DEBUG
char tB[256];
sprintf( tB, "Info: DBID[%d] R-Type: %d Provider: %d ", (*idx)->getDbId(), (*idx)->getHardwareType(), (*idx)->getProviderType() );
LOG( tB );
#endif
if( !(*idx)->create()){
LOG_ERROR( "HW Resource Creation Failure!" );
} else {
m_pDBC->setRessourceActive( (*idx)->getDbId() );
#ifdef DEBUG
LOG("Re-Created OK");
#endif
};
#ifdef DEBUG_EXTRA
} else {
LOG("Resource OK!");
#endif
};
};
#ifdef DEBUG_EXTRA
} else {
LOG("No Resources!");
#endif
};
m_mVectorProtector.unlock();
//Mem Validator
if( m_nMemoryLimitHeapSize ) {
size_t memStat = getCurrentRSS();
#ifdef DEBUG_EXTRA
char MEM_MSG[128];
sprintf( MEM_MSG, "MEM: %" PRIu64 " TARG: %" PRIu64, memStat, m_nMemoryLimitHeapSize );
LOG( MEM_MSG );
#endif
//https://www.ebay.com/itm/274974088159?
RetVal = ( memStat < m_nMemoryLimitHeapSize );
if ( !RetVal ) {
LOG_ERROR("Memory Consumption too BIG!");
};
};
if ( m_bCacheCleanCounter == 0 ) {
LOG_ERROR("System Cache Fas Too Big Too Many Times!");
RetVal = false;
};
return RetVal;
};
void hardwareManager::getMAC( CSTR if_name, CSTR buf ){
char tB[128];
FILE * fd=NULL;
if ( buf ) {
sprintf(tB, "/sys/class/net/%s/address", if_name);
#ifdef DEBUG_EXTRA
LOG( tB );
#endif
fd=fopen(tB,"r");
if ( fd ) {
fread( buf, 1, INET6_ADDRSTRLEN, fd );
fclose( fd );
buf = trim( buf );
} else {
memset( buf, 0, INET6_ADDRSTRLEN );
};
#ifdef DEBUG_EXTRA
LOG( buf );
#endif
};
};
void hardwareManager::getGW( CSTR if_name, CSTR buf ){
memset( buf, 0, INET6_ADDRSTRLEN );
#ifndef NO_EXEC_EXTERNALS
FILE * fd = popen( "route -n", "r" );
char tB[1024];
//char expBuf[1024];
if ( fd ) {
while (!feof(fd)) {
fgets((CSTR)tB, 1024, fd);
trim((CSTR)tB);
if( strlen(tB) ) {
if( strstr( tB, if_name ) != NULL ){
//strncpy( expBuf, tB, 1024 );
CArray *CA = explode( ' ', tB );
if ( CA ) {
//for (int i=0; i< CA->size(); i++ ) {
// char tB[128];
// trim( CA->at(i) );
// sprintf( tB, "GW# %d: %s", i, CA->at(i) );
// LOG( tB );
//};
trim( CA->at(1) );
if( strstr(CA->at(1), "0.0.0.0") == NULL ) {
strncpy( buf, CA->at(1), INET6_ADDRSTRLEN );
};
delete(CA);
};
};
};
};
fclose( fd );
};
#endif
if( strlen( buf ) == 0 ) strncpy( buf, "0.0.0.0", INET6_ADDRSTRLEN );
};
void hardwareManager::getTTyDesc( CSTR dev_name, CSTR buf ){
memset( buf, 0, DBC_RESOURCE_DESC_SIZE );
#ifndef NO_EXEC_EXTERNALS
FILE * fd = popen( "dmesg | grep tty", "r" );
char tB[1024];
//char expBuf[1024];
if ( fd ) {
while (!feof(fd)) {
fgets((CSTR)tB, 1024, fd);
trim((CSTR)tB);
if( strlen(tB) ) {
if( strstr( tB, dev_name ) != NULL ){
CArray *CA = explode( ':', tB );
if ( CA ) {
if( CA->size() ) {
trim( CA->at(CA->size()-1) );
strncpy( buf, CA->at(CA->size()-1), CTEXT );
buf[CTEXT-1]=(char)0;
};
delete(CA);
};
};
};
};
fclose( fd );
};
#endif
if( strlen( buf ) == 0 ){
strncpy( buf, "--Unknown--", DBC_RESOURCE_DESC_SIZE );
buf[DBC_RESOURCE_DESC_SIZE-1]=(char)0;
};
};
PARSE_RESULT_NET_INTERFACES *hardwareManager::parse_neconfig( CSTR if_name ){
PARSE_RESULT_NET_INTERFACES *tVal = NULL;
FILE *fd;
bool cConfig = false;
fd = fopen("/etc/network/interfaces","r");
if ( fd ) {
char tB[1024];
char expBuf[1024];
tVal = (PARSE_RESULT_NET_INTERFACES *) malloc( sizeof(PARSE_RESULT_NET_INTERFACES));
if ( tVal ) {
memset(tVal, 0 , sizeof(PARSE_RESULT_NET_INTERFACES));
while (!feof(fd)) {
fgets((CSTR)tB, 1024, fd);
trim((CSTR)tB);
if( strlen(tB) ) {
strncpy( expBuf, tB, 1024 );
CArray *CA = explode( ' ', expBuf );
if( CA ) {
for( CArray::iterator idx = CA->begin(); idx < CA->end(); idx++ ) {
if((*idx)[0]=='#') break;
if(strstr((*idx), "auto")!= NULL ) if( strstr( tB, if_name )!= NULL ) tVal->enabled = true;
if(strstr((*idx), "allow-hotplug")!= NULL ) if( strstr( tB, if_name )!= NULL ) tVal->hot_plug = true;
if(strstr((*idx), "iface")!= NULL ) if( strstr( tB, if_name )!= NULL ){
if (strstr( tB, "static") != NULL) tVal->if_static = true;
cConfig = true;
} else cConfig = false;
if(strstr((*idx), "address")!= NULL ) if( cConfig ){
idx++;
if(strstr((*idx),"/")!= NULL ){
int8_t sh = strstr((*idx),"/") - (*idx);
strncpy( tVal->address, (*idx), sh );
tVal->address[sh]=(char)0;
int8_t bm = atoi( (*idx) + sh + 1 );
union{
uint32_t mm;
uint8_t nm[4];
} nmu = {0};
for ( sh = 0; sh < bm; sh++ ) nmu.mm |= (1 << sh);
sprintf(tVal->netmask, "%d.%d.%d.%d", nmu.nm[0], nmu.nm[1], nmu.nm[2], nmu.nm[3]);
} else {
strncpy( tVal->address, (*idx), INET6_ADDRSTRLEN );
};
};
if(strstr((*idx), "netmask")!= NULL ) if( cConfig ){
LOG("netMSK");
idx++;
LOG(*idx);
strncpy(tVal->netmask, (*idx), INET6_ADDRSTRLEN);
};
//if(strstr((*idx), "bridge_ports")!= NULL ) cMode = 6;
//if(strstr((*idx), "bridge_stp")!= NULL ) cMode = 7;
//if(strstr((*idx), "bridge_waitport")!= NULL ) cMode = 8;
//if(strstr((*idx), "bridge_fd")!= NULL ) cMode = 9;
};
delete( CA );
};
};
};
};
fclose( fd );
};
#ifdef DEBUG_EXTRA
if ( tVal ) {
if( tVal->enabled ) LOG("NIF Enabled"); else LOG("NIF Disabled");
if (tVal->hot_plug) LOG("NIF Hot Plugable"); else LOG("NIF not Hot Plugable");
if (tVal->if_static) LOG("Address is static"); else LOG("Address is Dynamic");
if(strlen(tVal->address))LOG(tVal->address);
if(strlen(tVal->netmask))LOG(tVal->netmask);
};
#endif
return tVal;
};
PARSE_RESULT_WIFI_SETTINGS *hardwareManager::parse_wifi( CSTR if_name ){
PARSE_RESULT_WIFI_SETTINGS * tVal = NULL;
FILE * fd;
bool cConfig = false;
bool is_wifi = false;
tVal = (PARSE_RESULT_WIFI_SETTINGS *) malloc( sizeof(PARSE_RESULT_WIFI_SETTINGS));
if ( tVal ) {
memset(tVal, 0 , sizeof(PARSE_RESULT_WIFI_SETTINGS));
fd = fopen("/etc/dnsmasq.conf","r");
if ( fd ) {
char tB[1024];
char expBuf[1024];
while (!feof(fd)) {
fgets((CSTR)tB, 1024, fd);
trim((CSTR)tB);
if( strlen(tB) ) {
strncpy( expBuf, tB, 1024 );
CArray *CA = explode( '=', expBuf );
if( CA ) {
if( CA->size() ){
if( CA->at(0)[0] == '#' ) continue;
if( strstr(CA->at(0), "interface")!= NULL ) {
if( strstr( tB, if_name)!= NULL ) {
cConfig = true;
tVal->dhcp_enabled = true;
};
};
if( cConfig ){
if ( strstr(CA->at(0), "dhcp-range")!= NULL ) {
char tT[1024];
strncpy( tT, CA->at(1), 1024 );
CArray *CB = explode(',', tT );
if( CB ){
if( CB->size() > 3 ){
strncpy( tVal->range_start, CB->at(0), INET6_ADDRSTRLEN);
strncpy( tVal->range_stop, CB->at(1), INET6_ADDRSTRLEN);
strncpy( tVal->netmask, CB->at(2), INET6_ADDRSTRLEN);
strncpy( tVal->lease_period, CB->at(3), INET6_ADDRSTRLEN);
};
delete( CB );
};
};
};
};
delete( CA );
};
};
};
fclose( fd );
};
#ifndef NO_EXEC_EXTERNALS
//Check WiFi
if( strstr(if_name,"w")!= NULL ) {
char tName[128];
is_wifi = true;
sprintf( tName, "iwconfig %s", if_name );
fd = popen( tName, "r" );
if ( fd ) {
char tB[1024];
while (!feof(fd)) {
fgets((CSTR)tB, 1024, fd );
trim( tB );
if (strstr(tB, "Mode") != NULL) if (strstr(tB, "Master") != NULL) tVal->access_point = true;
};
fclose( fd );
};
};
#endif
if ( tVal->access_point ) {
fd = fopen("/etc/hostapd/hostapd.conf", "r");
if ( fd ) {
char tB[1024];
char expBuf[1024];
while (!feof(fd)) {
fgets((CSTR)tB, 1024, fd);
trim( tB );
if( strlen(tB) ) {
if( tB[0]=='#' ) continue;
strncpy(expBuf, tB, 1024);
CArray *CA = explode( '=', expBuf );
if( CA ) {
if( CA->size() ){
if (strstr(CA->at(0), "ssid") != NULL) if (strstr(CA->at(0), "ignore_broadcast_ssid") == NULL){
strncpy( tVal->SSID, CA->at(1), 64 );
} else tVal->hiden_ssid = (bool) atoi(CA->at(1));
if (strstr(CA->at(0), "wpa_passphrase") != NULL) strncpy( tVal->password, CA->at(1), 64 );
if (strstr(CA->at(0), "country_code") != NULL) strncpy(tVal->country_code, CA->at(1), 3);
if (strstr(CA->at(0), "channel") != NULL) tVal->channel = atoi(CA->at(1));
};
delete( CA );
};
};
};
fclose( fd );
};
} else {
fd = fopen("/etc/wpa_supplicant/wpa_supplicant.conf", "r");
if ( fd ) {
fclose( fd );
};
};
fd = fopen("/etc/rc.local","r");
if ( fd ) {
char tB[1024];
char expBuf[1024];
while (!feof(fd)) {
fgets((CSTR)tB, 1024, fd);
trim((CSTR)tB);
if( strlen(tB) ) {
strncpy( expBuf, tB, 1024 );
CArray *CA = explode( ' ', expBuf );
if( CA ) {
if ( CA->size() ) {
if (CA->at(0)[0] == '#') continue;
if( strstr(CA->at(0), "iptables-restore")!= NULL ) {
char zB[1024];
FILE *afd = fopen( CA->at(2), "r" );
if ( afd ) {
while( !feof( afd ) ){
fgets((CSTR)zB, 1024, afd );
if( strstr( zB, "POSTROUTING" )!= NULL ) if( strstr( zB, "MASQUERADE" )!= NULL ) if( strstr( zB, if_name )== NULL ){
CArray *CB = explode( ' ', zB );
if ( CB ) {
if ( CB->size() > 3 ) {
strncpy(tVal->router_outbond, CB->at(3), INET6_ADDRSTRLEN);
};
delete( CB );
};
tVal->router_enabled = true;
};
};
fclose(afd);
} else LOG("Error Opening Firewall Rules!");
};
};
delete( CA );
};
};
};
fclose(fd);
} else LOG_ERROR("Can not open rc.local!");
#ifdef DEBUG_EXTRA
char zz[128];
if ( is_wifi ) {
if (tVal->access_point){
LOG("WiFi is in AP Mode");
sprintf( zz, "\tSSID:%s PWD:%s", tVal->SSID, tVal->password );
LOG( zz );
if (tVal->hiden_ssid) LOG("SSID is hidden");
} else LOG("WiFi is in Client Mode");
};
if (tVal->dhcp_enabled){
LOG("DHCP Service - Enabled");
sprintf( zz, "\tRange: %s - %s Lease Time: %s", tVal->range_start, tVal->range_stop, tVal->lease_period );
LOG( zz );
} else {
LOG("DHCP Service - Disabled");
};
if (tVal->router_enabled){
sprintf( zz, "Routing enabled to [%s] NIF", tVal->router_outbond );
LOG( zz );
} else {
LOG("Routing Disabled");
};
#endif
};
return tVal;
};
void hardwareManager::enumerateNIFS( void ){
struct ifaddrs * ifaddr = NULL;
char tBuffer[128];
//if( m_pKernel == NULL ) return;
if( m_pDBC == NULL ) return;
if( -1 == getifaddrs(&ifaddr)) {
LOG_ERROR("No NET INTERFACES?!");
} else {
#ifdef DEBUG
LOG("Enumerating Network Interfaces");
#endif
struct ifaddrs * ifa;
for( ifa = ifaddr; ifa; ifa = ifa->ifa_next ){
char addr[INET6_ADDRSTRLEN];
char mask[INET6_ADDRSTRLEN];
char gw[INET6_ADDRSTRLEN];
char bc[INET6_ADDRSTRLEN];
char mac[INET6_ADDRSTRLEN];
char device[INET6_ADDRSTRLEN];
uint32_t nif_id = 0;
uint32_t nif_aux_id = 0;
uint32_t router_id = 0;
NIF_TYPE nif_type = NIF_LOOPBACK;
NETWORK_TYPE net_type = NETWORK_IPV4;
RESOURCE_TYPE res_type = HARDWARE_NIF_LOOPBACK;
NIF_MODE nif_mode = ADDRESS_DISABLED;
#ifdef DEBUG_EXTRA
LOG("*** Network Interface ***");
#endif
strncpy( device, ifa->ifa_name, INET6_ADDRSTRLEN );
strncpy( mac,"--no-mac--", INET6_ADDRSTRLEN );
#ifdef DEBUG_EXTRA
LOG(device);
#endif
// Filter Loopback if
if( strstr( device, "lo" ) != NULL ){
nif_type = NIF_LOOPBACK;
res_type = HARDWARE_NIF_LOOPBACK;
//Not Implemented
#ifdef DEBUG_EXTRA
LOG("Loopback Device -> SKIP");
#endif
continue;
};
// Filter vpn TUN if
if( strstr( device, "tun" ) != NULL ){
nif_type = NIF_VPN_TUNEL;
res_type = HARDWARE_NIF_TUNEL;
//Not Implemented Yet
#ifdef DEBUG_EXTRA
LOG("Tunel Device -> SKIP");
#endif
continue;
};
if( strstr( device, "e" ) != NULL ){
nif_type = NIF_ETHERNET;
res_type = HARDWARE_NIF_ETHERNET;
};
if( strstr( device, "wl" ) != NULL ){
nif_type = NIF_WIFI;
res_type = HARDWARE_NIF_WIFI;
};
if( strstr( device, "ww" ) != NULL ){
nif_type = NIF_WAN;
res_type = HARDWARE_NIF_WAN;
};
if( ifa->ifa_addr != NULL ){
if (ifa->ifa_addr->sa_family != AF_INET && ifa->ifa_addr->sa_family != AF_INET6) {
#ifdef DEBUG_EXTRA
LOG("No INET ADDRESSES -> SKIP");
#endif
continue;
}
} else {
#ifdef DEBUG_EXTRA
LOG("ifa->ifa_addr is NULL -> SKIP");
#endif
continue;
};
#ifdef DEBUG_EXTRA
LOG("Getting Info....");
#endif
getMAC( device, mac );
getGW( device, gw );
#ifdef DEBUG_EXTRA
LOG( mac );
LOG( gw );
#endif
PARSE_RESULT_NET_INTERFACES * tt = NULL;
PARSE_RESULT_WIFI_SETTINGS * tw = NULL;
#ifdef DEBUG_EXTRA
LOG("Parse NetConfig Info....");
#endif
tt = parse_neconfig( device );
if( tt ) {
if ( tt->enabled ) {
if( tt->if_static ){
nif_mode = ADDRESS_STATIC;
} else {
nif_mode = ADDRESS_DYNAMIC;
};
} else {
nif_mode = ADDRESS_DISABLED;
};
} else {
LOG_ERROR("Error Parsing System NIF Settings!");
continue;
};
#ifdef DEBUG_EXTRA
LOG("Parse Routing/DHCP/AP Info....");
#endif
tw = parse_wifi( device );
if ( tw ){
#ifdef DEBUG_EXTRA
LOG("Routing/AP Info OK!");
#endif
if( nif_mode == ADDRESS_STATIC ) {
if( tw->dhcp_enabled ){
#ifdef DEBUG_EXTRA
LOG("Address is Router");
#endif
nif_mode = ADDRESS_STATIC_RAP;
};
};
nif_id = m_pDBC->addLocalNIF( device, mac, nif_type, nif_mode );
#ifdef DEBUG_EXTRA
sprintf( tBuffer, "NIF(%s) added as [%d]", device, nif_id );
LOG( tBuffer );
#endif
if ( nif_type == NIF_WIFI ){
if( nif_id == 0 ){
LOG_ERROR("Error Adding NIF in DB!");
continue;
};
WIFI_MODE w_mode;
if( !tt->enabled ) {
w_mode = WIFI_DISABLED;
} else {
if( tt->if_static ){
if( tw->access_point ) {
w_mode = WIFI_IS_AP;
uint32_t outbond_id = 0;
if( tw->router_enabled ){
outbond_id = m_pDBC->getNIF_IDbyDevice( tw->router_outbond );
};
if( tw->dhcp_enabled ) {
#ifdef DEBUG_EXTRA
LOG("ADD Router With DHCP");
#endif
router_id = m_pDBC->addLocalNetworkInfrastructure(nif_id, outbond_id, true, tw->range_start, tw->range_stop, tw->netmask, tw->lease_period );
} else {
#ifdef DEBUG_EXTRA
LOG("ADD Router ONLY");
#endif
router_id = m_pDBC->addLocalNetworkInfrastructure( nif_id, outbond_id );
};
#ifdef DEBUG_EXTRA
sprintf( tBuffer, "Router added as [%d]", router_id );
LOG( tBuffer );
#endif
} else {
w_mode = WIFI_CONNECTED_TO_AP;
};
};
};
#ifdef DEBUG_EXTRA
LOG("ADD WiFi Record");
#endif
nif_aux_id = m_pDBC->addLocalWiFi( nif_id, w_mode, tw->SSID, tw->password, ENCRIPTION_WPA_PSK, router_id );
};
if( nif_type == NIF_ETHERNET || nif_type == NIF_ETHERNET_VIRTUAL ){
if( tt->if_static ){
uint32_t outbond_id = 0;
nif_mode = ADDRESS_STATIC;
if( tw->router_enabled ){
nif_mode = ADDRESS_STATIC_RAP;
outbond_id = m_pDBC->getNIF_IDbyDevice( tw->router_outbond );
};
if( tw->dhcp_enabled ) {
#ifdef DEBUG_EXTRA
LOG("ADD Router With DHCP");
#endif
router_id = m_pDBC->addLocalNetworkInfrastructure( nif_id, outbond_id, true, tw->range_start, tw->range_stop, tw->netmask, tw->lease_period );
} else {
#ifdef DEBUG_EXTRA
LOG("ADD Router ONLY");
#endif
router_id = m_pDBC->addLocalNetworkInfrastructure( nif_id, outbond_id );
};
#ifdef DEBUG_EXTRA
sprintf( tBuffer, "Router added as [%d]", router_id );
LOG( tBuffer );
#endif
} else {
nif_mode = ADDRESS_DYNAMIC;
};
};
free(tt);
free(tw);
} else {
LOG_ERROR("Error Parsing System Router/AP Settings!");
free(tt);
continue;
};
if( nif_aux_id != 0 ) {
nif_id = m_pDBC->addLocalNIF(device, mac, nif_type, nif_mode, nif_aux_id );
#ifdef DEBUG_EXTRA
sprintf( tBuffer, "2 NIF(%s) Updated as [%d]", device, nif_id );
LOG( tBuffer );
#endif
if( nif_id == 0 ) {
LOG_ERROR("Error Adding NIF in DB!");
continue;
};
#ifdef DEBUG_EXTRA
LOG("NIF added!");
} else {
LOG("NIF Already added (regular Mode)!");
#endif
};
m_pDBC->addResource( /*m_nServerNodeID,*/ res_type, device, nif_id );
if( ifa->ifa_addr->sa_family == AF_INET ){
net_type = NETWORK_IPV4;
// create IPv4 string
struct sockaddr_in *in = (struct sockaddr_in*) ifa->ifa_addr;
inet_ntop(AF_INET, &in->sin_addr, addr, sizeof(addr));
sprintf( mask, "%d.%d.%d.%d",
(uint8_t)ifa->ifa_netmask->sa_data[2],
(uint8_t)ifa->ifa_netmask->sa_data[3],
(uint8_t)ifa->ifa_netmask->sa_data[4],
(uint8_t)ifa->ifa_netmask->sa_data[5]
);
sprintf( bc, "%d.%d.%d.%d",
(uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[2],
(uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[3],
(uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[4],
(uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[5]
);
} else { // AF_INET6
net_type = NETWORK_IPV6;
// create IPv6 string
struct sockaddr_in6 *in6 = (struct sockaddr_in6*) ifa->ifa_addr;
inet_ntop(AF_INET6, &in6->sin6_addr, addr, sizeof(addr));
sprintf( mask, "%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x",
(uint8_t)ifa->ifa_netmask->sa_data[2],
(uint8_t)ifa->ifa_netmask->sa_data[3],
(uint8_t)ifa->ifa_netmask->sa_data[4],
(uint8_t)ifa->ifa_netmask->sa_data[5],
(uint8_t)ifa->ifa_netmask->sa_data[6],
(uint8_t)ifa->ifa_netmask->sa_data[7],
(uint8_t)ifa->ifa_netmask->sa_data[8],
(uint8_t)ifa->ifa_netmask->sa_data[9],
(uint8_t)ifa->ifa_netmask->sa_data[10],
(uint8_t)ifa->ifa_netmask->sa_data[11],
(uint8_t)ifa->ifa_netmask->sa_data[12],
(uint8_t)ifa->ifa_netmask->sa_data[13],
(uint8_t)ifa->ifa_netmask->sa_data[14],
(uint8_t)ifa->ifa_netmask->sa_data[15],
(uint8_t)ifa->ifa_netmask->sa_data[16],
(uint8_t)ifa->ifa_netmask->sa_data[17]
);
if( ifa->ifa_ifu.ifu_broadaddr != NULL ){
sprintf( bc, "%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x",
(uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[2],
(uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[3],
(uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[4],
(uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[5],
(uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[6],
(uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[7],
(uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[8],
(uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[9],
(uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[10],
(uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[11],
(uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[12],
(uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[13],
(uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[14],
(uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[15],
(uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[16],
(uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[17]
);
} else {
sprintf( bc, "" );
};
};
m_pDBC->addLocalNetwork( nif_id, net_type, addr, mask, gw, bc );
#ifdef DEBUG
sprintf( tBuffer, "Detected Network Interface: %s [%s]", ifa->ifa_name, addr );
LOG(tBuffer);
#endif
nif_id = 0;
nif_aux_id = 0;
router_id = 0;
nif_type = NIF_LOOPBACK;
net_type = NETWORK_IPV4;
res_type = HARDWARE_NIF_LOOPBACK;
nif_mode = ADDRESS_DISABLED;
};
freeifaddrs( ifaddr );
};
};
void hardwareManager::enumerateHardware( void ){
char tBuffer[CTEXT];
DIR * dFD = NULL;
struct dirent * pDR = NULL;
//ToDo: Check Ability to work without Kernel and DBC
//if( m_pKernel == NULL ) return;
if( m_pDBC == NULL ) return;
#ifdef DEBUG
LOG("HW Enumeration Started!");
#endif
// Moved to a constructor!!
//m_nServerNodeID = m_pKernel->getServerNodeId();
//m_nServerID = m_pKernel->getServerId();
//m_nSiteID = m_pKernel->getSiteId();
/* Add Network Interfaces */
//if( !m_pDBC->cleanResources( true ) ){
// LOG_ERROR("Cannot DeActivate Old Ressources!");
// return false;
//};
if( !m_pDBC->wipeServerResources() ){
LOG_ERROR("Cannot Wipe Old Ressources!");
return;
};
enumerateNIFS();
/* Check HID Devices */
struct hid_device_info * pDevs;
uint8_t DCBCount;
//Enumerate USB devices with the given IDs
pDevs = hid_enumerate( 0x16c0, 0x05df );
if( pDevs!=NULL ){
struct hid_device_info * pCDev = pDevs;
//Count the number of returned devices
for( DCBCount = 0; pCDev!=NULL; DCBCount++ ) pCDev = pCDev->next;
//Allocate a buffer for the relays
if( DCBCount > 0 ){
DC_BOARD tDCB;
//Fill the relay structs
pCDev = pDevs;
for( int idx = 0; idx < DCBCount; idx++ ){
//Save the path to this device
memset( tDCB.path, 0, MAX_PATH_LEN );
strncpy( tDCB.path, pCDev->path, MAX_PATH_LEN );
// The product string is USBRelayx where x is number of relays read to the \0 in case there are more than 9
tDCB.relay_count = atoi((const char *)&pCDev->product_string[8]);
//Open it to get more details
hid_device * handle;
handle = hid_open_path( tDCB.path );
if( handle ){
unsigned char buf[9];
//Get the features of the device
buf[0] = 0x01;
if( hid_get_feature_report( handle, buf, sizeof(buf)) == -1 ){
LOG_ERROR("hid_get_feature_report");
pCDev = pCDev->next;
hid_close( handle );
continue;
};
//Set the serial number (0x0 for termination)
memset( tDCB.serial, 0x0, (HID_DCR_SERIIAL_LENGTH+1) );
memcpy( tDCB.serial, buf, HID_DCR_SERIIAL_LENGTH );
//Byte 7 in the response contains the target_state of the relays
tDCB.state = buf[7];
hid_close( handle );
#ifdef DEBUG
//Output the device enumeration details if verbose is on
LOG("HID DCB Found");
sprintf(tBuffer, " Type: %04hx::%04hx", pCDev->vendor_id, pCDev->product_id);
LOG(tBuffer);
sprintf(tBuffer, " Path: %s", pCDev->path );
LOG(tBuffer);
sprintf(tBuffer, " Serial_number: %ls", pCDev->serial_number );
LOG(tBuffer);
sprintf(tBuffer, " Manufacturer: %ls", pCDev->manufacturer_string);
LOG(tBuffer);
sprintf(tBuffer, " Product: %ls", pCDev->product_string);
LOG(tBuffer);
sprintf(tBuffer, " Release: %hx", pCDev->release_number);
LOG(tBuffer);
sprintf(tBuffer, " Interface: %d", pCDev->interface_number);
LOG(tBuffer);
sprintf(tBuffer, " Number of Relays = %d", tDCB.relay_count);
LOG(tBuffer);
//If debug are on, output individual relay details
for( int k = 0; k < tDCB.relay_count; k++ ){
if( tDCB.state & 1 << k ){
sprintf(tBuffer, " %s_%d=1", tDCB.serial, k + 1);
} else {
sprintf(tBuffer, " %s_%d=0", tDCB.serial, k + 1);
};
LOG(tBuffer);
};
#endif
m_pDBC->addLocalDCB( m_nSiteID, pCDev->path, tDCB.serial, tDCB.relay_count, tDCB.state );
} else {
LOG_ERROR("unable to open HID device");
};
pCDev = pCDev->next;
};
};
hid_free_enumeration( pDevs );
};
/* Add devices from DEV */
dFD = opendir("/dev");
if( dFD != NULL ) {
while( ( pDR = readdir( dFD ))!= NULL ){
if( strcasestr( pDR->d_name, "video" ) == pDR->d_name ) {
createResourceVIDEO( pDR->d_name );
continue;
};
if( strcasestr( pDR->d_name, "ttyS" ) == pDR->d_name ){
createResourceUART( pDR->d_name );
continue;
};
// RaspberyPI Hardware
if( strcasestr( pDR->d_name, "ttyAMA" ) == pDR->d_name ){
createResourceUART( pDR->d_name );
continue;
};
if( strcasestr( pDR->d_name, "ttyUSB" ) == pDR->d_name ){
createResourceUART( pDR->d_name );
continue;
};
};
closedir( dFD );
};
//m_bHardwareEnumerated = true;
m_pDBC->updateSystemInfo( &m_sSYS_INFO );
};
uint32_t hardwareManager::createResourceUART( CSTR devName ){
uint32_t RetVal = 0;
char tBuffer[CTEXT];
/* Enumerate BuiltIn Serial */
#ifdef DEBUG
sprintf( tBuffer, "Serial Device: %s", devName );
LOG( tBuffer );
#endif
char dev_name[CTEXT];
int fd = -1;
struct serial_struct ss;
sprintf( dev_name, "/dev/%s", devName );
fd = open( dev_name, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK );
if (-1 == fd) {
sprintf( tBuffer, "Cannot open '%s': %d, %s\\n", dev_name, errno, strerror(errno));
LOG_ERROR( tBuffer );
} else {
if ( 0 && ( -1 == xioctl(fd, TIOCGSERIAL, &ss) )){
LOG_ERROR("TIOCGSERIAL");
} else {
#ifdef DEBUG
sprintf( tBuffer, "Serial Port[Port:0x%X IRQ:%d BB:%d Line:%d Type:%d Flags:%X]",
ss.port,
ss.irq,
ss.baud_base,
ss.line,
ss.type,
ss.flags
);
LOG( tBuffer );
#endif
memset( tBuffer, 0, CTEXT );
getTTyDesc( devName, tBuffer );
if( tBuffer[0] ) {
LOG( tBuffer );
uint32_t tID = m_pDBC->addLocalUART(/*m_nServerNodeID,*/1, 19200, 8, 'N', 1.0f, dev_name );
if ( tID ) {
m_pDBC->addResource( /*m_nServerNodeID,*/ HARDWARE_UART, tBuffer, tID );
};
} else {
LOG_ERROR("Device Not Initialized at Boot Time!");
};
};
close(fd);
};
return RetVal;
};
uint32_t hardwareManager::createResourceVIDEO( CSTR devName ){
uint32_t RetVal = 0;
char tBuffer[256];
/* Enumerate Video Capture */
#ifdef DEBUG_EXTRA
sprintf( tBuffer, "Video Source: %s", devName );
LOG( tBuffer );
#endif
struct v4l2_capability cap;
//struct v4l2_cropcap cropcap;
//struct v4l2_crop crop;
struct v4l2_format fmt;
struct v4l2_frmivalenum sprm;
char dev_name[CTEXT];
int fd = -1;
struct stat st;
sprintf( dev_name, "/dev/%s", devName );
if (-1 == stat( dev_name, &st )) {
sprintf( tBuffer, "Cannot identify '%s': %d, %s\\n", dev_name, errno, strerror(errno));
LOG_ERROR( tBuffer );
return 0;
};
if (!S_ISCHR(st.st_mode)) {
sprintf( tBuffer, "%s is no devicen", dev_name);
LOG_ERROR( tBuffer );
return 0;
};
#ifdef DEBUG
LOG( dev_name );
#endif
fd = open(dev_name, O_RDWR /* required */ | O_NONBLOCK, 0);
if (-1 == fd) {
sprintf( tBuffer, "Cannot open '%s': %d, %s\\n", dev_name, errno, strerror(errno));
LOG_ERROR( tBuffer );
} else {
if( -1 == xioctl(fd, VIDIOC_QUERYCAP, &cap) ){
if (EINVAL == errno) {
sprintf( tBuffer, "%s is no V4L2 device", dev_name );
LOG_ERROR( tBuffer );
} else {
LOG_ERROR( "VIDIOC_QUERYCAP" );
};
close(fd);
return 0;
};
if (!(cap.capabilities & V4L2_CAP_VIDEO_CAPTURE)) {
#ifdef DEBUG
sprintf(tBuffer, "%s is no video capture device", dev_name);
LOG_ERROR( tBuffer );
#endif
close(fd);
return 0;
};
CLEAR(fmt);
fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
/* Preserve original settings as set by v4l2-ctl for example */
if( -1 == xioctl(fd, VIDIOC_G_FMT, &fmt)){
LOG_ERROR("VIDIOC_G_FMT");
} else {
CLEAR( sprm );
if(-1 == xioctl(fd, VIDIOC_ENUM_FRAMEINTERVALS, &sprm) && 0 ){
LOG_ERROR("VIDIOC_ENUM_FRAMEINTERVALS");
} else {
uint16_t fps = 15;
switch ( sprm.type ) {
case V4L2_FRMIVAL_TYPE_DISCRETE: LOG("1DISCRETE"); break;
case V4L2_FRMIVAL_TYPE_CONTINUOUS: LOG("2DISCRETE"); break;
case V4L2_FRMIVAL_TYPE_STEPWISE: LOG("3DISCRETE"); break;
};
#ifdef DEBUG
sprintf( tBuffer, "Grabber{%s}{%s}[%dx%d@%d]", cap.card, cap.driver, fmt.fmt.pix.width,fmt.fmt.pix.height, fps );
LOG( tBuffer );
#endif
uint32_t mid = m_pDBC->addLocalCam( (CSTR)cap.card, (CSTR)cap.driver, dev_name, fmt.fmt.pix.width, fmt.fmt.pix.height, fps );
//uint64_t mid = m_pDBC->addLocalMediaSource( m_nSiteID, dev_name, fmt.fmt.pix.width, fmt.fmt.pix.height );
//m_pDBC->addNodeSocket( m_nServerNodeID, mid, NODE_SOCK_TYPE_ANALOG_VIDEO_GRABBER, NODE_SOCK_MODE_OUT, false, dev_name, tBuffer );
RetVal = m_pDBC->addResource( HARDWARE_ANALOG_VIDEO_IN, dev_name, mid );
};
};
close(fd);
};
return RetVal;
};
uint32_t hardwareManager::createResourceUDCB( CSTR devName ){
uint32_t RetVal = 0;
char tBuffer[256];
return RetVal;
};
bool hardwareManager::assignResource( hardwareResource *ptr, bool protected_mode ){
LOG("ASSIGN HWR");
if ( ptr == NULL ) return false;
if( protected_mode ) m_mVectorProtector.lock();
LOG("LOCKED");
m_vResources.push_back( ptr );
LOG("ADDED");
if( protected_mode ) m_mVectorProtector.unlock();
return true;
};
bool hardwareManager::resignResource( hardwareResource *ptr, bool protected_mode ){
LOG("RESIGN HWR");
if( ptr == NULL ) return false;
if( protected_mode ) m_mVectorProtector.lock();
LOG("LOCKED");
if( m_vResources.size() ) {
for( VECTOR_HW_RESOURCES::iterator idx = m_vResources.begin(); idx < m_vResources.end(); idx++ ) {
if( (*idx) == ptr ) {
LOG("FOUND");
m_vResources.erase( idx );
LOG("ERASED");
break;
};
};
} else {
LOG("NO RES!");
};
LOG("UNLOCKED");
if( protected_mode ) m_mVectorProtector.unlock();
return true;
};
hardwareResource *hardwareManager::requestResource( HARDWARE_PROVIDERS type, uint32_t id ){
hardwareResource *RetVal = NULL;
m_mVectorProtector.lock();
if( m_vResources.size() ) {
for( VECTOR_HW_RESOURCES::iterator idx = m_vResources.begin(); idx < m_vResources.end(); idx++ ) {
#ifdef DEBUG_EXTRA
char tB[256];
sprintf( tB, "Check Resources RR[%d] RI[%d] ?? CR[%d] CI[%d]", type, id, (*idx)->getProviderType(), (*idx)->getDbId() );
LOG( tB );
#endif
if( ((*idx)->getProviderType() == type ) && ( (*idx)->getDbId() == id ) ) {
RetVal = (*idx);
break;
};
};
} else {
LOG("No Resources!!");
};
m_mVectorProtector.unlock();
return RetVal;
};
DBC_INT_LIST *hardwareManager::requestResourcesByType( HARDWARE_PROVIDERS type ){
DBC_INT_LIST *RetVal = NULL;
#ifdef DEBUG
char tBuffer[128];
sprintf( tBuffer, "Requested Resource type: %d", type );
LOG( tBuffer );
#endif
m_mVectorProtector.lock();
if( m_vResources.size() ) {
#ifdef DEBUG
LOG("Have Some Resources!");
#endif
RetVal = new DBC_INT_LIST();
if( RetVal ) {
#ifdef DEBUG
LOG("RetVal Created!");
#endif
for( VECTOR_HW_RESOURCES::iterator idx = m_vResources.begin(); idx < m_vResources.end(); idx++ ) {
#ifdef DEBUG
sprintf( tBuffer, "Have Resource type: %d", (*idx)->getHardwareType() );
LOG( tBuffer );
#endif
if( (*idx)->getProviderType() == type ) {
#ifdef DEBUG
LOG("Matched!");
#endif
RetVal->push_back((*idx)->getDbId());
};
};
} else {
LOG_ERROR("Cannot Create DBC_INT_LIST");
};
};
m_mVectorProtector.unlock();
return RetVal;
};
#include <sys/types.h>
#include <signal.h>
bool hardwareManager::updateSysInfo( DBC_SYS_LOAD_INFO *ptr ){
if ( ptr == NULL) return false;
struct sysinfo SI;
struct statvfs DI;
ptr->CPU_CORES = get_nprocs();
if( sysinfo( &SI ) == 0 ){
float f_load = 100.f / (float)( ptr->CPU_CORES * ( 1 << SI_LOAD_SHIFT ) );
ptr->cpu1 = SI.loads[0] * f_load;
ptr->cpu5 = SI.loads[1] * f_load;
ptr->cpu15 = SI.loads[2] * f_load;
ptr->T_MEM = SI.totalram * SI.mem_unit;
ptr->C_MEM = ( SI.totalram - SI.freeram ) * SI.mem_unit;
ptr->mem = 100.0f * (float)ptr->C_MEM / (float)ptr->T_MEM;
#ifdef DEBUG_EXTRA
char tB[128];
sprintf( tB, "Total Mem: %" PRIu64 " Free: %" PRIu64 " Perc: %.2f", SI.totalram, SI.freeram, ptr->mem );
LOG( tB );
#endif
if ( ptr->mem > 80.0f ) {
LOG_ERROR( "Try to free some caches!" );
/*
To free pagecache:
# echo 1 > /proc/sys/vm/drop_caches
To free dentries and inodes:
# echo 2 > /proc/sys/vm/drop_caches
To free pagecache, dentries and inodes:
# echo 3 > /proc/sys/vm/drop_caches
*/
//system( "echo 1 > /proc/sys/vm/drop_caches" );
if( m_bCacheCleanCounter ) {
m_bCacheCleanCounter--;
} else {
// KillSellf
// kill( getpid(), 9 );
};
};
} else {
LOG_ERROR("Error while getting System Info!");
};
//const uint32_t MB = 1 << 10;//(1024 * 1024);// * 1024;
if( statvfs("/", &DI) == 0 ){
ptr->T_DISK = ( DI.f_blocks * (unsigned long long) DI.f_frsize ) >> 10;// / MB;
//cDISK = ( DI.f_bavail * (unsigned long long) DI.f_bsize ) >> 10;// / MB;
ptr->C_DISK = ptr->T_DISK - ( ( DI.f_bfree * (unsigned long long) DI.f_bsize ) >> 10 );
ptr->disk = 100.0f * (float)ptr->C_DISK / (float)ptr->T_DISK;
} else {
LOG_ERROR("Error while getting Disk Info!");
};
//Temperature reading
ptr->temperature = -1;
if( fileExist( "/sys/class/thermal" ) ) {
char tB[128];
// Check first 8 zones to find CPU one
for ( uint8_t i = 0; i < 8; i++ ) {
sprintf( tB, "/sys/class/thermal/thermal_zone%d", i );
if ( fileExist( tB ) ) {
sprintf( tB, "/sys/class/thermal/thermal_zone%d/type", i );
if ( fileExist( tB ) ) {
FILE *fd = fopen( tB, "r" );
readLine( fd, tB, 128 );
fclose(fd);
if ( strcasestr(tB,"cpu")!=NULL || strcasestr(tB,"x86_pkg")!=NULL || strcasestr(tB,"acpitz")!=NULL ) {
sprintf( tB, "/sys/class/thermal/thermal_zone%d/temp", i );
FILE *fd = fopen( tB, "r" );
readLine( fd, tB, 128 );
fclose(fd);
ptr->temperature = ((float) atoll( tB )) / 1000.0f;
break;
};
} else continue;
} else break;
};
};
return m_pDBC->updateServerUtilisation( ptr );
};
void hardwareManager::clearAllResources( void ){
};
#undef CLEAR
#undef LOG
#undef LOG_ERROR