Example #1
0
void gui_load()
{
    debug_start();

    pnd_app_get_list();
    cfg_gui_read();
    gui_load_skin();

    if ( ! ( nh = pnd_notify_init() ) )
    {
        debug_error ( "PND INOTIFY init problem spotted\n" );
    }

    if ( ! ( nh2 = pnd_dbusnotify_init() ) )
    {
        debug_error ( "PND DBUSINOTIFY init problem spotted\n" );
    }

    initStatusCalls();
    cpuUsage();
    getCPULoad();

    set_cpu( pmenu->cpu_mhz );

    debug_end();
}
QString sysInfo::getMinimalStats(){
    netStat();
    cpuUsage();
    memPerc();
    bytesTransmitted = getSizeUnit(bytesTransmitted);
    bytesReceived = getSizeUnit(bytesReceived);
    //Sende the CPU usage %, the RAM usage %, the amount of transmitted data in the applicable unit, the amount of received data in the applicable unit
    QString stats = cpuPerc + "%" + "#" + memoryLoad + "%" + "#"+ bytesTransmitted + "#" + bytesReceived;
    return stats;
}
QString sysInfo::getDetailedStats(){
    cpuUsage();
    memPerc();
    netStat();
    cpuStats();
    getDiskDetails();
    osVersion();
    listProcesses();
    QString stats = "";
    bytesTransmitted = getSizeUnit(bytesTransmitted);
    bytesReceived = getSizeUnit(bytesReceived);
    //Add the netstat info to the stats string
    stats = stats + "Data Transmitted," + bytesTransmitted + "#Data Received," + bytesReceived + "#Packets Transmitted," + packetsTransmitted + "#Packets Received," + packetsReceived + "#Errors Transmitting," + transmitErrors + "#Errors Receiving," + receiveErrors;
    //Add the cpuStats to the stats string
    stats = stats + "#Number of Processors," + _cpuCount;
    //Add the OS Version
    stats = stats + "#Operating System," + osVers;
    //Add the various logical drive details
    for(int i = 0; i < filesystems.length(); i++){
        QString cap = capacitys.at(i);
        cap.chop(cap.length() - cap.indexOf("."));
        cap = getSizeUnit(cap);
        QString used = useds.at(i);
        used = getSizeUnit(used);
        stats = stats + "#Drive Label," + filesystems.at(i) + ",Total Capacity," + cap+ ",Used Space," + used;
    }
    //Add RAM and CPU
    physMem.chop(physMem.length()- physMem.indexOf("."));
    physMem = getSizeUnit(physMem);
    freePhysMem.chop(freePhysMem.length() - freePhysMem.indexOf("."));
    freePhysMem = getSizeUnit(freePhysMem);
    stats = stats + "#Total RAM,"+physMem+"#Used RAM,"+freePhysMem+"#% RAM in use,"+memoryLoad+"#% CPU in use,"+cpuPerc;
    //Add the process/task related info
    stats = stats + "#Amount of Processes active," + procCount;
    for(int j = 0; j < procIDs.length(); j++){
        stats = stats + "#" + procIDs.at(j) + "," + procNames.at(j);
    }
    return stats;
}
Example #4
0
void ProcessServer::updateDemon()
{
	dword lastRegister = 0;
	dword lastTimeSync = 0;
	dword pingTime = 0;

	while ( running() && !m_bShutdownCompleted )
	{
		Thread::sleep( 1000 );

		if (! m_MetaClient.loggedIn() )
		{
			LOG_STATUS( "ProcessServer", "Establishing connection to the metaserver" );

			// attempt to connect
			if ( m_MetaClient.open( m_Context.metaAddress, m_Context.metaPort ) > 0 )
			{
				if ( m_MetaClient.login( m_Context.uid, m_Context.pw ) < 0 )
				{
					LOG_STATUS( "ProcessServer", "Failed to login to the metaserver" );
					m_MetaClient.close();	// failed to login
				}
				else
				{
					LOG_STATUS( "ProcessServer", "Connected to the metaserver" );
					// select the correct game
					m_MetaClient.selectGame( m_Context.gameId );
				}
			}
		}
		
		m_MetaClient.update();
		if ( m_MetaClient.loggedIn() )
		{
			if ( lastRegister < (Time::seconds() - REGISTER_TIME) )
			{
				AutoLock lock( &m_Lock );

				MetaClient::Server server;
				server.gameId = m_Context.gameId;
				server.type = MetaClient::PROCESS_SERVER;
				server.flags = 0;
				server.name = m_Context.name;
				server.shortDescription.format( "CPU: %d%%, MEM: %d%%", cpuUsage(), memoryUsage() );

				server.description = server.shortDescription + "\n\n";
				for(int i=0;i<m_ProcessList.size();i++)
				{
					Process & proc = m_ProcessList[ i ];
					if ( (proc.flags & ProcessClient::PF_RUNNING) == 0 )
						continue;
					server.description += CharString().format( "%s\n", proc.name.cstr() );
				}

				server.address = m_Context.address;
				server.port = m_Context.port;
				server.maxClients = m_Context.maxClients;
				server.clients = clientCount();
				server.data = CharString().format("processGroup=%u;networkGroup=%u;processCount=%u;cpuUsage=%d;memoryUsage=%d", 
					m_Context.processGroup, m_Context.networkGroup, m_ProcessList.size(), cpuUsage(), memoryUsage() );

				lock.release();

				if ( m_MetaClient.registerServer( server ) < 0 )
					lastRegister = (Time::seconds() - REGISTER_TIME) + 30;		// failed, try again in 30 seconds
				else
					lastRegister = Time::seconds();
			}

			if ( m_Context.syncClock && lastTimeSync < (Time::seconds() - SYNC_CLOCKS_TIME) )
			{
				// get the current time from the metaserver
				dword currentTime = m_MetaClient.getTime();
				if ( currentTime > 0 )
				{
					LOG_STATUS( "ProcessServer", "Syncronizing system time to %s", Time::format( currentTime, "%c" ).cstr() );

					if (! Time::setTime( currentTime ) )
						LOG_STATUS( "ProcessServer", "Failed to set the system time!" );

					lastTimeSync = Time::seconds();
				}
				else
				{
					LOG_STATUS( "ProcessServer", "Failed to syncronize system time from MetaServer!" );
					lastTimeSync = (Time::seconds() - SYNC_CLOCKS_TIME) + 300;		// try again in another 5 min
				}
			}
		}

		AutoLock lock( &m_Lock );

		bool shutdownComplete = true;			// have all child processes stopped

		// check for log updates
		for(int i=0;i<m_ActiveLog.size();i++)
		{
			dword logId = m_ActiveLog[ i ];

			FileDisk & file = m_LogFile[ logId ];

			try {
				if ( file.position() > file.size() )
					file.setPosition( 0 );		// file has been rotated... reset read position

				dword read = file.size() - file.position();
				if ( read > 0 )
				{
					if ( read > MAX_LOG_SIZE )
					{
						file.setPosition( file.size() - MAX_LOG_SIZE );
						read = MAX_LOG_SIZE;
					}
				
					char * pLines = new char[ read + 1 ];
					pLines[ read ] = 0;

					file.read( pLines, read );

					send( m_LogClient[ logId ], ProcessClient::CLIENT_RECV_LOG_UPDATE ) << logId << CharString(pLines);

					delete [] pLines;
				}
			}
			catch( FileDisk::FileError )
			{
				LOG_STATUS( "ProcessServer", CharString().format("Log Read Error, logFile = %s, logId = %u", file.fileName(), logId) );

				// close the previously open file
				file.close();
				// attempt to reopen the file
				file.open( file.fileName() );
			}
		}

		// check process list
		for(int i=0;i<m_ProcessList.size();i++)
		{
			Process & proc = m_ProcessList[ i ];
			if ( m_ProcessInfo.find( proc.processId ).valid() )
			{
				ProcessInfo & info = m_ProcessInfo[ proc.processId ];

				proc.flags |= ProcessClient::PF_RUNNING;
				if ( (proc.flags & ProcessClient::PF_DISABLED) == 0 )
				{
					// make sure the process is still running
					if (! ::Process::active( info.m_pHandle ) )
					{
						proc.flags &= ~ProcessClient::PF_RUNNING;

						if ( ! m_Shutdown )
						{
							if ( info.m_nRestartTime != 0 && Time::seconds() < info.m_nRestartTime )
								continue;		// not time to restart yet, continue onto the next process..

							// process has exited, increment the number of restarts, then calculate the next restart
							// time increasing the wait time each time the process exits
							info.m_nRestarts += 1;
							info.m_nRestartTime = Time::seconds() + (60 * (info.m_nRestarts * info.m_nRestarts) );

							int exitCode = ::Process::exitCode( info.m_pHandle );
							::Process::close( info.m_pHandle );

							CharString message;
							message.format( "Process %u exit, name = %s, exec = %s, arg = %s, exitCode = %d, restarts = %u", 
								proc.processId, proc.name.cstr(), proc.executable.cstr(), proc.arguments.cstr(), exitCode, info.m_nRestarts );
							LOG_STATUS( "ProcessServer", message );


							// send report if exit code is negative
							if ( exitCode < 0 )
								m_MetaClient.sendChat( 0, CharString().format("/report %s", message.cstr()) );

							// restart the process..
							Path exePath( proc.executable );
							void * pStart = ::Process::start( CharString().format("%s %s", exePath.file().cstr(), proc.arguments.cstr()), 
								exePath.directory() );
							if ( pStart == NULL )
							{
								LOG_STATUS( "ProcessServer", "Process %u failed to restart", proc.processId );

								m_ProcessInfo.remove( proc.processId );
								proc.flags |= ProcessClient::PF_DISABLED;
							}
							else
							{
								LOG_STATUS( "ProcessServer", "Process %u restarted", proc.processId );
								info.m_pHandle = pStart;
							}
						}
						else
						{
							int exitCode = ::Process::exitCode( info.m_pHandle );

							LOG_STATUS( "ProcessServer", "Process Stopped, name = %s, exitCode = %d", proc.name.cstr(), exitCode );
							::Process::close( info.m_pHandle );

							m_ProcessInfo.remove( proc.processId );
						}
						
					}
					else if ( m_Shutdown )
					{
						shutdownComplete = false;	
						stopProcess( proc.processId );
					}
					else if ( info.m_nRestartTime != 0 && Time::seconds() > info.m_nRestartTime )
					{
						// process has been running long enough to clear the restart time.
						info.m_nRestartTime = 0;
						info.m_nRestarts = 0;
					}
				}
				else
				{
					if (! ::Process::active( info.m_pHandle ) )
					{
						LOG_STATUS( "ProcessServer", "Process Stopped, name = %s", proc.name.cstr() );
						::Process::close( info.m_pHandle );

						m_ProcessInfo.remove( proc.processId );
					}
					else
						stopProcess( proc.processId );
				}
			}
			else
			{
				proc.flags &= ~ProcessClient::PF_RUNNING;
				if ( (proc.flags & ProcessClient::PF_DISABLED) == 0 && !m_Shutdown )
				{
					LOG_STATUS( "ProcessServer", "Starting Process %u, name = %s, exec = %s, arg = %s", 
						proc.processId, proc.name.cstr(), proc.executable.cstr(), proc.arguments.cstr() );

					Path exePath( proc.executable );
					void * pStart = ::Process::start( CharString().format("%s %s", exePath.file().cstr(), proc.arguments.cstr()),
						exePath.directory() );
					if ( pStart == NULL )
					{
						proc.flags |= ProcessClient::PF_DISABLED;

						LOG_STATUS( "ProcessServer", "Process %u Failed to Start, name = %s, exec = %s", 
							proc.processId, proc.name.cstr(), proc.executable.cstr() );
					}
					else
						m_ProcessInfo[ proc.processId ].m_pHandle = pStart;
				}
			}
		}

		pingTime++;
		if ( pingTime > 15 )
		{
			// ping all clients
			for(int i=0;i<clientCount();i++)
				send( client(i), ProcessClient::PING );
			
			pingTime = 0;
		}

		// check for shutdown
		if ( m_Shutdown && shutdownComplete )
		{
			m_bShutdownCompleted = true;

			if ( m_RebootOnShutdown )
				rebootMachine();
		}

		lock.release();
	}
}
Example #5
0
void ProcessServer::onReceive( dword client, byte message, const InStream & input )
{
	//LOG_STATUS( "ProcessServer","onReceive, client = %u (%s), message = 0x%x", client, clientAddress(client), message );

	switch( message )
	{
	case ProcessClient::SERVER_LOGIN:
		{
			dword job;
			input >> job;
			CharString uid;
			input >> uid;
			CharString md5;
			input >> md5;

			bool result = false;

			MetaClient::Profile profile;
			if ( m_MetaClient.loginByProxy( uid, md5, profile ) > 0 )
			{
				LOG_STATUS( "ProcessServer", CharString().format("Login %s, client %u (%s)", profile.name.cstr(), client, clientAddress(client)) );
				result = (profile.flags & (MetaClient::ADMINISTRATOR|MetaClient::SERVER)) != 0;
			}
			else
				LOG_STATUS( "ProcessServer", CharString().format("Login failed, client %u (%s)", client, clientAddress(client)) );

			AutoLock lock( &m_Lock );

			m_ClientValid[ client ] = result;
			send( client, ProcessClient::CLIENT_JOB_DONE ) << job << result;
		}
		break;
	case ProcessClient::SERVER_SESSION_LOGIN:
		{
			dword job;
			input >> job;
			dword sessionId;
			input >> sessionId;

			bool result = false;

			MetaClient::Profile profile;
			if ( m_MetaClient.loginByProxy( sessionId, profile ) > 0 )
			{
				LOG_STATUS( "ProcessServer", CharString().format("Login %s, client %u (%s)", profile.name.cstr(), client, clientAddress(client)) );
				result = (profile.flags & MetaClient::ADMINISTRATOR) != 0;
			}
			else
				LOG_STATUS( "ProcessServer", CharString().format("Login failed, client %u (%s)", client, clientAddress(client)) );

			AutoLock lock( &m_Lock );

			m_ClientValid[ client ] = result;
			send( client, ProcessClient::CLIENT_JOB_DONE ) << job << result;
		}
		break;
	case ProcessClient::SERVER_SEND_PROCESS_LIST:
		if ( validateClient( client ) )
		{
			dword job;
			input >> job;

			// send process list to the server
			AutoLock lock( &m_Lock );
			send( client, ProcessClient::CLIENT_RECV_PROCESS_LIST ) << job << m_ProcessList;
		}
		break;
	case ProcessClient::SERVER_SEND_CONFIG:
		if ( validateClient( client ) )
		{
			dword job;
			input >> job;
			dword processId;
			input >> processId;

			CharString config;
			CharString configFile;

			if ( processId != 0 )
			{
				Process proc;
				if ( findProcess( processId, proc ) )
					configFile = proc.config;
			}
			else
				configFile = m_Context.config;

			LOG_STATUS( "ProcessServer", CharString().format("Send Config, client %u (%s), configFile = %s", 
				client, clientAddress(client), configFile.cstr()) );

			// attempt to load the configuration file
			char * pConfig = FileDisk::loadTextFile( configFile );
			if ( pConfig != NULL )
			{
				config = pConfig;
				delete [] pConfig;
			}

			send( client, ProcessClient::CLIENT_RECV_CONFIG ) << job << config;
		}
		break;
	case ProcessClient::SERVER_RECV_CONFIG:
		if ( validateClient( client ) )
		{
			dword job;
			input >> job;
			dword processId;
			input >> processId;
			CharString config;
			input >> config;

			bool jobDone = false;

			CharString configFile;
			if ( processId != 0 )
			{
				Process proc;
				if ( findProcess( processId, proc ) )
					configFile = proc.config;
			}
			else
				configFile = m_Context.config;

			LOG_STATUS( "ProcessServer", "Recv Config, client %u (%s), configFile = %s", 
				client, clientAddress(client), configFile.cstr() );

			// save the new file
			jobDone = FileDisk::saveTextFile( configFile, CharString( config ) );

			send( client, ProcessClient::CLIENT_JOB_DONE ) << job << jobDone;
		}
		break;
	case ProcessClient::SERVER_SEND_LOG:
		if ( validateClient( client ) )
		{
			dword job;
			input >> job;
			dword processId;
			input >> processId;

			CharString log;
			CharString logFile;
			if ( processId != 0 )
			{
				// send log of one of our processes
				Process proc;
				if ( findProcess( processId, proc ) )
					logFile = proc.log;
			}
			else
				logFile = m_Context.logFile;

			FileDisk file;
			if ( file.open( logFile ) )
			{
				dword size = file.size();
				if ( size > MAX_LOG_SIZE )
				{
					file.setPosition( size - MAX_LOG_SIZE );
					size = MAX_LOG_SIZE;
				}

				char * pLog = new char[ size + 1];
				pLog[ size ] = 0;

				file.read( pLog, size );
				file.close();

				// save to string
				log = pLog;
				// release allocated memory
				delete [] pLog;
			}
			else
				log = "Failed to open log file!";


			send( client, ProcessClient::CLIENT_RECV_LOG ) << job << log;
		}
		break;
	case ProcessClient::SERVER_ADD_PROCESS:
		if ( validateClient( client ) )
		{
			dword job;
			input >> job;
			Process proc;
			input >> proc;

			AutoLock lock( &m_Lock );

			proc.processId = m_NextProcessId++;
			m_ProcessList.push( proc );

			LOG_STATUS( "ProcessServer", "Add Process, client = %u (%s), processId = %u, name = %s, exec = %s", 
				client, clientAddress(client), proc.processId, proc.name.cstr(), proc.executable.cstr() );

			saveProcessList();
			send( client, ProcessClient::CLIENT_JOB_DONE ) << job << true;
		}
		break;
	case ProcessClient::SERVER_SET_PROCESS:
		if ( validateClient( client ) )
		{
			dword job;
			input >> job;
			Process proc;
			input >> proc;

			bool jobDone = false;

			AutoLock lock( &m_Lock );

			int pi = findProcess( proc.processId );
			if ( pi >= 0 )
			{
				m_ProcessList[pi] = proc;
				jobDone = true;

				LOG_STATUS( "ProcessServer", "Set Process, client = %u (%s), processId = %u, name = %s, exec = %s", 
					client, clientAddress(client), proc.processId, proc.name.cstr(), proc.executable.cstr() );

				saveProcessList();
			}

			send( client, ProcessClient::CLIENT_JOB_DONE ) << job << jobDone;
		}
		break;
	case ProcessClient::SERVER_DEL_PROCESS:
		if ( validateClient( client ) )
		{
			dword job;
			input >> job;
			dword processId;
			input >> processId;

			bool jobDone = false;

			AutoLock lock( &m_Lock );

			int pi = findProcess( processId );
			if ( pi >= 0 )
			{
				LOG_STATUS( "ProcessServer", "Delete Process, name = %s, client = %u (%s), processId = %u", 
					m_ProcessList[pi].name.cstr(), client, clientAddress(client), processId );

				// stop the actual process if any
				if ( m_ProcessInfo.find( processId ).valid() )
				{
					::Process::stop( m_ProcessInfo[ processId ].m_pHandle );
					m_ProcessInfo.remove( processId );
				}

				// remove from the list
				m_ProcessList.remove( pi );
				jobDone = true;

				saveProcessList();
			}

			send( client, ProcessClient::CLIENT_JOB_DONE ) << job << jobDone;
		}
		break;
	case ProcessClient::SERVER_STOP_PROCESS:
		if ( validateClient( client ) )
		{
			dword job;
			input >> job;
			dword processId;
			input >> processId;

			bool jobDone = false;

			AutoLock lock( &m_Lock );

			int pi = findProcess( processId );
			if ( pi >= 0 )
			{
				m_ProcessList[ pi ].flags |= ProcessClient::PF_DISABLED;
				jobDone = true;

				LOG_STATUS( "ProcessServer", "Stop Process, name = %s, client = %u (%s), processId = %u", 
					m_ProcessList[pi].name.cstr(), client, clientAddress(client), processId );

				saveProcessList();
			}

			send( client, ProcessClient::CLIENT_JOB_DONE ) << job << jobDone;
		}
		break;
	case ProcessClient::SERVER_START_PROCESS:
		if ( validateClient( client ) )
		{
			dword job;
			input >> job;
			dword processId;
			input >> processId;

			bool jobDone = false;

			AutoLock lock( &m_Lock );

			int pi = findProcess( processId );
			if ( pi >= 0 )
			{
				m_ProcessList[ pi ].flags &= ~ProcessClient::PF_DISABLED;
				jobDone = true;

				LOG_STATUS( "ProcessServer", "Start Process, name = %s, client = %u (%s), processId = %u", 
					m_ProcessList[pi].name.cstr(), client, clientAddress(client), processId );
				saveProcessList();
			}

			send( client, ProcessClient::CLIENT_JOB_DONE ) << job << jobDone;
		}
		break;
	case ProcessClient::SERVER_RESTART_PROCESS:
		if ( validateClient( client ) )
		{
			dword job;
			input >> job;
			dword processId;
			input >> processId;

			bool jobDone = false;

			AutoLock lock( &m_Lock );

			Process proc;
			if ( findProcess( processId, proc ) )
			{
				if ( m_ProcessInfo.find( processId ).valid() )
				{
					jobDone = stopProcess( processId );

					LOG_STATUS( "ProcessServer", "Restart Process, name = %s, client = %u (%s), processId = %u,", 
						proc.name.cstr(), client, clientAddress(client), processId );
				}
			}

			send( client, ProcessClient::CLIENT_JOB_DONE ) << job << jobDone;
		}
		break;
	case ProcessClient::SERVER_SEND_STATUS:
		if ( validateClient( client ) )
		{
			dword job;
			input >> job;

			AutoLock lock( &m_Lock );

			ProcessClient::Status status;
			status.processGroup = m_Context.processGroup;
			status.networkGroup = m_Context.networkGroup;
			status.cpuUsage = cpuUsage();
			status.memoryUsage = memoryUsage();	
			status.processCount = 0;

			for(int i=0;i<m_ProcessList.size();i++)
				if ( (m_ProcessList[i].flags & ProcessClient::PF_RUNNING) != 0 )
					status.processCount++;

			send( client, ProcessClient::CLIENT_RECV_STATUS ) << job << status;
		}
		break;
	case ProcessClient::SERVER_STOP_ALL:
		if ( validateClient( client ) )
		{
			dword job;
			input >> job;

			bool jobDone = false;

			AutoLock lock( &m_Lock );
			for(int i=0;i<m_ProcessList.size();i++)
				m_ProcessList[i].flags |= ProcessClient::PF_DISABLED;
			saveProcessList();

			jobDone = true;

			LOG_STATUS( "ProcessServer", CharString().format("Stop All, client = %u (%s)", client, clientAddress(client)) );
			send( client, ProcessClient::CLIENT_JOB_DONE ) << job << jobDone;
		}
		break;
	case ProcessClient::SERVER_START_ALL:
		if ( validateClient( client ) )
		{
			dword job;
			input >> job;

			bool jobDone = false;

			AutoLock lock( &m_Lock );
			for(int i=0;i<m_ProcessList.size();i++)
				m_ProcessList[i].flags &= ~ProcessClient::PF_DISABLED;
			saveProcessList();

			jobDone = true;
			LOG_STATUS( "ProcessServer", CharString().format("Start All, client = %u (%s)", client, clientAddress(client)) );
			send( client, ProcessClient::CLIENT_JOB_DONE ) << job << jobDone;
		}
		break;
	case ProcessClient::SERVER_RESTART_ALL:
		if ( validateClient( client ) )
		{
			dword job;
			input >> job;

			bool jobDone = false;

			AutoLock lock( &m_Lock );
			for(int i=0;i<m_ProcessList.size();i++)
				stopProcess( m_ProcessList[i].processId );

			jobDone = true;
			LOG_STATUS( "ProcessServer", CharString().format("Restart All, client = %u (%s)", client, clientAddress(client)) );
			send( client, ProcessClient::CLIENT_JOB_DONE ) << job << jobDone;
		}
		break;
	case ProcessClient::SERVER_REBOOT:
		if ( validateClient( client ) )
		{
			dword job;
			input >> job;

			bool jobDone = reboot();
			if ( jobDone )
				LOG_STATUS( "ProcessServer", CharString().format("Server Rebooting, client = %u (%s)", client, clientAddress(client)) );

			send( client, ProcessClient::CLIENT_JOB_DONE ) << job << jobDone;
		}
		break;
	case ProcessClient::SERVER_EXIT:
		if ( validateClient( client ) )
		{
			dword job;
			input >> job;

			// signal all running processes to stop
			bool jobDone = shutdown();
			if ( jobDone )
				LOG_STATUS( "ProcessServer", CharString().format("Server Exiting, client = %u (%s)", client, clientAddress(client)) );

			send( client, ProcessClient::CLIENT_JOB_DONE ) << job << jobDone;
		}
		break;
	case ProcessClient::SERVER_TERMINATE_PROCESS:
		if ( validateClient( client ) )
		{
			dword job;
			input >> job;
			dword processId;
			input >> processId;

			bool jobDone = false;

			AutoLock lock( &m_Lock );

			Process proc;
			if ( findProcess( processId, proc ) )
			{
				// just terminate the process
				if ( m_ProcessInfo.find( processId ).valid() )
				{
					::Process::stop( m_ProcessInfo[ processId ].m_pHandle );
					jobDone = true;

					LOG_STATUS( "ProcessServer", "Terminated Process, name = %s, client = %u (%s), processId = %u,", 
						proc.name.cstr(), client, clientAddress(client), processId );
				}
			}

			send( client, ProcessClient::CLIENT_JOB_DONE ) << job << jobDone;
		}
		break;
	case ProcessClient::SERVER_OPEN_LOG:
		if ( validateClient( client ) )
		{
			dword job;
			input >> job;
			dword processId;
			input >> processId;

			CharString logFile;
			if ( processId != 0 )
			{
				// send log of one of our processes
				Process proc;
				if ( findProcess( processId, proc ) )
					logFile = proc.log;
			}
			else
				logFile = m_Context.logFile;

			dword logId = m_NextLogId++;

			AutoLock lock( &m_Lock );

			FileDisk & file = m_LogFile[ logId ];
			if ( file.open( logFile ) )
			{
				LOG_STATUS( "ProcessServer", "Open Log, logFile = %s, logId = %u, clientId = %u", logFile.cstr(), logId, client );

				m_ActiveLog.push( logId );
				m_LogClient[ logId ] = client;
				m_ClientLog[ client ].push( logId );
			}
			else
			{
				LOG_STATUS( "ProcessServer", "Open Log Failed, logFile = %s, clientId = %u", logFile.cstr(), client );

				// failed to open file
				m_LogFile.remove( logId );
				// set id to 0 for error
				logId = 0;
			}

			send( client, ProcessClient::CLIENT_RECV_LOG_ID ) << job << logId;
		}
		break;
	case ProcessClient::SERVER_CLOSE_LOG:
		if ( validateClient( client ) )
		{
			dword logId;
			input >> logId;

			AutoLock lock( &m_Lock );

			LOG_STATUS( "ProcessServer", CharString().format("Close Log, logId = %u, client = %u", logId, client) );

			m_ActiveLog.removeSearch( logId );
			m_LogFile.remove( logId );
			m_LogClient.remove( logId );
			m_ClientLog[ client ].removeSearch( logId );
		}
		break;
	case ProcessClient::SERVER_SEARCH_LOGS:
		if ( validateClient( client ) )
		{
			dword job;
			input >> job;
			ProcessClient::SearchLogRequest req;
			input >> req;

			LOG_STATUS( "ProcessServer", CharString().format("Search Log, clientId = %u", client) );

			CharString result;
			if( req.filemask.find('/') >= 0 || req.filemask.find('\\') >= 0 )
			{	// this should never happen, unless the user has a hacked client
				LOG_STATUS( "ProcessServer", CharString().format("Search Log, invalid filemask received from clientId = %u", client) );
				result = "Failed";
			}
			else
			{
				result = searchLogFiles( req.filemask, req.searchString, req.isRegExp, req.searchLevel, req.resolveClientId );
			}

			send( client, ProcessClient::CLIENT_RECV_SEARCHRESULT ) << job << result;
		}
		break;
	case ProcessClient::PING:
		send( client, ProcessClient::PONG );
		break;
	case ProcessClient::PONG:
		break;
	default:
		{
			LOG_ERROR( "ProcessServer", CharString().format("Bad Message, client = %u (%s), message = %d", client, clientAddress(client), message) );
			removeClient( client );
		}
		break;
	}
}
Example #6
0
void VoxMain::run()
{
    int modesw = 3;
    uint64_t cnt = 0;
    timeval tvchk = {0, 0};
    timeval tvcur = {0, 0};
    std::string datastr = "";

    INFORMATION("(MAIN) start of loop");

    pinMode(modesw, INPUT);
    pullUpDnControl(modesw, PUD_UP); 
    gettimeofday(&tvchk, NULL);

    while(!m_exit)
    {
        int onoff = digitalRead(modesw);

        gettimeofday(&tvcur, NULL);

        if(onoff == LOW)
        {
            std::string retstr = "";

            if(m_mode > MD5)
                --m_mode;
            else
                m_mode = MD1;

            NOTICE("mode changed: mode=%d", m_mode);

            if(m_mode == MD1)  // control
            {
            }
            else if(m_mode == MD2) // vision
            {
                //if(!createProcess("/home/pi/mjpg-streamer/stop_mjpg.sh", retstr))
                //    ERROR("(MAIN) failed to stop mjpg-streamer");
            }
            else if(m_mode == MD3) // voice
            {
            }

            Servo* servo = VoxControl::getInstance().getServo();
            servo->setNeutral();
            VoxPlayer::getInstance().play("", false);

            delay(300);
        }

        if(timeSpan(tvchk, tvcur) >= 1.0f)
        {
            cpuUsage();
            tvchk.tv_sec = tvcur.tv_sec;
            tvchk.tv_usec = tvcur.tv_usec;
        }

        if((cnt % 100) == 0)
        {
            std::vector<std::string> addrs;
            getLocalIPString(addrs);

            m_myip = "";
            for(size_t i = 0; i < addrs.size(); i++)
            {
                std::string acls = "";
                extractSubString(acls, addrs[i].c_str(), 0, '.');

                if(isPositiveNumber(acls))
                {
                    if(acls != "127")
                        m_myip += addrs[i] + ", ";
                }
            }

            m_myip = strTrim(m_myip, " ,");

            std::string retstr = "";
            
            if(createProcess("/usr/bin/vcgencmd measure_temp", retstr))
            {
                strRemove(retstr, "temp=");
                strRemove(retstr, "'C");
                m_cputemp = atof(retstr.c_str());
            }

            m_appmem = getRss();
        }

        if((cnt % 2) == 0)
        {
            bool voice = VoxVoice::getInstance().isRunning();

            datastr = strFormat("%s|%d|%d|%d|%.1f|%.1f|%.1f|%.1f|%.1f|%.1f|%.1f|%.1f|%.1f|%d|%d|%d|%.1f|%d|%d|%s|%s",
                m_myip.c_str(),
                abs(MD1 - m_mode) + 1,
                m_stat,
                VoxSensor::getInstance().isFreeze(),
                VoxSensor::getInstance().getTemperature(),
                VoxSensor::getInstance().getHumidity(),
                VoxSensor::getInstance().getDistF(),
                VoxSensor::getInstance().getDistB(),
                VoxSensor::getInstance().getDistL(),
                VoxSensor::getInstance().getDistR(),
                m_cpuusage,
                m_cputemp,
                (float)(m_appmem / 1024.0 / 1024.0),
                VoxVision::getInstance().isFollowing(),
                VoxVision::getInstance().getPosX(),
                VoxVision::getInstance().getPosY(),
                VoxVision::getInstance().getRadius(),
                VoxVision::getInstance().getBallCount(),
                (voice) ? VoxVoice::getInstance().readyToGo() : 0,
                (voice) ? VoxVoice::getInstance().getReq().c_str() : "",
                (voice) ? VoxVoice::getInstance().getRsp().c_str() : ""
                );

            writeDataFile(datastr);
        }

        delay(150);
        ++cnt;
    }

    pinMode(modesw, OUTPUT);
    digitalWrite(modesw, LOW);

    INFORMATION("(MAIN) end of loop");
}
Example #7
0
void gui_draw()
{
    if ( category == SETTINGS )
        GLES2D_DrawTextureSimple ( background_settings, 0, 0 );
    else if ( category == MEDIA )
        GLES2D_DrawTextureSimple ( background_media, 0, 0 );
    else
        GLES2D_DrawTextureSimple ( background_applications, 0, 0 );

    if ( category == MEDIA )
    {
        menu_media_draw();
    }
	else if ( category == SETTINGS )
	{
        menu_settings_draw();
	}
    else
	{
	    app_scale();

        int y = gui->applications_box_y;
		int i = list_start[category];

		while (i < ( list_start[category]+gui->max_app_per_page ) )
		{
			if ( i < list_num[category] )
			{
				if ( i == list_curpos[category] )
				{
					GLES2D_DrawTextureSimple ( app_highlight, gui->applications_box_x, y );

                    GLES2D_SetFontCacheColor( applications[category]->name_cached[i], HEXTOR(gui->font_big_color_highlight), HEXTOG(gui->font_big_color_highlight), HEXTOB(gui->font_big_color_highlight), HEXTOA(gui->font_big_color_highlight) );
					GLES2D_DrawFontCache( applications[category]->name_cached[i], gui->applications_box_x + gui->icon_scale_max + 10, y + gui->applications_title_description_y );

                    y += applications[category]->name_cached[i]->height;

					if ( scroll_count < gui->applications_box_x - GLES2D_GetTextWidth ( fnt[SMALL], applications[category]->description[i] ) )
                        scroll_count = gui->applications_box_x + gui->icon_scale_max + gui->applications_box_w + 10;

                    if ( reset_scroll_count )
                    {
                        scroll_count = gui->applications_box_x + gui->icon_scale_max + 10;
                        reset_scroll_count = 0;
                        scroll_wait = 0;
                    }

                    GLES2D_SetFontColor( fnt[SMALL], HEXTOR(gui->font_small_color_highlight), HEXTOG(gui->font_small_color_highlight), HEXTOB(gui->font_small_color_highlight), HEXTOA(gui->font_small_color_highlight) );
                    GLES2D_DrawFontScroll( fnt[SMALL], scroll_count, y + gui->applications_title_description_y, gui->applications_box_x + gui->icon_scale_max + 10, gui->applications_box_x + gui->applications_box_w - 10,  applications[category]->description[i] );

                    if ( scroll_wait > 60 ) scroll_count--;
                    scroll_wait++;
				}
				else
				{
				    GLES2D_SetFontCacheColor( applications[category]->name_cached[i], HEXTOR(gui->font_big_color), HEXTOG(gui->font_big_color), HEXTOB(gui->font_big_color), HEXTOA(gui->font_big_color) );
					GLES2D_DrawFontCache( applications[category]->name_cached[i], gui->applications_box_x + gui->icon_scale_max + 10, y + gui->applications_title_description_y );

					y += applications[category]->name_cached[i]->height;

                    GLES2D_SetFontCacheColor( applications[category]->description_cached[i], HEXTOR(gui->font_small_color), HEXTOG(gui->font_small_color), HEXTOB(gui->font_small_color), HEXTOA(gui->font_small_color) );
					GLES2D_DrawFontCache( applications[category]->description_cached[i], gui->applications_box_x + gui->icon_scale_max + 10, y + gui->applications_title_description_y );
				}

				if ( applications[category]->icon[i] != NULL )
					GLES2D_DrawTextureScaledCentered( applications[category]->icon[i], gui->applications_box_x + 5 + gui->icon_scale_max / 2, y + 4, applications[category]->scale[i], applications[category]->scale[i] );
				else
					GLES2D_DrawTextureScaledCentered( no_icon, gui->applications_box_x + 5 + gui->icon_scale_max / 2, y + 4, applications[category]->scale[i], applications[category]->scale[i] );
			}
			i++;
			y += gui->applications_spacing;
		}

		if( list_num[category] )
		{
			if( preview_timer == 1 )
                gui_load_preview( category, list_curpos[category] );

			if( preview_timer > 0 )
			{
				preview_timer--;
			}
			else
			{
			    if ( ! video_playing )
			    {
                    if( alpha_preview < 250 ) alpha_preview += 5;
                    if( preview_scale < gui->preview_pic_w ) preview_scale += 10;

                    if( tmp_preview != NULL )
                    {
                        GLES2D_SetTextureAlpha ( tmp_preview, alpha_preview );
                        GLES2D_DrawTextureScaledCentered( tmp_preview, gui->preview_pic_x, gui->preview_pic_y, preview_scale, \
                            preview_scale / 1.666 );
                    }
                    else
                    {
                        GLES2D_SetTextureAlpha ( no_preview, alpha_preview );
                        GLES2D_DrawTextureScaledCentered( no_preview, gui->preview_pic_x, gui->preview_pic_y, preview_scale, \
                            preview_scale / 1.666 );
                    }
			    }
			}
		}

	}

    if ( gui->highlight_enabled )
    {
        if( alpha_up )
            alpha += 5;
        else
            alpha -= 5;

        if( alpha > 250 )
            alpha_up = 0;
        else if(alpha < 50 )
            alpha_up = 1;

        GLES2D_SetTextureAlpha ( highlight, alpha );
        GLES2D_DrawTextureCentered( highlight, category_icon_x[category], category_icon_y[category] );
    }

	int i;
	for ( i = 0; i < CATEGORY_COUNT; i++ )
	{
	    if ( category == i )
	    {
            GLES2D_DrawTextureCentered( category_icon_highlight[i], category_icon_x[i], category_icon_y[i] );
            if ( gui->show_category_title )
            {
                GLES2D_SetFontCacheColor( gui->title_cache[i], HEXTOR(gui->font_small_color), HEXTOG(gui->font_small_color), HEXTOB(gui->font_small_color), HEXTOA(gui->font_small_color) );
                GLES2D_DrawFontCacheCentered( gui->title_cache[i], category_icon_highlight[i]->dst->x + category_icon_highlight[i]->dst->w / 2, category_icon_highlight[i]->dst->y + category_icon_highlight[i]->dst->h + 15 );
            }
	    }
	    else
	    {
            GLES2D_DrawTextureCentered( category_icon[i], category_icon_x[i], category_icon_y[i] );
            if ( gui->show_category_title )
            {
                GLES2D_SetFontCacheColor( gui->title_cache[i], HEXTOR(gui->font_small_color), HEXTOG(gui->font_small_color), HEXTOB(gui->font_small_color), HEXTOA(gui->font_small_color) );
                GLES2D_DrawFontCacheCentered( gui->title_cache[i], category_icon[i]->dst->x + category_icon[i]->dst->w / 2, category_icon[i]->dst->y + category_icon[i]->dst->h + 15 );
            }
	    }
	}


    char cpu_char[16];
    memset( cpu_char, 0, 16 );
    sprintf( cpu_char, "%.0f%%", cpuUsage()*100 );
    //sprintf( cpu_char, "%i", pmenu->cpu_mhz );
    GLES2D_DrawFont( fnt[CPU], gui->cpu_text_x, gui->cpu_text_y, cpu_char );
	GLES2D_DrawTextureSimple( cpu_icon, gui->cpu_icon_x, gui->cpu_icon_y );

    GLES2D_DrawFont( fnt[CLOCK], gui->clock_text_x, gui->clock_text_y, get_time_string(TIME_24) );
    GLES2D_DrawTextureSimple( clock_icon, gui->clock_icon_x, gui->clock_icon_y );

    GLES2D_DrawTextureSimple( sd1_icon, gui->sd1_icon_x, gui->sd1_icon_y );
//    GLES2D_DrawFont( fnt[SD1], gui->sd1_text_x, gui->sd1_text_y, disk_space( cfg_fav_path[0] ) );

    GLES2D_DrawTextureSimple( sd2_icon, gui->sd2_icon_x, gui->sd2_icon_y );
//    GLES2D_DrawFont( fnt[SD2], gui->sd2_text_x, gui->sd2_text_y, disk_space( cfg_fav_path[1] ) );

}