Пример #1
0
void MainController::mdl_message_new(cxx::eventobj_t &evt)
{    
    xmpp::im::Message const* msg = evt;
    trace_msg(msg->from.username + ": " + msg->content);
}
Пример #2
0
void MainController::mdl_got_vcard(cxx::eventobj_t &evt)
{    
    xmpp::xep::VCard* obj = evt;
    core::string str = obj->vcard->name.name + "\n" + obj->vcard->name.title + "\n" + obj->vcard->orangizations.front().unit + "\n" + obj->vcard->mobiles.front().number;
    trace_msg(str);
}
Пример #3
0
Clause*
Component::getClauseToPropagate(
    Learning& learning )
{
    begin:;
    if( unfoundedSet.empty() )
    {
        assert( !done );
        clauseToPropagate = NULL;
        
        assert( !variablesWithoutSourcePointer.empty() || checkSourcePointersStatus() );
        assert( !variablesWithoutSourcePointer.empty() || checkFoundedStatus() );
        if( variablesWithoutSourcePointer.empty() )
            return NULL;
             
        if( first )
            computeGUSFirst();
        else
            computeGUS();
        
        assert( !unfoundedSet.empty() || variablesWithoutSourcePointer.empty() );
        assert( !unfoundedSet.empty() || checkSourcePointersStatus() );
        assert( !unfoundedSet.empty() || checkFoundedStatus() );
        if( unfoundedSet.empty() )
            return NULL;
        assert( clauseToPropagate == NULL );
        clauseToPropagate = learning.learnClausesFromUnfoundedSet( unfoundedSet );
        clausesToDelete.push_back( clauseToPropagate );
        trace_msg( unfoundedset, 2, "Reasons of unfounded sets: " << *clauseToPropagate );
        goto begin;
    }
    else
    {
        assert( clauseToPropagate != NULL );
        
        if( done )
        {
            Var variable = updateClauseToPropagate();
            if( variable == 0 )
            {
                assert( unfoundedSet.empty() );
                done = 0;
                clauseToPropagate = NULL;
                goto begin;
            }
            
            Clause* c = clauseToPropagate;
            if( solver.isTrue( variable ) )
            {
                assert( c->getAt( 0 ) == Literal( variable, FALSE ) );
                assert( solver.getDecisionLevel( variable ) == solver.getCurrentDecisionLevel() );

                c = new Clause( clauseToPropagate->size() );
                c->copyLiterals( *clauseToPropagate );
                if( solver.glucoseHeuristic() )
                    c->setLbd( clauseToPropagate->lbd() );
                c->setLearned();
                reset();
                assert( !done );
                assert( clauseToPropagate == NULL );
            }
            return c;              
        }
        
        if( conflict != 0 )
            return handleConflict();

        //Keep small clauses
        if( clauseToPropagate->size() <= 3 || unfoundedSet.size() == 1 )
        {
            Clause* c = inferFalsityOfUnfoundedAtoms();
            if( c != NULL )
                return c;

            goto begin;
        }
                        
        assert( unfoundedSet.size() >= 2 );        
        assert( clauseToPropagate->size() > 3 );
        
        assert( !done );
        clauseToPropagate->addLiteralInLearnedClause( Literal::null );
        clauseToPropagate->swapLiterals( 0, 1 );
        clauseToPropagate->swapLiterals( 0, clauseToPropagate->size() - 1 );

//        assert( unfoundedSet.empty() );
//        clauseToPropagate = NULL;
        done = 1;
        goto begin;
//        return NULL;
    }

    goto begin;
}
Пример #4
0
bool
Component::computeUnfoundedSet(
    Var variable )
{
    trace_msg( unfoundedset, 1, "Starting the computation of Unfounded Set from variable " << Literal( variable, POSITIVE ) );
    numberOfCalls++;
    vector< Var > toConsider;    
    assert( unfoundedSet.empty() );
    toConsider.push_back( variable );    
    visit( variable );
    for( unsigned int i = 0; i < toConsider.size(); i++ )
    {
        assert_msg( toConsider.size() <= solver.numberOfVariables(), "Loop!" );        
        Var next = toConsider[ i ];
        assert( solver.getComponent( next ) == this );
        assert( visited( next ) );
        
        assert( !solver.isFalse( next ) );
        if( getGUSData( next ).isFounded() )
            continue;
        
        if( getGUSData( next ).isAux() )
        {
            vector< Literal >& literals = getGUSData( next ).literals;
            #ifndef NDEBUG
            unsigned int count = 0;
            #endif

            for( unsigned int j = 0; j < literals.size(); j++ )
            {
                Literal currentLiteral = literals[ j ];
                Var currentVariable = currentLiteral.getVariable();
                assert( !solver.isFalse( currentLiteral ) );                
                if( currentLiteral.isNegative() || solver.getComponent( currentVariable ) != this || getGUSData( currentVariable ).isFounded() )
                    continue;
                assert( ++count );

                assert( solver.getComponent( currentVariable ) == this );
                if( visited( currentVariable ) )
                    continue;

                visit( currentVariable );
                toConsider.push_back( currentVariable );
            }
            assert_msg( count > 0 && count == getGUSData( next ).numberOfSupporting, count << " - " << getGUSData( next ).numberOfSupporting );
            unfoundedSet.push_back( next );
            continue;
        }

        bool hasSource = false;
        vector< Literal >& externalLiterals = getGUSData( next ).externalLiterals;        
        for( unsigned int j = 0; j < externalLiterals.size(); j++ )
        {
            Literal lit = externalLiterals[ j ];
            if( solver.isFalse( lit ) )
                continue;

            trace_msg( unfoundedset, 1, "Literal " << lit << " is an external source pointer of " << Literal( next, POSITIVE ) );
            propagateSourcePointer( next, lit );
            hasSource = true;
            break;
        }

        if( hasSource )
            continue;

        vector< Literal >& internalLiterals = getGUSData( next ).internalLiterals;
        for( unsigned int j = 0; j < internalLiterals.size(); j++ )
        {
            Literal lit = internalLiterals[ j ];
            assert( lit.isPositive() );
            if( solver.isFalse( lit ) )
                continue;

            Var var = lit.getVariable();
            assert( solver.getComponent( var ) == this );
            if( !getGUSData( var ).isFounded() )
            {
                if( visited( var ) )
                    continue;

                visit( var );
                toConsider.push_back( var );
            }
            else
            {
                trace_msg( unfoundedset, 1, "Literal " << lit << " is an internal source pointer of " << Literal( next, POSITIVE ) );
                propagateSourcePointer( next, lit );
                hasSource = true;
                break;
            }
        }

        if( hasSource )
            continue;

        assert( !unfoundedSet.existElement( next ) );
        unfoundedSet.push_back( next );
    }

    unsigned int j = 0;
    for( unsigned int i = 0; i < unfoundedSet.size(); i++ )
    {
        unfoundedSet[ j ] = unfoundedSet[ i ];
        if( getGUSData( unfoundedSet[ i ] ).isFounded() )
            continue;

        getGUSData( unfoundedSet[ i ] ).setInUnfoundedSet();
        j++;

        if( conflict || !solver.isTrue( unfoundedSet[ i ] ) )
            continue;

        assert( conflict == 0 );
        assert( unfoundedSet[ i ] != 0 );
        conflict = unfoundedSet[ i ];
    }
    unfoundedSet.shrink( j );

    return !unfoundedSet.empty();
}
Пример #5
0
 virtual void handle_time_out(const ACE_Time_Value &tv, const void *act = 0)
 {
     trace_msg("handle timeout.");
     super::handle_time_out(tv, act);
 }
Пример #6
0
Файл: core.c Проект: shenzhe/bsp
// Start main loop
int core_loop(void (* server_event)(BSP_CALLBACK *))
{
    BSP_THREAD *t = get_thread(MAIN_THREAD);
    if (!t)
    {
        trigger_exit(BSP_RTN_FATAL, "Main thread lost!");
    }

    // Servers
    BSP_VALUE *val = object_get_hash_str(runtime_settings, "servers");
    BSP_OBJECT *vobj = value_get_object(val);
    BSP_STRING *vstr = NULL;
    if (vobj && OBJECT_TYPE_ARRAY == vobj->type)
    {
        struct bsp_conf_server_t srv;
        BSP_OBJECT *vsrv = NULL;
        size_t varr_size = object_size(vobj), i;
        reset_object(vobj);
        for (i = 0; i < varr_size; i ++)
        {
            val = object_get_array(vobj, i);
            vsrv = value_get_object(val);
            if (vsrv && OBJECT_TYPE_HASH == vsrv->type)
            {
                // Default value
                memset(&srv, 0, sizeof(struct bsp_conf_server_t));
                srv.server_inet = INET_TYPE_ANY;
                srv.server_sock = SOCK_TYPE_ANY;
                srv.def_client_type = CLIENT_TYPE_DATA;
                srv.def_data_type = DATA_TYPE_PACKET;
                val = object_get_hash_str(vsrv, "name");
                vstr = value_get_string(val);
                srv.server_name = bsp_strndup(STR_STR(vstr), STR_LEN(vstr));
                val = object_get_hash_str(vsrv, "inet");
                vstr = value_get_string(val);
                if (vstr)
                {
                    if (0 == strncasecmp(STR_STR(vstr), "ipv6", 4))
                    {
                        srv.server_inet = INET_TYPE_IPV6;
                    }
                    else if (0 == strncasecmp(STR_STR(vstr), "ipv4", 4))
                    {
                        srv.server_inet = INET_TYPE_IPV4;
                    }
                    else if (0 == strncasecmp(STR_STR(vstr), "local", 5))
                    {
                        srv.server_inet = INET_TYPE_LOCAL;
                    }
                }
                val = object_get_hash_str(vsrv, "sock");
                vstr = value_get_string(val);
                if (vstr)
                {
                    if (0 == strncasecmp(STR_STR(vstr), "tcp", 3))
                    {
                        srv.server_sock = SOCK_TYPE_TCP;
                    }
                    else if (0 == strncasecmp(STR_STR(vstr), "udp", 3))
                    {
                        srv.server_sock = SOCK_TYPE_UDP;
                    }
                }
                val = object_get_hash_str(vsrv, "addr");
                vstr = value_get_string(val);
                srv.server_addr = bsp_strndup(STR_STR(vstr), STR_LEN(vstr));
                val = object_get_hash_str(vsrv, "port");
                srv.server_port = (int) value_get_int(val);
                val = object_get_hash_str(vsrv, "heartbeat_check");
                srv.heartbeat_check = (int) value_get_int(val);
                val = object_get_hash_str(vsrv, "debug_input");
                srv.debug_hex_input = value_get_boolean(val);
                val = object_get_hash_str(vsrv, "debug_output");
                srv.debug_hex_input = value_get_boolean(val);
                val = object_get_hash_str(vsrv, "max_clients");
                srv.max_clients = (int) value_get_int(val);
                val = object_get_hash_str(vsrv, "max_packet_length");
                srv.max_packet_length = (size_t) value_get_int(val);
                val = object_get_hash_str(vsrv, "websocket");
                if (value_get_boolean(val))
                {
                    srv.def_client_type = CLIENT_TYPE_WEBSOCKET_HANDSHAKE;
                }
                val = object_get_hash_str(vsrv, "data_type");
                vstr = value_get_string(val);
                if (vstr && 0 == strncasecmp(STR_STR(vstr), "stream", 6))
                {
                    srv.def_data_type = DATA_TYPE_STREAM;
                }

                // Add server
                BSP_SERVER *s;
                int srv_fds[MAX_SERVER_PER_CREATION], srv_ct, fd_type;
                int nfds = MAX_SERVER_PER_CREATION;
                nfds = new_server(srv.server_addr, srv.server_port, srv.server_inet, srv.server_sock, srv_fds, &nfds);
                for (srv_ct = 0; srv_ct < nfds; srv_ct ++)
                {
                    fd_type = FD_TYPE_SOCKET_SERVER;
                    s = (BSP_SERVER *) get_fd(srv_fds[srv_ct], &fd_type);
                    if (s)
                    {
                        s->name = srv.server_name;
                        s->heartbeat_check = srv.heartbeat_check;
                        s->def_client_type = srv.def_client_type;
                        s->def_data_type = srv.def_data_type;
                        s->max_packet_length = srv.max_packet_length;
                        s->max_clients = srv.max_clients;
                        s->debug_hex_input = srv.debug_hex_input;
                        s->debug_hex_output = srv.debug_hex_output;

                        add_server(s);
                    }
                    else
                    {
                        bsp_free(srv.server_name);
                    }
                }
            }
        }
    }

    // Server event
    if (server_event)
    {
        core_settings.on_srv_events = server_event;
    }

    // Create 1 Hz clock
    BSP_TIMER *tmr = new_timer(BASE_CLOCK_SEC, BASE_CLOCK_USEC, -1);
    tmr->on_timer = base_timer;
    core_settings.main_timer = tmr;
    dispatch_to_thread(tmr->fd, MAIN_THREAD);
    start_timer(tmr);

    // Let's go
    load_bootstrap();
    trace_msg(TRACE_LEVEL_CORE, "Core   : Main thread loop started");
    thread_process((void *) t);

    return BSP_RTN_SUCCESS;
}
Пример #7
0
DBMSqlDatatable* SqlServer::exec(const core::string &sql)
{
    MSSqlDatatable* dt = NULL;
    
# ifdef _FREETDS
    
    RETCODE sta = dbcmd(d_ptr->proc, sql.c_str());
    if (sta == FAIL)
        return NULL;
    
    sta = dbsqlexec(d_ptr->proc);
    if (sta == FAIL)
        return NULL;
    
    sta = dbresults(d_ptr->proc);    
    if (sta == NO_MORE_RESULTS)
        return NULL;   
    
    while (0 == dbrows(d_ptr->proc) && \
           FAIL == dbresults(d_ptr->proc));                    
    
    dt = new MSSqlDatatable(d_ptr->proc);
    dt->update();
    
    MSSqlDatatable* prev_ = dt;
    while (SUCCEED == (sta = dbresults(d_ptr->proc)))
    {
        MSSqlDatatable* next_dt = new MSSqlDatatable(d_ptr->proc);
        next_dt->update();
        
        prev_->next = next_dt;
        next_dt->prev = prev_;
        prev_ = next_dt;
    }
    
# endif

# ifdef _MSSQL

	_RecordsetPtr rcdset;
	try
	{
		rcdset.CreateInstance(__uuidof(Recordset));
		rcdset->Open(sql.c_str(), _variant_t((IDispatch*)d_ptr->conn, true), adOpenStatic, adLockOptimistic, adCmdText);
	}
	catch (_com_error& err)
	{
		_bstr_t msg = err.ErrorMessage();
		trace_msg((char const*)msg);
		return NULL;
	}
	catch (...)
	{
		trace_msg("failed to execute sql.");
		return NULL;
	}

	if (rcdset->adoEOF)
		return NULL;

	dt = new MSSqlDatatable(rcdset);
	dt->update();

# endif
    
    return dt;
}
Пример #8
0
void
HCComponent::computeReasonForUnfoundedAtom(
    Var v,
    Learning& learning )
{
    trace_msg( modelchecker, 2, "Processing variable " << solver.getLiteral( v ) );
    vector< Clause* >& definingRules = getGUSData( v ).definingRulesForNonHCFAtom;        
    for( unsigned int i = 0; i < definingRules.size(); i++ )
    {
        Clause* rule = definingRules[ i ];
        trace_msg( modelchecker, 3, "Processing rule " << *rule );
        
        bool skipRule = false;
        
        unsigned int min = UINT_MAX;
        unsigned int pos = UINT_MAX;
        for( unsigned int j = 0; j < rule->size(); j++ )
        {
            Literal lit = rule->getAt( j );
            if( isInUnfoundedSet( lit.getVariable() ) )
            {
                trace_msg( modelchecker, 4, "Literal " << lit << " is in the unfounded set" );
                if( lit.isHeadAtom() )
                {
                    trace_msg( modelchecker, 5, "Skip " << lit << " because it is in the head" );
                    continue;
                }
                else if( lit.isPositiveBodyLiteral() )
                {
                    trace_msg( modelchecker, 5, "Skip rule because of an unfounded positive body literal: " << lit );
                    skipRule = true;
                    break;
                }
            }
            
            //This should be not true anymore.
//            assert( !isInUnfoundedSet( lit.getVariable() ) );
            //If the variable is in the HCC component and it is undefined can be a reason during partial checks
            if( solver.isUndefined( lit ) && solver.getHCComponent( lit.getVariable() ) == this && ( lit.isNegativeBodyLiteral() || lit.isHeadAtom() ) )
            {
                if( pos == UINT_MAX )
                    pos = j;
                continue;
            }
            
            if( !solver.isTrue( lit ) )
            {
                trace_msg( modelchecker, 5, "Skip " << lit << " because it is not true" );
                continue;
            }
            
            unsigned int dl = solver.getDecisionLevel( lit );
            if( dl == 0 )
            {
                trace_msg( modelchecker, 5, "Skip rule because of a literal of level 0: " << lit );
                skipRule = true;
                break;
            }
            if( dl < min )
            {
                min = dl;
                pos = j;
            }
        }
        
        if( !skipRule )
        {
            assert_msg( pos < rule->size(), "Trying to access " << pos << " in " << *rule );
            trace_msg( modelchecker, 4, "The reason is: " << rule->getAt( pos ) );
            learning.onNavigatingLiteralForUnfoundedSetLearning( rule->getAt( pos ).getOppositeLiteral() );
        }
    }
}
Пример #9
0
NNTDECL_SIGNALS_END

void SocketClientAsync::connect_to(core::NetAddress const& addr, core::Timeout const& tm)
{    
    // connect.
    
# ifdef USE_REACTOR_MODE

    ACE_Synch_Options opt = ACE_Synch_Options::synch;
    if (tm.infinate())
    {
        opt.set(ACE_Synch_Options::USE_REACTOR, ACE_Time_Value::zero, 0);
    }
    else
    {
        opt.timeout(ace::type_cast<ACE_Time_Value>(tm));
    }
    
    d_ptr->handler = new _aceasync_handler;

# endif
    
# ifdef USE_PROACTOR_MODE

    d_ptr->handler = new _ace_handler_async;
    d_ptr->handler->_owner = this;

# endif

    // connect.
    
# ifdef USE_REACTOR_MODE

    int ret = d_ptr->connector.connect(d_ptr->handler,
                                       ace::type_cast<ACE_INET_Addr>(addr),
                                       opt
                                       );

# endif

# ifdef USE_PROACTOR_MODE

    int ret = d_ptr->connector.open(d_ptr->handler);
    if (ret == 0)
    {
        ret = d_ptr->connector.connect(ace::type_cast<ACE_INET_Addr>(addr));
    }

# endif

    if (ret == 0)
    {

# ifdef USE_REACTOR_MODE
        emit(kSignalSuccess);
# endif

    }
    else
    {
        emit(kSignalFailed);
		trace_msg("socketclient: failed to connect server.");
    }
}
Пример #10
0
bool SqlServer::connect(connection_info const& info)
{    
# ifdef _FREETDS
    RETCODE sta;
    LOGINREC* login = dblogin();
    
    sta = DBSETLUSER(login, info.user.c_str());
    if (sta == FAIL)
        return false;
    
    sta = DBSETLPWD(login, info.passwd.c_str());
    if (sta == FAIL)
        return false;
    
    DBPROCESS* proc = dbopen(login, info.url.c_str());
    if (proc == NULL)
        return false;
    
    sta = dbuse(proc, info.database.c_str());
    if (sta == FAIL)
        return false;
    
    d_ptr->proc = proc;
    
# endif

# ifdef _MSSQL

	_ConnectionPtr conn;
	HRESULT sta = conn.CreateInstance(__uuidof(Connection));
	if (FAILED(sta)) 
	{
		MessageBox(NULL, _W("failed to instance a new connection."), NULL, MB_OK);
		return false;
	}

	core::stringstream ss;
	ss << "Driver={SQL Server};" <<
		"Server=" << info.url << ";" << 
		"Database=" << info.database << ";" <<
		"UID=" << info.user << ";" <<
		"PWD=" << info.passwd << ";";
	core::string str_conn = ss.str();

	try
	{
		sta = conn->Open(str_conn.c_str(), "", "", adModeUnknown);
	}
	catch (_com_error& NNTDEBUG_EXPRESS(er))
	{
		trace_msg((char const*)er.ErrorMessage());
		return false;
	}
	catch (...)
	{
		trace_msg("failed to open database.");
		return false;
	}

	this->close();
	d_ptr->conn = conn;
 
# endif
    
    return true;
}
Пример #11
0
 virtual int handle_timeout (const ACE_Time_Value &current_time,
                             const void *act)
 {
     trace_msg("handle timeout.");
     return super::handle_timeout(current_time, act);
 }
Пример #12
0
 virtual int handle_exception (ACE_HANDLE fd)
 {
     trace_msg("handle exception.");
     return super::handle_exception(fd);
 }
Пример #13
0
 virtual int handle_output (ACE_HANDLE fd)
 {
     trace_msg("handle output.");
     return super::handle_output(fd);
 }
Пример #14
0
void MainController::act_disconnected(eventobj_t&)
{
    trace_msg("LOST CONNECTED.");
}
Пример #15
0
void MSSqlDatatable::update()
{
    // clear.
    this->clear();
    
# ifdef _FREETDS
    
    DBPROCESS* proc = (DBPROCESS*)_proc;
    
    // update.
    uint const ncols = dbnumcols(proc); 
    
    struct COL 						
    { 
        char *name; 
        char *buffer; 
        int type, size, status; 
    } *columns, *pcol;
    
    if ((columns = (COL*)calloc(ncols, sizeof(struct COL))) == NULL) {
        return;
    }
    
    RETCODE sta = 0;
    
    rows_type& rows = this->_rows;
    cols_type& cols = this->_cols;
    cols.resize(ncols);        
    
    //Read metadata and bind.  
    for (pcol = columns; pcol - columns < ncols; pcol++) {
        int c = (int)(pcol - columns + 1);
        
        pcol->name = dbcolname(proc, c);		
        pcol->type = dbcoltype(proc, c);
        pcol->size = dbcollen(proc, c);
        
        // add cols.
        cols[c - 1] = new variant_t(pcol->name, core::copy);
        
        if (SYBCHAR != pcol->type) {			
            pcol->size = dbwillconvert(pcol->type, SYBCHAR);
        }        
        
        if ((pcol->buffer = (char*)calloc(1, pcol->size + 1)) == NULL){
            break;
        }
        
        sta = dbbind(proc,
                     c,
                     NTBSTRINGBIND,	
                     pcol->size + 1,
                     (byte*)pcol->buffer);
        if (sta == FAIL) {
            break;
        }
        sta = dbnullbind(proc, 
                         c,
                         &pcol->status);	
        if (sta == FAIL) {
            break;
        }
    }
    
    // Get rows.
    while ((sta = dbnextrow(proc)) != NO_MORE_ROWS){	
        switch (sta) {
			case REG_ROW:
            {
                DBMSqlDatatable::row_type *row = new DBMSqlDatatable::row_type;
                row->resize(ncols);
                
				for (pcol=columns; pcol - columns < ncols; ++pcol) 
                {
                    int c = (int)(pcol - columns + 1);
					char const* buffer = pcol->status == -1 ? "" : pcol->buffer;
                    (*row)[c - 1] = new variant_t(buffer, core::copy);
				}
                
                rows.push_back(row);
            } break;
        }                
    }
    
    /* free metadata and data buffers */
    for (pcol=columns; pcol - columns < ncols; pcol++) {
        free(pcol->buffer);
    }
    free(columns);
    
# endif

# ifdef _MSSQL
	_RecordsetPtr& rcdset = *((_RecordsetPtr*)_proc);

	usize const ncols = (usize const)rcdset->Fields->GetCount();

	rows_type& rows = this->_rows;
	cols_type& cols = this->_cols;
	cols.resize(ncols);	

	// read cols.
	for (uint idx = 0; idx < ncols; ++idx)
	{
# ifdef NNT_DEBUG
		try {
# endif

		_bstr_t name = rcdset->Fields->GetItem((long)idx)->GetName();
		cols[idx] = new variant_t((char const*)name, core::copy);

# ifdef NNT_DEBUG
		} catch (_com_error& err) 	{
			_bstr_t msg = err.ErrorMessage();
			trace_msg((char const*)msg);
		}
# endif
	}

	// read rows.
	while (!rcdset->adoEOF)
	{
		row_type* row = new row_type;
		row->resize(ncols);

		for (uindex idx = 0; idx < ncols; ++idx)
		{
# ifdef NNT_DEBUG
			try {
# endif

			_bstr_t val = rcdset->GetCollect((long)idx);
			(*row)[idx] = new variant_t((char const*)val, core::copy);

# ifdef NNT_DEBUG
			} catch (_com_error& err) 	{
				_bstr_t msg = err.ErrorMessage();
				trace_msg((char const*)msg);
			}
# endif
		}

		rows.push_back(row);

		rcdset->MoveNext();
	}

# endif

}
Пример #16
0
Файл: main.cpp Проект: imace/nnt
static void test_database()
{
    // connect sqlite.
    if (0)
    {
        store::Sqlite sqlite;
        store::connection_info info;
        info.url = "sqlite.db";
        sqlite.connect(info);
        
        store::datatable_t* dt = NULL;
        
        if (1)
        {
            dt = sqlite.exec("select * from TEST");
            trace_msg(dt->to_string());
            dt->drop();
        }
        
        if (1)
        {
            dt = sqlite.exec("select * from TEST where ID = :id",
                             core::push_back<store::Sqlite::params_type>(
                                                                         core::make_pair(":id", variant_t(1))
                                                                         ));
            trace_msg(dt->to_string());
            dt->drop();
        }
    }
    
    if (1)
    {        
        store::Sqlite sqlite;
        sqlite.creatable = true;
        sqlite.readonly = false;
        store::connection_info info;
        info.url = "sqlite-new.db";
        sqlite.connect(info);
        sqlite.set_key("abcdef");
        store::datatable_t* dt = NULL;
        dt = sqlite.exec("create table test (id integer, name text)");
        if (dt) dt->drop();
        sqlite.exec("insert into test (id, name) values (1, 'test')")->drop();
        dt = sqlite.exec("select * from test");
        trace_msg(dt->to_string());
        dt->drop();
    }
    
    // connect mysql.
    if (0)
    {
        store::MySql mysql;
        store::connection_info info;
        info.url = "localhost";
        info.user = "******";
        info.passwd = "root";
        info.database = "test";
        mysql.connect(info);
        
        store::datatable_t* dt = NULL;
        
        if (1)
        {
            dt = mysql.exec("select * from test");
            trace_msg(dt->to_string());
            dt->drop();
        }
        
        if (1)
        {
            dt = mysql.exec("select * from test where test = ?", 
                            core::push_back<store::MySql::params_type>(
                                                                       core::make_pair("", variant_t(1))
                                                                       ));
            //dt = mysql.exec("select * from test where test = 1", store::MySql::params_type());
            trace_msg(dt->to_string());
            dt->drop();
        }
    }
    
    // connect sqlserver.
    if (0)
    {
        store::SqlServer sqlsrv;
        store::connection_info info;
        info.url = "wybo-win";
        info.user = "******";
        info.passwd = "test";
        info.database = "TEST";
        sqlsrv.connect(info);
        
        store::datatable_t* dt = NULL;
        
        if (1)
        {
            dt = sqlsrv.exec("select * from TEST");
            trace_msg(dt->to_string());
            dt->drop();
        }
        
        if (1)
        {
            dt = sqlsrv.exec("select * from TEST where ID = @id; select * from TEST where NAME = @name;", 
                             core::push_back<store::MySql::params_type>(
                                                                        core::make_pair("id", variant_t(1)),
                                                                        core::make_pair("name", variant_t("DDDDD", core::assign))
                                                                        ));
            store::datatable_t* next = dt;
            while (next)
            {
                trace_msg(next->to_string());
                next = next->next;
            }
            dt->drop();
        }
    }
    
    // connect postgresql.
    if (0)
    {
        store::PostgreSql pgsql;
        store::connection_info info;
        info.url = "localhost:5432";
        info.user = "******";
        info.passwd = "root";
        info.database = "postgres";
        pgsql.connect(info);
        
        store::datatable_t* dt = NULL;
        
        if (0)
        {
            dt = pgsql.exec("select * from \"TEST\"");
            trace_msg(dt->to_string());
            dt->drop();
        }
        
        if (1)
        {
            dt = pgsql.exec("select * from \"TEST\" where \"TEST\".\"ID\" = $1::int4",
                            core::push_back<store::PostgreSql::params_type>(
                                                                            core::make_pair("", variant_t(1))
                                                                            ));
            trace_msg(dt->to_string());
            dt->drop();
        }
    }
    
    // connect bdb.
    if (0)
    {
        store::test::Bdb ca;
        ut::Suite su;
        su.add(&ca);
        su.run();
    }
}
Пример #17
0
Файл: core.c Проект: shenzhe/bsp
// Parse runtime setting
int _parse_runtime_setting(BSP_STRING *rs)
{
    if (!rs)
    {
        return BSP_RTN_FATAL;
    }

    if (!core_settings.initialized)
    {
        init_core_setting();
    }

    runtime_settings = json_nd_decode(rs);
    if (!runtime_settings || OBJECT_TYPE_HASH != runtime_settings->type)
    {
        trace_msg(TRACE_LEVEL_ERROR, "Core   : Runtime setting parse error");
        return BSP_RTN_ERROR_GENERAL;
    }

    trace_msg(TRACE_LEVEL_NOTICE, "Core   : Runtime setting parsed");
    BSP_OBJECT *vobj;
    BSP_STRING *vstr;
    BSP_VALUE *val;
    // Global settings
    val = object_get_hash_str(runtime_settings, "global");
    vobj = value_get_object(val);
    if (vobj && OBJECT_TYPE_HASH == vobj->type)
    {
        val = object_get_hash_str(vobj, "instance_id");
        if (val && BSP_VAL_INT == val->type)
        {
            core_settings.instance_id = (int) value_get_int(val);
        }
        val = object_get_hash_str(vobj, "static_workers");
        if (val && BSP_VAL_INT == val->type)
        {
            core_settings.static_workers = value_get_int(val);
            if (core_settings.static_workers <= 0)
            {
                core_settings.static_workers = DEFAULT_STATIC_WORKERS;
            }
        }
        val = object_get_hash_str(vobj, "debug_output");
        core_settings.debug_hex_output = value_get_boolean(val);
        val = object_get_hash_str(vobj, "debug_connector_input");
        core_settings.debug_hex_connector_input = value_get_boolean(val);
        val = object_get_hash_str(vobj, "log_dir");
        vstr = value_get_string(val);
        core_settings.log_dir = (vstr) ? bsp_strndup(STR_STR(vstr), STR_LEN(vstr)) : NULL;
        val = object_get_hash_str(vobj, "enable_log");
        if (value_get_boolean(val) && core_settings.is_daemonize)
        {
            log_open();
            core_settings.trace_recorder = log_add;
        }
        val = object_get_hash_str(vobj, "script_dir");
        vstr = value_get_string(val);
        core_settings.script_dir = (vstr) ? bsp_strndup(STR_STR(vstr), STR_LEN(vstr)) : NULL;
        val = object_get_hash_str(vobj, "script_gc_interval");
        if (val && BSP_VAL_INT == val->type)
        {
            core_settings.script_gc_interval = value_get_int(val);
        }
    }

    return BSP_RTN_SUCCESS;
}
Пример #18
0
/*
 * The main function of `master' is to periodically compute the differences
 * (deltas) between its clock and the clocks of the slaves, to compute the
 * network average delta, and to send to the slaves the differences between
 * their individual deltas and the network delta.
 * While waiting, it receives messages from the slaves (i.e. requests for
 * master's name, remote requests to set the network time, ...), and
 * takes the appropriate action.
 */
int
master()
{
	struct hosttbl *htp;
	long pollingtime;
#define POLLRATE 4
	int polls;
	struct timeval wait, ntime;
	time_t tsp_time_sec;
	struct tsp *msg, *answer, to;
	char newdate[32];
	struct sockaddr_in taddr;
	char tname[MAXHOSTNAMELEN];
	struct netinfo *ntp;
	int i;

	syslog(LOG_NOTICE, "This machine is master");
	if (trace)
		fprintf(fd, "This machine is master\n");
	for (ntp = nettab; ntp != NULL; ntp = ntp->next) {
		if (ntp->status == MASTER)
			masterup(ntp);
	}
	(void)gettimeofday(&ntime, 0);
	pollingtime = ntime.tv_sec+3;
	if (justquit)
		polls = 0;
	else
		polls = POLLRATE-1;

/* Process all outstanding messages before spending the long time necessary
 *	to update all timers.
 */
loop:
	(void)gettimeofday(&ntime, 0);
	wait.tv_sec = pollingtime - ntime.tv_sec;
	if (wait.tv_sec < 0)
		wait.tv_sec = 0;
	wait.tv_usec = 0;
	msg = readmsg(TSP_ANY, ANYADDR, &wait, 0);
	if (!msg) {
		(void)gettimeofday(&ntime, 0);
		if (ntime.tv_sec >= pollingtime) {
			pollingtime = ntime.tv_sec + SAMPLEINTVL;
			get_goodgroup(0);

/* If a bogus master told us to quit, we can have decided to ignore a
 * network.  Therefore, periodically try to take over everything.
 */
			polls = (polls + 1) % POLLRATE;
			if (0 == polls && nignorednets > 0) {
				trace_msg("Looking for nets to re-master\n");
				for (ntp = nettab; ntp; ntp = ntp->next) {
					if (ntp->status == IGNORE
					    || ntp->status == NOMASTER) {
						lookformaster(ntp);
						if (ntp->status == MASTER) {
							masterup(ntp);
							polls = POLLRATE-1;
						}
					}
					if (ntp->status == MASTER
					    && --ntp->quit_count < 0)
						ntp->quit_count = 0;
				}
				if (polls != 0)
					setstatus();
			}

			synch(0L);

			for (ntp = nettab; ntp != NULL; ntp = ntp->next) {
				to.tsp_type = TSP_LOOP;
				to.tsp_vers = TSPVERSION;
				to.tsp_seq = sequence++;
				to.tsp_hopcnt = MAX_HOPCNT;
				(void)strcpy(to.tsp_name, hostname);
				bytenetorder(&to);
				if (sendto(sock, (char *)&to,
					   sizeof(struct tsp), 0,
					   (struct sockaddr*)&ntp->dest_addr,
					   sizeof(ntp->dest_addr)) < 0) {
				   trace_sendto_err(ntp->dest_addr.sin_addr);
				}
			}
		}


	} else {
		switch (msg->tsp_type) {

		case TSP_MASTERREQ:
			break;

		case TSP_SLAVEUP:
			newslave(msg);
			break;

		case TSP_SETDATE:
			/*
			 * XXX check to see it is from ourself
			 */
			tsp_time_sec = msg->tsp_time.tv_sec;
			(void)strcpy(newdate, ctime(&tsp_time_sec));
			if (!good_host_name(msg->tsp_name)) {
				syslog(LOG_NOTICE,
				       "attempted date change by %s to %s",
				       msg->tsp_name, newdate);
				spreadtime();
				break;
			}

			mchgdate(msg);
			(void)gettimeofday(&ntime, 0);
			pollingtime = ntime.tv_sec + SAMPLEINTVL;
			break;

		case TSP_SETDATEREQ:
			if (!fromnet || fromnet->status != MASTER)
				break;
			tsp_time_sec = msg->tsp_time.tv_sec;
			(void)strcpy(newdate, ctime(&tsp_time_sec));
			htp = findhost(msg->tsp_name);
			if (htp == 0) {
				syslog(LOG_ERR,
				       "attempted SET DATEREQ by uncontrolled %s to %s",
				       msg->tsp_name, newdate);
				break;
			}
			if (htp->seq == msg->tsp_seq)
				break;
			htp->seq = msg->tsp_seq;
			if (!htp->good) {
				syslog(LOG_NOTICE,
				"attempted SET DATEREQ by untrusted %s to %s",
				       msg->tsp_name, newdate);
				spreadtime();
				break;
			}

			mchgdate(msg);
			(void)gettimeofday(&ntime, 0);
			pollingtime = ntime.tv_sec + SAMPLEINTVL;
			break;

		case TSP_MSITE:
			xmit(TSP_ACK, msg->tsp_seq, &from);
			break;

		case TSP_MSITEREQ:
			break;

		case TSP_TRACEON:
			traceon();
			break;

		case TSP_TRACEOFF:
			traceoff("Tracing ended at %s\n");
			break;

		case TSP_ELECTION:
			if (!fromnet)
				break;
			if (fromnet->status == MASTER) {
				pollingtime = 0;
				(void)addmach(msg->tsp_name, &from,fromnet);
			}
			taddr = from;
			(void)strcpy(tname, msg->tsp_name);
			to.tsp_type = TSP_QUIT;
			(void)strcpy(to.tsp_name, hostname);
			answer = acksend(&to, &taddr, tname,
					 TSP_ACK, 0, 1);
			if (answer == NULL) {
				syslog(LOG_ERR, "election error by %s",
				       tname);
			}
			break;

		case TSP_CONFLICT:
			/*
			 * After a network partition, there can be
			 * more than one master: the first slave to
			 * come up will notify here the situation.
			 */
			if (!fromnet || fromnet->status != MASTER)
				break;
			(void)strcpy(to.tsp_name, hostname);

			/* The other master often gets into the same state,
			 * with boring results if we stay at it forever.
			 */
			ntp = fromnet;	/* (acksend() can leave fromnet=0 */
			for (i = 0; i < 3; i++) {
				to.tsp_type = TSP_RESOLVE;
				(void)strcpy(to.tsp_name, hostname);
				answer = acksend(&to, &ntp->dest_addr,
						 ANYADDR, TSP_MASTERACK,
						 ntp, 0);
				if (!answer)
					break;
				htp = addmach(answer->tsp_name,&from,ntp);
				to.tsp_type = TSP_QUIT;
				msg = acksend(&to, &htp->addr, htp->name,
					      TSP_ACK, 0, htp->noanswer);
				if (msg == NULL) {
					syslog(LOG_ERR,
				    "no response from %s to CONFLICT-QUIT",
					       htp->name);
				}
			}
			masterup(ntp);
			pollingtime = 0;
			break;

		case TSP_RESOLVE:
			if (!fromnet || fromnet->status != MASTER)
				break;
			/*
			 * do not want to call synch() while waiting
			 * to be killed!
			 */
			(void)gettimeofday(&ntime, (struct timezone *)0);
			pollingtime = ntime.tv_sec + SAMPLEINTVL;
			break;

		case TSP_QUIT:
			doquit(msg);		/* become a slave */
			break;

		case TSP_LOOP:
			if (!fromnet || fromnet->status != MASTER
			    || !strcmp(msg->tsp_name, hostname))
				break;
			/*
			 * We should not have received this from a net
			 * we are master on.  There must be two masters.
			 */
			htp = addmach(msg->tsp_name, &from,fromnet);
			to.tsp_type = TSP_QUIT;
			(void)strcpy(to.tsp_name, hostname);
			answer = acksend(&to, &htp->addr, htp->name,
					 TSP_ACK, 0, 1);
			if (!answer) {
				syslog(LOG_WARNING,
				"loop breakage: no reply from %s=%s to QUIT",
				    htp->name, inet_ntoa(htp->addr.sin_addr));
				(void)remmach(htp);
			}

		case TSP_TEST:
			if (trace) {
				fprintf(fd,
		"\tnets = %d, masters = %d, slaves = %d, ignored = %d\n",
		nnets, nmasternets, nslavenets, nignorednets);
				setstatus();
			}
			pollingtime = 0;
			polls = POLLRATE-1;
			break;

		default:
			if (trace) {
				fprintf(fd, "garbage message: ");
				print(msg, &from);
			}
			break;
		}
	}
	goto loop;
}
Пример #19
0
bool
Aggregate::onLiteralFalse(
    Solver& solver,
    Literal currentLiteral,
    PropagatorData p )
{
    int position = p.position();
    assert_msg( abs( position ) > 0 && abs( position ) < static_cast< int >( literals.size() ), abs( position ) << " >= " << literals.size() );
    assert_msg( currentLiteral == ( position < 0 ? literals[ -position ].getOppositeLiteral() : literals[ position ] ), currentLiteral << " != " << ( position < 0 ? literals[ -position ].getOppositeLiteral() : literals[ position ] ) );
    trace_msg( aggregates, 10, "Aggregate: " << *this << ". Literal: " << currentLiteral.getOppositeLiteral() << " is true. Position: " << position );
    int ac = ( position < 0 ? POS : NEG );
    Literal aggrLiteral = ( ac == POS ? literals[ 1 ].getOppositeLiteral() : literals[ 1 ] );
    
    if( solver.isTrue( aggrLiteral ) || active + ac == 0 )
    {        
        trace_msg( aggregates, 2, "Return. AggrLiteral: " << aggrLiteral << " - Active: " << active << " - Ac: " << ac );
        return false;
    }
    
    unsigned int index = ( position > 0 ? position : -position ); 
    int64_t& counter = ( position > 0 ? counterW2 : counterW1 );

    trace_msg( aggregates, 2, "Updating counter. Old value: " << counter << " - New value: " << counter - weights[ index ] );
    
    if( counter < ( int64_t ) weights[ index ] )
    {
        assert_msg( solver.getDecisionLevel( currentLiteral ) == 0, "Literal " << currentLiteral << " in " << *this << " has a decision level " << solver.getDecisionLevel( currentLiteral ) );
        trace_msg( aggregates, 3, "A conflict happened." );        
        solver.assignLiteral( currentLiteral, this );
        return false;
    }
    assert( counter >= ( int64_t ) weights[ index ] );
    counter -= weights[ index ];
    watched[ index ] = false;
    
    if( solver.getDecisionLevel( currentLiteral ) != 0 )
        trail.push_back( position );

    trace_msg( aggregates, 2, "Umax: " << umax << " - size: " << size() );
    while( umax < literals.size() && ( int64_t ) weights[ umax ] > counter )
    {
        if( watched[ umax ] )
        {
            if( literalOfUnroll == Literal::null )
                literalOfUnroll = currentLiteral;
            active = ac;
            Literal lit = ( ac == POS ? literals[ umax ].getOppositeLiteral() : literals[ umax ] );
            if( !solver.isTrue( lit ) )
            {                
                //Maybe we don't need to add the position of this literal
                trail.push_back( umax * ac );
            
                trace_msg( aggregates, 9, "Inferring " << lit << " as true" );
//                createClauseFromTrail( lit );
                solver.assignLiteral( lit, this );
                if( solver.conflictDetected() )
                    return true;
            }
            else
            {
                trace_msg( aggregates, 9, "Skipping true literal " << lit );
            }
        }
        
        ++umax;
        trace_msg( aggregates, 3, "Updated umax. New Value: " << umax );        
    }
    
    return true;
}