bool CDataUnitCache::GetApplianceByDataUnitKeyID(
                const unsigned char* const i_pDataUnitKeyID,
                int i_iDataUnitKeyIDMaxLen,
                utf8char* const o_wsApplianceNetworkAddress,
                int i_iMaxApplianceNetworkAddressLen )
{
    FATAL_ASSERT( i_pDataUnitKeyID );
    FATAL_ASSERT( i_iDataUnitKeyIDMaxLen == KMS_KEY_ID_SIZE );
    FATAL_ASSERT( i_iMaxApplianceNetworkAddressLen <= KMS_MAX_NETWORK_ADDRESS );

    // assumes o_wsApplianceNetworkAddress points to at least KMS_MAX_NETWORK_ADDRESS

    Lock();

    int i;
    for( i = 0; i < m_iSize; i++ )
    {
        if( memcmp(m_pCache[i].m_aDataUnitKeyID,
                i_pDataUnitKeyID, KMS_KEY_ID_SIZE) == 0 )
        {
            strncpy( o_wsApplianceNetworkAddress, 
                m_pCache[i].m_wsApplianceNetworkAddress, 
                i_iMaxApplianceNetworkAddressLen );
            o_wsApplianceNetworkAddress[i_iMaxApplianceNetworkAddressLen-1] = '\0';

            Unlock();

            return true;
        }
    }

    Unlock();

    return false;
}
void CLogInterface::Initialize_Dynamic( bool delete_all_logs )
{
    static const uint64_t SECONDS_PER_HOUR = 3600;

    FATAL_ASSERT( StaticInitialized == true );

    std::lock_guard< std::mutex > lock( LogLock );

    FATAL_ASSERT( DynamicInitialized == false );

    // Remove old logs if they exist, logs that are not removable are attached to currently running processes
    std::basic_ostringstream< wchar_t > file_pattern_string;
    file_pattern_string << LogPath << ServiceName << L"*.txt";

    std::vector< std::wstring > matching_file_names;
    IP::File::Enumerate_Matching_Files( file_pattern_string.rdbuf()->str(), matching_file_names );

    auto current_time = IP::Time::Get_Current_System_Time();

    // Try to remove all matching log files that are older than an hour
    for ( uint32_t i = 0; i < matching_file_names.size(); ++i )
    {
        auto file_time = IP::Time::Get_File_Last_Modified_Time( LogPath + matching_file_names[ i ] );
        auto time_difference = current_time - file_time;

        if ( delete_all_logs || std::chrono::duration_cast< std::chrono::seconds >( time_difference ).count() > SECONDS_PER_HOUR )
        {
            IP::File::Delete_File( LogPath + matching_file_names[ i ] );
        }
    }

    LogProcess.reset( new CLoggingProcess( LOGGING_PROCESS_PROPERTIES ) );

    DynamicInitialized = true;
}
Esempio n. 3
0
/**********************************************************************************************************************
	CProcessBase::Handle_Release_Mailbox_Request -- handles the ReleaseMailboxRequest message

		source_process_id -- id of the process source of the message
		message -- message to handle
					
**********************************************************************************************************************/
void CProcessBase::Handle_Release_Mailbox_Request( EProcessID::Enum source_process_id, const shared_ptr< const CReleaseMailboxRequest > &request )
{
	FATAL_ASSERT( source_process_id == EProcessID::CONCURRENCY_MANAGER );

	EProcessID::Enum shutdown_process_id = request->Get_Process_ID();
	FATAL_ASSERT( shutdown_process_id != EProcessID::CONCURRENCY_MANAGER && shutdown_process_id != EProcessID::LOGGING );

	ShutdownMailboxes.insert( shutdown_process_id );
}
/**********************************************************************************************************************
	CPlatformThreadImpl::Launch_Thread -- creates and starts a new Windows thread

		stack_size -- desired size of thread's user stack, 0 for default (1 MB)
		execution_function -- what function the thread should run
		run_context -- parameter to the execution function

**********************************************************************************************************************/
void CPlatformThreadImpl::Launch_Thread( uint64 stack_size, const ThreadExecutionFunctionType &execution_function, void *run_context )
{
	FATAL_ASSERT( ThreadHandle == nullptr );

	TranslationContext.Initialize( execution_function, run_context );

	ThreadHandle = reinterpret_cast< HANDLE >( 
		::_beginthreadex( NULL, static_cast< uint32 >( stack_size ), CPlatformThreadImpl::Run_Thread, &TranslationContext, 0, NULL ) );

	FATAL_ASSERT( ThreadHandle != nullptr );
}
/**********************************************************************************************************************
	CThreadProcessBase::Run -- execution logic

		context -- the process execution context that this process is being run under
					
**********************************************************************************************************************/
void CThreadProcessBase::Run( const CProcessExecutionContext &context )
{
	FATAL_ASSERT( !HasBeenRun );

	HasBeenRun = true;

	CPlatformThread *thread = context.Get_Platform_Thread();
	FATAL_ASSERT( thread != nullptr );

	thread->Create_And_Run( 0, ThreadExecutionFunctionType( this, &CThreadProcessBase::Thread_Function ), thread );
}
void CEnumConverter::Register_Enum_Internal( const Loki::TypeInfo &enum_type_info, const std::string &enum_name, EConvertibleEnumProperties properties )
{
	FATAL_ASSERT( Enums.find( enum_type_info ) == Enums.cend() );

	std::string upper_enum_name;
	IP::String::To_Upper_Case( enum_name, upper_enum_name );
	FATAL_ASSERT( EnumsByName.find( upper_enum_name ) == EnumsByName.cend() );

	CConvertibleEnum *enum_object = new CConvertibleEnum( enum_name, properties );
	Enums[ enum_type_info ] = enum_object;
	EnumsByName[ upper_enum_name ] = enum_object;
}
int CAgentLoadBalancer::GetKWKID (
                                  int    i_Index,
                                  Long64 i_lKMAID,
                                  struct soap * const i_pstSoap,
                                  UTF8_KEYID o_pKWKID,
                                  bool * const o_pbClientAESKeyWrapSetupError)
{
    FATAL_ASSERT(i_Index >= 0 && i_Index <= m_iClusterNum);
    FATAL_ASSERT(i_lKMAID != 0);
    FATAL_ASSERT(i_pstSoap);
    FATAL_ASSERT(o_pKWKID);
    FATAL_ASSERT(o_pbClientAESKeyWrapSetupError);

    *o_pbClientAESKeyWrapSetupError = false;
    
    // check if the KMA for this cluster index is at a version supporting
    // AES key wrap
    if (!AESKeyWrapSupported(i_Index))
    {
        strcpy(o_pKWKID, "");
        return TRUE;
    }

    // AES Key Wrap Mode

    struct KWKEntry* pKWKentry = GetKWK(i_lKMAID);

    if (pKWKentry == NULL)
    {
        const char* sURL = GetHTTPSURL(
                i_Index,
                m_pProfile->m_iPortForAgentService);

        pKWKentry = CreateKWK(i_lKMAID, i_pstSoap, sURL, o_pbClientAESKeyWrapSetupError);

        if (pKWKentry == NULL)
        {
            return FALSE;
        }
    }

#if defined(DEBUG) && defined(METAWARE)
    log_printf("CAgentLoadBalancer::GetKWKID(): KWK IDhex=%s\n",
            pKWKentry->m_acKWKID,
            sizeof (UTF8_KEYID));
#endif
    
    strncpy(o_pKWKID, pKWKentry->m_acKWKID, sizeof(UTF8_KEYID));
    o_pKWKID[sizeof(UTF8_KEYID)-1] = '\0';

    return TRUE;
};
/**********************************************************************************************************************
	CConvertibleEnum::Register_Entry -- registers a string and integer value pair as convertible

		entry_name -- corresponding string value
		value -- integer to convert to/from

**********************************************************************************************************************/
void CConvertibleEnum::Register_Entry( const std::string &entry_name, uint64 value )
{
	std::string upper_entry_name;
	NStringUtils::To_Upper_Case( entry_name, upper_entry_name );

	auto name_iter = NameToValueTable.find( upper_entry_name );
	FATAL_ASSERT( name_iter == NameToValueTable.end() );

	auto value_iter = ValueToNameTable.find( value );
	FATAL_ASSERT( value_iter == ValueToNameTable.end() );

	NameToValueTable[ upper_entry_name ] = value;
	ValueToNameTable[ value ] = upper_entry_name;
}
/**********************************************************************************************************************
	CEnumConverter::Register_Enum_Entry_Internal -- registers a string<->integer conversion pair within an enum

		enum_type_id -- type info of the enum to register a conversion entry for
		entry_name -- string representation of the enum entry value
		entry_value -- integer value of the enum entry

**********************************************************************************************************************/		
void CEnumConverter::Register_Enum_Entry_Internal( const std::type_info &enum_type_id, const std::string &entry_name, uint64 entry_value )
{
	CConvertibleEnum *enum_object = Find_Enum( enum_type_id );
	FATAL_ASSERT( enum_object != nullptr );

	enum_object->Register_Entry( entry_name, entry_value );
}
Esempio n. 10
0
///=====================================================
/// 
///=====================================================
NetworkMessageDefinition::NetworkMessageDefinition(MessageID id, const std::string& name, NetworkCallback callback /*= nullptr*/) :
m_id(id),
m_name(name),
m_callback(callback){
	FATAL_ASSERT(s_definitionRegistry.find(m_id) == s_definitionRegistry.cend());
	s_definitionRegistry.emplace(m_id, this);
}
Esempio n. 11
0
/**********************************************************************************************************************
	CProcessBase::Handle_Shutdown_Mailboxes -- services all mailboxes that are pending shutdown, either erasing
		an associated outbound frame if we don't have the mailbox, or erasing the mailbox.  Notifies the manager
		that each mailbox has been released.
					
**********************************************************************************************************************/
void CProcessBase::Handle_Shutdown_Mailboxes( void )
{
	for ( auto iter = ShutdownMailboxes.cbegin(); iter != ShutdownMailboxes.cend(); ++iter )
	{
		EProcessID::Enum process_id = *iter;

		auto interface_iter = Mailboxes.find( process_id );
		if ( interface_iter == Mailboxes.end() )
		{
			auto frame_iter = PendingOutboundFrames.find( process_id );
			if ( frame_iter != PendingOutboundFrames.end() )
			{
				PendingOutboundFrames.erase( frame_iter );
			}
		}
		else
		{
			// should have been sent in the flush that preceding this call
			FATAL_ASSERT( PendingOutboundFrames.find( process_id ) == PendingOutboundFrames.end() );

			Mailboxes.erase( interface_iter );
		}

		Remove_Process_ID_From_Tables( process_id );

		// let the manager know we've release this interface
		Send_Manager_Message( shared_ptr< const IProcessMessage >( new CReleaseMailboxResponse( process_id ) ) );
	}

	ShutdownMailboxes.clear();
}
Esempio n. 12
0
void Clock::RemoveAlarm(const std::string& event_name)
{
	auto theAlarmIter = m_alarms.find(event_name);
	FATAL_ASSERT(theAlarmIter != m_alarms.end());
	delete theAlarmIter->second;
	m_alarms.erase(theAlarmIter);
}
Esempio n. 13
0
/**********************************************************************************************************************
	CProcessBase::Log -- requests a message be written to the log file for this virtual process

		message -- message to output to the log file
					
**********************************************************************************************************************/
void CProcessBase::Log( const std::wstring &message )
{
	// actual logging thread should override this function and never call the baseclass
	FATAL_ASSERT( ID != EProcessID::LOGGING );

	Send_Process_Message( EProcessID::LOGGING, shared_ptr< const IProcessMessage >( new CLogRequestMessage( Properties, message ) ) );
}
Esempio n. 14
0
///////////////////////////////////////////////////////////////////////////////////////
// public key methods
///////////////////////////////////////////////////////////////////////////////////////
CPublicKey::CPublicKey()
{
   m_pPublicKeyImpl = InitializePKeyImpl();
   
   FATAL_ASSERT( m_pPublicKeyImpl != NULL );
   
}
Esempio n. 15
0
CPrivateKey::CPrivateKey()
{
   m_pPKeyImpl = InitializePKeyImpl();
   
   FATAL_ASSERT( m_pPKeyImpl != NULL );
   
}
void CDatabaseTaskBase::Set_Parent( ICompoundDatabaseTask *parent )
{
	FATAL_ASSERT( parent != nullptr );

	Parent = parent;
	ID = parent->Get_ID();
}
Esempio n. 17
0
	void deinit()
	{
		FATAL_ASSERT( (posts->next == nullptr )
			&& (posts->prev == nullptr )
			&& (posts->free) );

		free(buffer);
	}
Esempio n. 18
0
/**********************************************************************************************************************
	CProcessBase::Register_Handler -- registers a message handlers for a process message

		message_type_info -- the C++ type of the message class
		handler -- message handling delegate
					
**********************************************************************************************************************/
void CProcessBase::Register_Handler( const std::type_info &message_type_info, const shared_ptr< IProcessMessageHandler > &handler )
{
	Loki::TypeInfo key( message_type_info );

	FATAL_ASSERT( MessageHandlers.find( key ) == MessageHandlers.end() );

	MessageHandlers[ key ] = handler;
}
bool CAgentLoadBalancer::AESKeyUnwrap (
                                       int * const io_pIndex,
                                       const WRAPPED_KEY i_pAESWrappedKey,
                                       KEY o_pPlainTextKey)
{
    FATAL_ASSERT(io_pIndex);
    FATAL_ASSERT(*io_pIndex >= 0);
    FATAL_ASSERT(o_pPlainTextKey);
    FATAL_ASSERT(i_pAESWrappedKey);

    struct KWKEntry * pKWKEntry = GetKWK(GetKMAID(*io_pIndex));

    if (pKWKEntry == NULL)
    {
        Log(AGENT_LOADBALANCER_AESKEYUNWRAP_GETKWK_RETURNED_NULL,
                NULL,
                m_aCluster[*io_pIndex].m_wsApplianceNetworkAddress,
                NULL);
        *io_pIndex = CAgentLoadBalancer::AES_KEY_UNWRAP_ERROR;
        
        return false;
    }

#if defined(DEBUG) && defined(METAWARE)
    char sHexKWK[2*KMS_MAX_KEY_SIZE+1];
    ConvertBinaryToUTF8HexString( sHexKWK, pKWKEntry->m_acKWK, sizeof (pKWKEntry->m_acKWK));
    log_printf("CAgentLoadBalancer::AESKeyUnwrap(): KWK hex=%s\n",
            sHexKWK);
#endif
    
    if (aes_key_unwrap(pKWKEntry->m_acKWK,
        sizeof (pKWKEntry->m_acKWK),
        i_pAESWrappedKey,
        o_pPlainTextKey, 4) != 0)
    {
        Log(AGENT_LOADBALANCER_AESKEYUNWRAP_KEY_UNWRAP_FAILED,
                NULL,
                m_aCluster[*io_pIndex].m_wsApplianceNetworkAddress,
                NULL);
        *io_pIndex = CAgentLoadBalancer::AES_KEY_UNWRAP_ERROR;
        return false;
    }

    return true;
}
void CODBCObjectBase::Push_User_Error( DBErrorStateType error_state, const std::wstring &error_description )
{
	FATAL_ASSERT( error_state != DBEST_SUCCESS );

	ErrorState = error_state;

	Errors.clear();
	Errors.push_back( SODBCError( -1, L"*USER*", error_description ) );
}
Esempio n. 21
0
NetMessage::NetMessage(uint8_t id) : 
	m_inOrderID(0),
	m_reliableID(0)
{
	m_messageDefinition = NetMessage::GetNetMessageDefinitionByID(id);
	FATAL_ASSERT(m_messageDefinition != nullptr);
	Init(m_buffer, NetMessage_MTU);
	//WriteBytes((void*)id, sizeof(uint8_t));
}
void CProcessStatics::Initialize( void )
{
	if ( Initialized )
	{
		return;
	}

	FATAL_ASSERT( ProcessHandle == THREAD_LOCAL_INVALID_HANDLE );
	FATAL_ASSERT( ConcurrencyManagerHandle == THREAD_LOCAL_INVALID_HANDLE );

	ProcessHandle = Allocate_Thread_Local_Storage();
	FATAL_ASSERT( ProcessHandle != THREAD_LOCAL_INVALID_HANDLE );

	ConcurrencyManagerHandle = Allocate_Thread_Local_Storage();
	FATAL_ASSERT( ConcurrencyManagerHandle != THREAD_LOCAL_INVALID_HANDLE );

	Initialized = true;
}
Esempio n. 23
0
/**********************************************************************************************************************
	CProcessBase::Handle_Shutdown_Self_Request -- handles the ShutdownSelf request

		source_process_id -- id of the process source of the message
		message -- the ShutdownThread request
					
**********************************************************************************************************************/
void CProcessBase::Handle_Shutdown_Self_Request( EProcessID::Enum source_process_id, const shared_ptr< const CShutdownSelfRequest > &message )
{
	FATAL_ASSERT( source_process_id == EProcessID::CONCURRENCY_MANAGER );
	FATAL_ASSERT( !Is_Shutting_Down() );

	if ( message->Get_Is_Hard_Shutdown() )
	{
		State = EPS_SHUTTING_DOWN_HARD;
	}
	else
	{
		State = EPS_SHUTTING_DOWN_SOFT;
	}

	On_Shutdown_Self_Request();

	Send_Manager_Message( shared_ptr< const IProcessMessage >( new CShutdownSelfResponse() ) );	
}
Esempio n. 24
0
WidgetBase* UISystem::CreateWidget(const std::string& widgetType, const TiXmlNode* data) {
	WidgetBase* wid;

	auto result = s_widgetFactory.find(widgetType);

	FATAL_ASSERT(result != s_widgetFactory.end());
	wid = result->second(data);

	return wid;
}
Esempio n. 25
0
/**********************************************************************************************************************
	CProcessBase::Handle_Message -- central message handling dispatcher

		key -- message sender
		message -- the process message to handle
					
**********************************************************************************************************************/
void CProcessBase::Handle_Message( EProcessID::Enum process_id, const shared_ptr< const IProcessMessage > &message )
{
	const IProcessMessage *msg_base = message.get();

	Loki::TypeInfo hash_key( typeid( *msg_base ) );
	auto iter = MessageHandlers.find( hash_key );
	FATAL_ASSERT( iter != MessageHandlers.end() );

	iter->second->Handle_Message( process_id, message );
}
Esempio n. 26
0
///---------------------------------------------------------------------------------
///
///---------------------------------------------------------------------------------
void Profiler::UpdateProfiler()
{
    for (std::map< std::string, ProfileData >::iterator categoryIter = s_profileDataMap.begin(); categoryIter != s_profileDataMap.end(); ++categoryIter)
    {
        ProfileData& data = categoryIter->second;
        data.UpdateTimes();

    }

    FATAL_ASSERT( s_startStopProfilers.empty() );
}
Esempio n. 27
0
Clock::Clock(Clock* parentClock)
	: m_parent(parentClock),
	m_currentTime(0),
	m_deltaSeconds(0),
	m_paused(false),
	m_timeScale(1.f),
	m_maximumDelta(0.5f)
{
	FATAL_ASSERT(parentClock);
	parentClock->m_children.push_back(this);
}
Esempio n. 28
0
void CLogInterface::Shutdown_Dynamic( void )
{
    FATAL_ASSERT( StaticInitialized == true );

    if ( DynamicInitialized )
    {
        std::lock_guard< std::mutex > lock( LogLock );

        LogProcess = nullptr;

        DynamicInitialized = false;
    }
}
Esempio n. 29
0
///=====================================================
/// 
///=====================================================
void JobManager::Update(){
	if (m_threads.empty()){
		ProcessJob(ThreadType::AnyType);
	}

	Job* completedJob;
	while (m_finishedJobs.Dequeue(&completedJob)){
		FATAL_ASSERT(completedJob->m_callback != nullptr);
		completedJob->m_callback(completedJob->m_callbackArgs);

		delete completedJob;
	}
}
Esempio n. 30
0
/**********************************************************************************************************************
	CProcessBase::Run -- base execution logic

		context -- the tbb context that this process is being run under
					
**********************************************************************************************************************/
void CProcessBase::Run( const CProcessExecutionContext & /*context*/ )
{
	if ( State == EPS_INITIALIZING )
	{
		State = EPS_RUNNING;
	}

	if ( Is_Shutting_Down() )
	{
		return;
	}

	Per_Frame_Logic_Start();

	// message and scheduled task logic
	Service_Message_Frames();

	TaskScheduler->Service( Get_Current_Process_Time() );

	Per_Frame_Logic_End();

	FATAL_ASSERT( !( Should_Reschedule() && Is_Shutting_Down() ) );

	Service_Reschedule();

	// Awkward but necessary due to shutdown sequence
	// We need to flush before we call Handle_Shutdown_Mailboxes, but that function also needs to send messages that go out this moment too,
	// so we do before-and-after flushes
	Flush_Regular_Messages();
	Handle_Shutdown_Mailboxes();
	Flush_Regular_Messages();

	if ( Is_Shutting_Down() )
	{
		FATAL_ASSERT( PendingOutboundFrames.size() == 0 );
		Mailboxes.clear();
	}
}