コード例 #1
0
ファイル: rdnval.c プロジェクト: cptaffe/openldap
static int
rdnval_repair( BackendDB *be )
{
	slap_overinst *on = (slap_overinst *)be->bd_info;
	void *ctx = ldap_pvt_thread_pool_context();
	Connection conn = { 0 };
	OperationBuffer opbuf;
	Operation *op;
	BackendDB db;
	slap_callback sc = { 0 };
	rdnval_repair_cb_t rcb = { 0 };
	SlapReply rs = { REP_RESULT };
	rdnval_mod_t *rmod;
	int nrepaired = 0;

	connection_fake_init2( &conn, &opbuf, ctx, 0 );
	op = &opbuf.ob_op;

	op->o_tag = LDAP_REQ_SEARCH;
	memset( &op->oq_search, 0, sizeof( op->oq_search ) );

	assert( !BER_BVISNULL( &be->be_nsuffix[ 0 ] ) );

	op->o_bd = select_backend( &be->be_nsuffix[ 0 ], 0 );
	assert( op->o_bd != NULL );
	assert( op->o_bd->be_nsuffix != NULL );

	op->o_req_dn = op->o_bd->be_suffix[ 0 ];
	op->o_req_ndn = op->o_bd->be_nsuffix[ 0 ];

	op->o_dn = op->o_bd->be_rootdn;
	op->o_ndn = op->o_bd->be_rootndn;

	op->ors_scope = LDAP_SCOPE_SUBTREE;
	op->ors_tlimit = SLAP_NO_LIMIT;
	op->ors_slimit = SLAP_NO_LIMIT;
	op->ors_attrs = slap_anlist_no_attrs;

	op->ors_filterstr.bv_len = STRLENOF( "(!(=*))" ) + ad_rdnValue->ad_cname.bv_len;
	op->ors_filterstr.bv_val = op->o_tmpalloc( op->ors_filterstr.bv_len + 1, op->o_tmpmemctx );
	snprintf( op->ors_filterstr.bv_val, op->ors_filterstr.bv_len + 1,
		"(!(%s=*))", ad_rdnValue->ad_cname.bv_val );

	op->ors_filter = str2filter_x( op, op->ors_filterstr.bv_val );
	if ( op->ors_filter == NULL ) {
		rs.sr_err = LDAP_OTHER;
		goto done_search;
	}
	
	op->o_callback = ≻
	sc.sc_response = rdnval_repair_cb;
	sc.sc_private = &rcb;
	rcb.bd = &db;
	db = *be;
	db.bd_info = (BackendInfo *)on;

	(void)op->o_bd->bd_info->bi_op_search( op, &rs );

	op->o_tag = LDAP_REQ_MODIFY;
	sc.sc_response = slap_null_cb;
	sc.sc_private = NULL;
	memset( &op->oq_modify, 0, sizeof( req_modify_s ) );

	for ( rmod = rcb.mods; rmod != NULL; ) {
		rdnval_mod_t *rnext;

		Modifications *mod;
		SlapReply rs2 = { REP_RESULT };

		mod = (Modifications *) ch_malloc( sizeof( Modifications ) );
		mod->sml_flags = SLAP_MOD_INTERNAL;
		mod->sml_op = LDAP_MOD_REPLACE;
		mod->sml_desc = ad_rdnValue;
		mod->sml_type = ad_rdnValue->ad_cname;
		mod->sml_values = rmod->vals;
		mod->sml_nvalues = rmod->nvals;
		mod->sml_numvals = rmod->numvals;
		mod->sml_next = NULL;

		op->o_req_dn = rmod->ndn;
		op->o_req_ndn = rmod->ndn;

		op->orm_modlist = mod;

		op->o_bd->be_modify( op, &rs2 );

		slap_mods_free( op->orm_modlist, 1 );
		if ( rs2.sr_err == LDAP_SUCCESS ) {
			Debug( LDAP_DEBUG_TRACE, "%s: rdnval_repair: entry DN=\"%s\" repaired\n",
				op->o_log_prefix, rmod->ndn.bv_val, 0 );
			nrepaired++;

		} else {
			Debug( LDAP_DEBUG_ANY, "%s: rdnval_repair: entry DN=\"%s\" repair failed (%d)\n",
				op->o_log_prefix, rmod->ndn.bv_val, rs2.sr_err );
		}

		rnext = rmod->next;
		op->o_tmpfree( rmod, op->o_tmpmemctx );
		rmod = rnext;
	}

done_search:;
	op->o_tmpfree( op->ors_filterstr.bv_val, op->o_tmpmemctx );
	filter_free_x( op, op->ors_filter, 1 );

	Log1( LDAP_DEBUG_STATS, LDAP_LEVEL_INFO,
		"rdnval: repaired=%d\n", nrepaired );

	return 0;
}
コード例 #2
0
ファイル: CharacterClient.cpp プロジェクト: olekw/cyphesis
/// \brief Send an operation to the server from this avatar
///
/// @param op Operation to be sent
void CharacterClient::send(const Operation & op)
{
    op->setFrom(getId());
    m_connection.send(op);
}
コード例 #3
0
ファイル: CharacterClient.cpp プロジェクト: olekw/cyphesis
/// \brief Send an operation to the server, and wait for a reply
///
/// Reply is identified as it should have its refno attribute set to
/// the serialno of the operation sent.
/// @param op Operation to be sent
/// @param res Result with correct refno is returned here
int CharacterClient::sendAndWaitReply(const Operation & op, OpVector & res)
{
    op->setFrom(getId());
    return m_connection.sendAndWaitReply(op, res);
}
コード例 #4
0
ファイル: Entity.cpp プロジェクト: cyclefusion/cyphesis
/// \brief Find and call the handler for an operation
///
/// @param op The operation to be processed.
/// @param res The result of the operation is returned here.
void Entity::callOperation(const Operation & op, OpVector & res)
{
    auto op_no = op->getClassNo();
    OP_SWITCH(op, op_no, res,)
}
コード例 #5
0
ファイル: Sum.cpp プロジェクト: spencerparkin/Junk
bool Sum::CombineLikeOperands( void )
{
	for( OperandList::Node* nodeA = operandList->Head(); nodeA; nodeA = nodeA->Next() )
	{
		Operand* operandA = nodeA->data;

		for( OperandList::Node* nodeB = nodeA->Next(); nodeB; nodeB = nodeB->Next() )
		{
			Operand* operandB = nodeB->data;

			if( operandA->IsScalar() && operandB->IsScalar() )
			{
				Operand* scalar = AddScalars( operandA, operandB );
				if( scalar )
				{
					operandList->InsertAfter()->data = scalar;
					operandList->Remove( nodeA );
					operandList->Remove( nodeB );
					return true;
				}
			}
			else if( dynamic_cast< Vector* >( operandA ) && dynamic_cast< Vector* >( operandB ) )
			{
				Vector* vectorA = ( Vector* )operandA;
				Vector* vectorB = ( Vector* )operandB;

				if( 0 == strcmp( vectorA->GetName(), vectorB->GetName() ) )
				{
					Operand* scalarA = vectorA->GetScalar();
					Operand* scalarB = vectorB->GetScalar();

					vectorA->SetScalar( 0, false );
					vectorB->SetScalar( 0, false );

					if( !scalarA )
					{
						NumericScalar* numericScalar = new NumericScalar();
						numericScalar->SetReal( 1.0 );
						scalarA = numericScalar;
					}

					if( !scalarB )
					{
						NumericScalar* numericScalar = new NumericScalar();
						numericScalar->SetReal( 1.0 );
						scalarB = numericScalar;
					}

					Sum* scalar = new Sum();
					scalar->operandList->InsertAfter()->data = scalarA;
					scalar->operandList->InsertAfter()->data = scalarB;

					vectorB->SetScalar( scalar );
					operandList->Remove( nodeA );

					return true;
				}
			}
			else if( ( operandA->IsBlade() && operandB->IsBlade() ) ||
					( operandA->IsVersor() && operandB->IsVersor() ) )
			{
				Operation* operationA = ( Operation* )operandA;
				Operation* operationB = ( Operation* )operandB;

				if( OperationsAlike( operationA, operationB ) )
				{
					// Degenerates are removed well before we can get here, so this shouldn't happen.
					Vector* vector = operationB->FindLeadingVector();
					if( !vector )
					{
						Error* error = new Error();
						error->Format( "Sum expected to find a leading vector, but didn't." );
						throw error;
					}

					// An empty geometric product in either case will do fine.
					GeometricProduct* scalarA = operationA->StripScalars();
					GeometricProduct* scalarB = operationB->StripScalars();

					Sum* scalar = new Sum();
					scalar->operandList->InsertAfter()->data = scalarA;
					scalar->operandList->InsertAfter()->data = scalarB;

					vector->MarryWithScalar( scalar );
					operandList->Remove( nodeA );

					return true;
				}
			}
		}
	}

	return false;
}
コード例 #6
0
ファイル: dds.c プロジェクト: bhanug/likewise-open
/* count dynamic objects existing in the database at startup */
static int
dds_count( void *ctx, BackendDB *be )
{
	slap_overinst	*on = (slap_overinst *)be->bd_info;
	dds_info_t	*di = (dds_info_t *)on->on_bi.bi_private;

	Connection	conn = { 0 };
	OperationBuffer opbuf;
	Operation	*op;
	slap_callback	sc = { 0 };
	SlapReply	rs = { REP_RESULT };

	int		rc;
	char		*extra = "";

	connection_fake_init( &conn, &opbuf, ctx );
	op = &opbuf.ob_op;

	op->o_tag = LDAP_REQ_SEARCH;
	memset( &op->oq_search, 0, sizeof( op->oq_search ) );

	op->o_bd = be;

	op->o_req_dn = op->o_bd->be_suffix[ 0 ];
	op->o_req_ndn = op->o_bd->be_nsuffix[ 0 ];

	op->o_dn = op->o_bd->be_rootdn;
	op->o_ndn = op->o_bd->be_rootndn;

	op->ors_scope = LDAP_SCOPE_SUBTREE;
	op->ors_tlimit = SLAP_NO_LIMIT;
	op->ors_slimit = SLAP_NO_LIMIT;
	op->ors_attrs = slap_anlist_no_attrs;

	op->ors_filterstr.bv_len = STRLENOF( "(objectClass=" ")" )
		+ slap_schema.si_oc_dynamicObject->soc_cname.bv_len;
	op->ors_filterstr.bv_val = op->o_tmpalloc( op->ors_filterstr.bv_len + 1, op->o_tmpmemctx );
	snprintf( op->ors_filterstr.bv_val, op->ors_filterstr.bv_len + 1,
		"(objectClass=%s)",
		slap_schema.si_oc_dynamicObject->soc_cname.bv_val );

	op->ors_filter = str2filter_x( op, op->ors_filterstr.bv_val );
	if ( op->ors_filter == NULL ) {
		rs.sr_err = LDAP_OTHER;
		goto done_search;
	}

	op->o_callback = &sc;
	sc.sc_response = dds_count_cb;
	sc.sc_private = &di->di_num_dynamicObjects;
	di->di_num_dynamicObjects = 0;

	op->o_bd->bd_info = (BackendInfo *)on->on_info;
	(void)op->o_bd->bd_info->bi_op_search( op, &rs );
	op->o_bd->bd_info = (BackendInfo *)on;

done_search:;
	op->o_tmpfree( op->ors_filterstr.bv_val, op->o_tmpmemctx );
	filter_free_x( op, op->ors_filter, 1 );

	rc = rs.sr_err;
	switch ( rs.sr_err ) {
	case LDAP_SUCCESS:
		Log1( LDAP_DEBUG_STATS, LDAP_LEVEL_INFO,
			"DDS non-expired=%d\n",
			di->di_num_dynamicObjects );
		break;

	case LDAP_NO_SUCH_OBJECT:
		/* (ITS#5267) database not created yet? */
		rs.sr_err = LDAP_SUCCESS;
		extra = " (ignored)";
		/* fallthru */

	default:
		Log2( LDAP_DEBUG_ANY, LDAP_LEVEL_ERR,
			"DDS non-expired objects lookup failed err=%d%s\n",
			rc, extra );
		break;
	}

	return rs.sr_err;
}
コード例 #7
0
ファイル: Server.cpp プロジェクト: zouleipku/gStore
void Server::listen()
{
    while (true)
    {
        Socket new_server_socket;

        cout << "Wait for input..." << endl;

        this->socket.accept(new_server_socket);

        cout << "accept new socket." << endl;

        string recv_cmd;
        bool recv_return = new_server_socket.recv(recv_cmd);
        if (!recv_return)
        {
            cerr << "receive command from client error. @Server::listen" << endl;
            continue;
        }

        cout <<"received msg: " << recv_cmd << endl;

        Operation operation;
        bool parser_return = this->parser(recv_cmd, operation);
        cout << "parser_return=" << parser_return << endl; //debug
        if (!parser_return)
        {
            cout << "parser command error. @Server::listen" << endl;
            string ret_msg = "invalid command.";
            this->response(new_server_socket, ret_msg);
            new_server_socket.close();
            continue;
        }

        string ret_msg;
        CommandType cmd_type = operation.getCommand();
        switch (cmd_type)
        {
        case CMD_LOAD:
        {
            string db_name = operation.getParameter(0);
            this->loadDatabase(db_name, "", ret_msg);
            break;
        }
        case CMD_UNLOAD:
        {
            string db_name = operation.getParameter(0);
            this->unloadDatabase(db_name, "", ret_msg);
            break;
        }
        case CMD_IMPORT:
        {
            string db_name = operation.getParameter(0);
            string rdf_path = operation.getParameter(1);
            this->importRDF(db_name, "", rdf_path, ret_msg);
            break;
        }
        case CMD_QUERY:
        {
            string query = operation.getParameter(0);
            this->query(query, ret_msg);
            break;
        }
        case CMD_SHOW:
        {
            string para = operation.getParameter(0);
            if (para == "databases")
            {
                this->showDatabases("", ret_msg);
            }
            else
            {
                ret_msg = "invalid command.";
            }
            break;
        }
        case CMD_INSERT:
        {
            string db_name = operation.getParameter(0);
            string rdf_path = operation.getParameter(1);
            this->insertTriple(db_name, "", rdf_path, ret_msg);
            break;
        }
        default:
            cerr << "this command is not supported by now. @Server::listen" << endl;
        }

        this->response(new_server_socket, ret_msg);
        new_server_socket.close();
    }
}
コード例 #8
0
int main(int argc, char *argv[])
{
	ListContainer list_container;
	StackContainer stack_container;
	TimeComplexity time_complexity;				   //TODO: ensure that the below sharing of the same list_container does not interfere with the stack or arithmetic infix to postfix conversions.
	time_complexity.all_lists = &list_container; //gives the TimeComplexity object an address to the listContainer
	stack_container.all_lists = &list_container; //gives the stackContainer an address to the listContainer
/* 
	time_actual = 0;
	
	list_container.initialize("A", "A20.txt");
	ListNode* list = list_container.find_list("A");
	int n_hi = list_container.getN("A");
	int estimate = (n_hi*(6*n_hi))+ 9;
	cout << estimate << " ESTIMATE " << endl;
	list->list.alphabetize();
	cout << time_actual << endl;
	list->list.output();
	return 99; */
	if ( argc != 2 )
	{
		list_container.error("No file input or too many arguments, please try again");
		return -1;
	}
	ArgumentManager argMgr(argv[1]);
	string filename = argMgr.get("script");
	time_complexity.result_filename = argMgr.get("result");
	time_complexity.output("L1,L2,,,,-----,---,O(g(n)),--------,,", "");
	time_complexity.output("size,size,operation,T(n) estimate,T(n) actual,c,n0,g(n)=n^2", "append");
	
	char* fn = new char[filename.length()+1];
	strcpy(fn, filename.c_str());
	
	ifstream fin(fn);
	if(fin.fail())
	{
		list_container.error("Failure to open script file "+filename+" exiting program...");
		return -1;
	}
	
	list_container.error("||||||||||||| Start log for script file "+filename+" |||||||||||||");
	
	OperationQueue opQueue(filename);
	
	while(!opQueue.isEmpty())
	{
		Operation op = opQueue.pop();
		//cout << op << endl;
		if(op.isExpression())	//if true, operation is an expression that needs to be evaluated
		{
			stack_container.convertToPostfix(op.getExpression()); //convert infix to postfix
			stack_container.postfixCalc(op.getName()); //calculte the postfix expression and perform the operations
		}
		else if(op.getName() == "write" || op.getName() == "read")			//if false, the operation could be a simple read or write
		{
			if(op.getName() == "write")
			{	
				if(op.parameterCount() == 2)	//this means there is no 'forward' or 'reverse' specification in which we will just assume forward
				{
					list_container.writeForward(op.getParameter(0), op.getParameter(1));
				}
				else if(op.getParameter(2) == "forward")
				{
					list_container.writeForward(op.getParameter(0), op.getParameter(1));
				}
				else if(op.getParameter(2) == "reverse")
				{	
					list_container.writeReverse(op.getParameter(0), op.getParameter(1));
				}
				else
				{
					list_container.writeForward(op.getParameter(0), op.getParameter(1));
				}
				continue;
			}
			
			if(op.getName() == "read")
			{
				list_container.initialize(op.getParameter(0), op.getParameter(1));
				continue;
			}
		}
		else if(op.getName() == "union" || op.getName() == "intersection") //if not expression or read/write, it must be a union or intersection command
		{
			if(op.getName() == "union")
			{
				// call time complex func, and union here using op.getParameter(0) 1 and 2
				time_complexity.union_tracktime(op.getParameter(0), op.getParameter(1), op.getParameter(2));
				continue;
			}
			else if(op.getName() == "intersection")
			{
				// call time complex func, and intersection here using op.getParameter(0) 1 and 2
				time_complexity.intersection_tracktime(op.getParameter(0), op.getParameter(1), op.getParameter(2));
				continue;
			}
		}
		else
			list_container.error("operation is neither an expression, read/write, or union/intersection and therefore invalid");
	}

	//list_container.armageddon(); //deallocates all memory taken by the various lists and crashes the program currently, after merge was implemented in union_func_iterative
	list_container.error("||||||||||||| End log for script file "+filename+" |||||||||||||");
	return 99;
}
コード例 #9
0
ファイル: state_tests.cpp プロジェクト: AbheekG/mesos
TEST_F(LogStateTest, Diff)
{
  Future<Variable<Slaves>> future1 = state->fetch<Slaves>("slaves");
  AWAIT_READY(future1);

  Variable<Slaves> variable = future1.get();

  Slaves slaves = variable.get();
  ASSERT_EQ(0, slaves.slaves().size());

  for (size_t i = 0; i < 1024; i++) {
    Slave* slave = slaves.add_slaves();
    slave->mutable_info()->set_hostname("localhost" + stringify(i));
  }

  variable = variable.mutate(slaves);

  Future<Option<Variable<Slaves>>> future2 = state->store(variable);
  AWAIT_READY(future2);
  ASSERT_SOME(future2.get());

  variable = future2.get().get();

  Slave* slave = slaves.add_slaves();
  slave->mutable_info()->set_hostname("localhost1024");

  variable = variable.mutate(slaves);

  future2 = state->store(variable);
  AWAIT_READY(future2);
  ASSERT_SOME(future2.get());

  // It's possible that we're doing truncation asynchronously which
  // will cause the test to fail because we'll end up getting a
  // pending position from Log::Reader::ending which will cause
  // Log::Reader::read to fail. To remedy this, we pause the clock and
  // wait for all executing processe to settle.
  Clock::pause();
  Clock::settle();
  Clock::resume();

  Log::Reader reader(log);

  Future<Log::Position> beginning = reader.beginning();
  Future<Log::Position> ending = reader.ending();

  AWAIT_READY(beginning);
  AWAIT_READY(ending);

  Future<list<Log::Entry>> entries = reader.read(beginning.get(), ending.get());

  AWAIT_READY(entries);

  // Convert each Log::Entry to an Operation.
  vector<Operation> operations;

  foreach (const Log::Entry& entry, entries.get()) {
    // Parse the Operation from the Log::Entry.
    Operation operation;

    google::protobuf::io::ArrayInputStream stream(
        entry.data.data(),
        entry.data.size());

    ASSERT_TRUE(operation.ParseFromZeroCopyStream(&stream));

    operations.push_back(operation);
  }

  ASSERT_EQ(2u, operations.size());
  EXPECT_EQ(Operation::SNAPSHOT, operations[0].type());
  EXPECT_EQ(Operation::DIFF, operations[1].type());
}
コード例 #10
0
ファイル: JunctureTest.cpp プロジェクト: worldforge/cyphesis
int main()
{
    {
        Juncture * j = new Juncture(0, "1", 1);

        delete j;
    }

    {
        Juncture * j = new Juncture(0, "1", 1);

        OpVector res;
        Operation op;
        j->operation(op, res);

        delete j;
    }

    {
        Juncture * j = new Juncture(0, "1", 1);

        OpVector res;
        Atlas::Objects::Operation::Login op;
        j->operation(op, res);

        delete j;
    }

    // Login op, no args
    {
        Juncture * j = new Juncture(0, "1", 1);

        OpVector res;
        Operation op;
        j->LoginOperation(op, res);

        delete j;
    }

    // Login op, empty arg
    {
        Juncture * j = new Juncture(0, "1", 1);

        OpVector res;

        Operation op;
        Atlas::Objects::Root arg;
        op->setArgs1(arg);
        
        j->LoginOperation(op, res);

        delete j;
    }

    // Login op, username in arg
    {
        Juncture * j = new Juncture(0, "1", 1);

        OpVector res;

        Operation op;
        Atlas::Objects::Root arg;
        arg->setAttr("username", "69e362c6-03a4-11e0-9608-001ec93e7c08");
        op->setArgs1(arg);
        
        j->LoginOperation(op, res);

        delete j;
    }

    // Login op, bad username in arg
    {
        Juncture * j = new Juncture(0, "1", 1);

        OpVector res;

        Operation op;
        Atlas::Objects::Root arg;
        arg->setAttr("username", 0x69e362c6);
        op->setArgs1(arg);
        
        j->LoginOperation(op, res);

        delete j;
    }

    // Login op, username & password in arg
    {
        Juncture * j = new Juncture(0, "1", 1);

        OpVector res;

        Operation op;
        Atlas::Objects::Root arg;
        arg->setAttr("username", "69e362c6-03a4-11e0-9608-001ec93e7c08");
        arg->setAttr("password", "a12a2f3a-03a4-11e0-8379-001ec93e7c08");
        op->setArgs1(arg);
        
        j->LoginOperation(op, res);

        delete j;
    }

    // Login op, username & bad password in arg
    {
        Juncture * j = new Juncture(0, "1", 1);

        OpVector res;

        Operation op;
        Atlas::Objects::Root arg;
        arg->setAttr("username", "69e362c6-03a4-11e0-9608-001ec93e7c08");
        arg->setAttr("password", 0x12a2f3aL);
        op->setArgs1(arg);
        
        j->LoginOperation(op, res);

        delete j;
    }

    // Login op, username & password in arg, connected
    {
        ServerRouting sr(*(BaseWorld*)0, "", "", "2", 2, "3", 3);
        TestJuncture * j = new TestJuncture(0);
        boost::asio::io_service io_service;
        CommPeer * cp = new CommPeer("", io_service);
        j->test_addPeer(new Peer(*cp, sr, "", 6767, "4", 4));

        OpVector res;

        Operation op;
        Atlas::Objects::Root arg;
        arg->setAttr("username", "69e362c6-03a4-11e0-9608-001ec93e7c08");
        arg->setAttr("password", "a12a2f3a-03a4-11e0-8379-001ec93e7c08");
        op->setArgs1(arg);
        
        j->LoginOperation(op, res);

        delete j;
    }

    // Login op, username & password in arg, connected already authenticating
    {
        ServerRouting sr(*(BaseWorld*)0, "", "", "2", 2, "3", 3);

        TestJuncture * j = new TestJuncture(0);

        boost::asio::io_service io_service;
        CommPeer * cp = new CommPeer("", io_service);
        Peer * p = new Peer(*cp, sr, "", 6767, "4", 4);
        j->test_addPeer(p);

        p->setAuthState(PEER_AUTHENTICATING);

        OpVector res;

        Operation op;
        Atlas::Objects::Root arg;
        arg->setAttr("username", "69e362c6-03a4-11e0-9608-001ec93e7c08");
        arg->setAttr("password", "a12a2f3a-03a4-11e0-8379-001ec93e7c08");
        op->setArgs1(arg);
        
        j->LoginOperation(op, res);

        delete j;
    }

    // Login op, username & password in arg, connected, with serialno
    {
        ServerRouting sr(*(BaseWorld*)0, "", "", "2", 2, "3", 3);

        TestJuncture * j = new TestJuncture(0);

        boost::asio::io_service io_service;
        CommPeer * cp = new CommPeer("", io_service);
        j->test_addPeer(new Peer(*cp, sr, "", 6767, "4", 4));

        OpVector res;

        Operation op;
        Atlas::Objects::Root arg;
        arg->setAttr("username", "69e362c6-03a4-11e0-9608-001ec93e7c08");
        arg->setAttr("password", "a12a2f3a-03a4-11e0-8379-001ec93e7c08");
        op->setArgs1(arg);
        op->setSerialno(0x6dc5b5eaL);
        
        j->LoginOperation(op, res);

        delete j;
    }

    {
        Juncture * j = new Juncture(0, "1", 1);

        OpVector res;
        Operation op;
        j->OtherOperation(op, res);

        delete j;
    }

    {
        Juncture * j = new Juncture(0, "1", 1);

        OpVector res;
        Atlas::Objects::Operation::Connect op;
        j->OtherOperation(op, res);

        delete j;
    }

    // Connect op, no args
    {
        Juncture * j = new Juncture(0, "1", 1);

        OpVector res;
        Operation op;
        j->customConnectOperation(op, res);

        delete j;
    }

    // Connect op, no args, already connected
    {
        TestJuncture * j = new TestJuncture(0);

        j->test_addPeer(new Peer(*(CommPeer*)0, *(ServerRouting*)0, "", 6767, "4", 4));

        OpVector res;
        Operation op;
        j->customConnectOperation(op, res);

        delete j;
    }

    // Connect op, hostname in arg
    {
        Juncture * j = new Juncture(0, "1", 1);

        OpVector res;
        Operation op;
        Atlas::Objects::Root arg;
        arg->setAttr("hostname", "3752ca4a-03a9-11e0-bd8a-001ec93e7c08");

        op->setArgs1(arg);

        j->customConnectOperation(op, res);

        delete j;
    }

    // Connect op, bad hostname in arg
    {
        Juncture * j = new Juncture(0, "1", 1);

        OpVector res;
        Operation op;
        Atlas::Objects::Root arg;
        arg->setAttr("hostname", 0x3752ca4aL);

        op->setArgs1(arg);

        j->customConnectOperation(op, res);

        delete j;
    }

    // Connect op, hostname and port in arg, connected this end
    {
        ServerRouting sr(*(BaseWorld*)0, "", "", "2", 2, "3", 3);
        boost::asio::io_service io_service;
        CommSocket * cc = new StubSocket(io_service);
        Connection * c = new Connection(*cc, sr, "", "4", 4);

        Juncture * j = new Juncture(c, "1", 1);

        OpVector res;
        Operation op;
        Atlas::Objects::Root arg;
        arg->setAttr("hostname", "3752ca4a-03a9-11e0-bd8a-001ec93e7c08");
        arg->setAttr("port", 0x03a9);

        op->setArgs1(arg);

        j->customConnectOperation(op, res);

        delete j;
    }

    // Connect op, hostname and port in arg, connected this end, connect fails
    {
        stub_CommPeer_connect_return = -1;

        ServerRouting sr(*(BaseWorld*)0, "", "", "2", 2, "3", 3);
        boost::asio::io_service io_service;
        CommSocket * cc = new StubSocket(io_service);
        Connection * c = new Connection(*cc, sr, "", "4", 4);

        Juncture * j = new Juncture(c, "1", 1);

        OpVector res;
        Operation op;
        Atlas::Objects::Root arg;
        arg->setAttr("hostname", "3752ca4a-03a9-11e0-bd8a-001ec93e7c08");
        arg->setAttr("port", 0x03a9);

        op->setArgs1(arg);

        j->customConnectOperation(op, res);

        stub_CommPeer_connect_return = 0;

        delete j;
    }

    // Teleport unconnected
    {
        TestJuncture * j = new TestJuncture(0);

        j->teleportEntity(0);

        delete j;
    }

    // Teleport connected
    {
        TestJuncture * j = new TestJuncture(0);

        j->test_addPeer(new Peer(*(CommPeer*)0, *(ServerRouting*)0, "", 6767, "4", 4));
        j->teleportEntity(0);

        delete j;
    }

    {
        TestJuncture * j = new TestJuncture(0);

        j->test_onPeerLost();

        delete j;
    }

    // Peer replied, unconnected this end
    {
        TestJuncture * j = new TestJuncture(0);

        Operation op;
        j->test_onPeerReplied(op);

        delete j;
    }

    // Peer replied, connected this end
    {
        Connection * c = new Connection(*(CommSocket*)0,
                                        *(ServerRouting*)0, "", "4", 4);

        TestJuncture * j = new TestJuncture(c);

        Operation op;
        j->test_onPeerReplied(op);

        delete j;
    }

    return 0;
}
コード例 #11
0
ファイル: pguid.c プロジェクト: DanahBlanahaseth/cniiag_ldap
static int
pguid_repair( BackendDB *be )
{
	slap_overinst *on = (slap_overinst *)be->bd_info;
	void *ctx = ldap_pvt_thread_pool_context();
	Connection conn = { 0 };
	OperationBuffer opbuf;
	Operation *op;
	slap_callback sc = { 0 };
	pguid_repair_cb_t pcb = { 0 };
	SlapReply rs = { REP_RESULT };
	pguid_mod_t *pmod;
	int nrepaired = 0;

	connection_fake_init2( &conn, &opbuf, ctx, 0 );
	op = &opbuf.ob_op;

	op->o_tag = LDAP_REQ_SEARCH;
	memset( &op->oq_search, 0, sizeof( op->oq_search ) );

	op->o_bd = select_backend( &be->be_nsuffix[ 0 ], 0 );

	op->o_req_dn = op->o_bd->be_suffix[ 0 ];
	op->o_req_ndn = op->o_bd->be_nsuffix[ 0 ];

	op->o_dn = op->o_bd->be_rootdn;
	op->o_ndn = op->o_bd->be_rootndn;

	op->ors_scope = LDAP_SCOPE_SUBORDINATE;
	op->ors_tlimit = SLAP_NO_LIMIT;
	op->ors_slimit = SLAP_NO_LIMIT;
	op->ors_attrs = slap_anlist_no_attrs;

	op->ors_filterstr.bv_len = STRLENOF( "(!(=*))" ) + ad_parentUUID->ad_cname.bv_len;
	op->ors_filterstr.bv_val = op->o_tmpalloc( op->ors_filterstr.bv_len + 1, op->o_tmpmemctx );
	snprintf( op->ors_filterstr.bv_val, op->ors_filterstr.bv_len + 1,
		"(!(%s=*))", ad_parentUUID->ad_cname.bv_val );

	op->ors_filter = str2filter_x( op, op->ors_filterstr.bv_val );
	if ( op->ors_filter == NULL ) {
		rs.sr_err = LDAP_OTHER;
		goto done_search;
	}
	
	op->o_callback = &sc;
	sc.sc_response = pguid_repair_cb;
	sc.sc_private = &pcb;
	pcb.on = on;

	(void)op->o_bd->bd_info->bi_op_search( op, &rs );

	op->o_tag = LDAP_REQ_MODIFY;
	sc.sc_response = slap_null_cb;
	sc.sc_private = NULL;
	memset( &op->oq_modify, 0, sizeof( req_modify_s ) );

	for ( pmod = pcb.mods; pmod != NULL; ) {
		pguid_mod_t *pnext;

		Modifications *mod;
		SlapReply rs2 = { REP_RESULT };

		mod = (Modifications *) ch_malloc( sizeof( Modifications ) );
		mod->sml_flags = SLAP_MOD_INTERNAL;
		mod->sml_op = LDAP_MOD_REPLACE;
		mod->sml_desc = ad_parentUUID;
		mod->sml_type = ad_parentUUID->ad_cname;
		mod->sml_values = ch_malloc( sizeof( struct berval ) * 2 );
		mod->sml_nvalues = NULL;
		mod->sml_numvals = 1;
		mod->sml_next = NULL;

		ber_dupbv( &mod->sml_values[0], &pmod->pguid );
		BER_BVZERO( &mod->sml_values[1] );

		op->o_req_dn = pmod->ndn;
		op->o_req_ndn = pmod->ndn;

		op->orm_modlist = mod;
		op->o_bd->be_modify( op, &rs2 );
		slap_mods_free( op->orm_modlist, 1 );
		if ( rs2.sr_err == LDAP_SUCCESS ) {
			Debug( LDAP_DEBUG_TRACE, "%s: pguid_repair: entry DN=\"%s\" repaired\n",
				op->o_log_prefix, pmod->ndn.bv_val, 0 );
			nrepaired++;

		} else {
			Debug( LDAP_DEBUG_ANY, "%s: pguid_repair: entry DN=\"%s\" repair failed (%d)\n",
				op->o_log_prefix, pmod->ndn.bv_val, rs2.sr_err );
		}

		pnext = pmod->next;
		op->o_tmpfree( pmod, op->o_tmpmemctx );
		pmod = pnext;
	}

done_search:;
	op->o_tmpfree( op->ors_filterstr.bv_val, op->o_tmpmemctx );
	filter_free_x( op, op->ors_filter, 1 );

	Log1( LDAP_DEBUG_STATS, LDAP_LEVEL_INFO,
		"pguid: repaired=%d\n", nrepaired );

	return rs.sr_err;
}
コード例 #12
0
ファイル: BaseMind.cpp プロジェクト: anthonypesce/cyphesis
/// \brief Process the Sight of a Create operation.
///
/// @param op The Create operation to be processed.
/// @param res The result of the operation is returned here.
void BaseMind::sightCreateOperation(const Operation & op, OpVector & res)
{
    const std::vector<Root> & args = op->getArgs();
    if (args.empty()) {
        debug( std::cout << " no args!" << std::endl << std::flush;);
コード例 #13
0
ファイル: MCOperationQueue.cpp プロジェクト: AabanTariq/UCLA
void OperationQueue::runOperations()
{
#if defined(__ANDROID) || defined(ANDROID)
    androidSetupThread();
#endif

    MCLog("start thread");
    mailsem_up(mStartSem);
    
    while (true) {
        Operation * op = NULL;
        bool needsCheckRunning = false;
        bool quitting;
        
        AutoreleasePool * pool = new AutoreleasePool();
        
        mailsem_down(mOperationSem);
        
        pthread_mutex_lock(&mLock);
        if (mOperations->count() > 0) {
            op = (Operation *) mOperations->objectAtIndex(0);
        }
        quitting = mQuitting;
        pthread_mutex_unlock(&mLock);

        //MCLog("quitting %i %p", mQuitting, op);
        if ((op == NULL) && quitting) {
            MCLog("stopping %p", this);
            mailsem_up(mStopSem);
            
            retain(); // (2)
#if __APPLE__
            performMethodOnDispatchQueue((Object::Method) &OperationQueue::stoppedOnMainThread, NULL, mDispatchQueue, true);
#else
            performMethodOnMainThread((Object::Method) &OperationQueue::stoppedOnMainThread, NULL, true);
#endif
            
            pool->release();
            break;
        }

        MCAssert(op != NULL);
        performOnCallbackThread(op, (Object::Method) &OperationQueue::beforeMain, op, true);
        
        if (!op->isCancelled() || op->shouldRunWhenCancelled()) {
            op->main();
        }
        
        op->retain()->autorelease();
        
        pthread_mutex_lock(&mLock);
        mOperations->removeObjectAtIndex(0);
        if (mOperations->count() == 0) {
            if (mWaiting) {
                mailsem_up(mWaitingFinishedSem);
            }
            needsCheckRunning = true;
        }
        pthread_mutex_unlock(&mLock);
        
        if (!op->isCancelled()) {
            performOnCallbackThread(op, (Object::Method) &OperationQueue::callbackOnMainThread, op, true);
        }
        
        if (needsCheckRunning) {
            retain(); // (1)
            //MCLog("check running %p", this);
#if __APPLE__
            performMethodOnDispatchQueue((Object::Method) &OperationQueue::checkRunningOnMainThread, this, mDispatchQueue);
#else
            performMethodOnMainThread((Object::Method) &OperationQueue::checkRunningOnMainThread, this);
#endif
        }
        
        pool->release();
    }
    MCLog("cleanup thread %p", this);
#if defined(__ANDROID) || defined(ANDROID)
    androidUnsetupThread();
#endif
}
コード例 #14
0
ファイル: slapi_ops.c プロジェクト: bagel/openldap-ga
void
slapi_int_connection_done_pb( Slapi_PBlock *pb )
{
	Connection		*conn;
	Operation		*op;

	PBLOCK_ASSERT_INTOP( pb, 0 );

	conn = pb->pb_conn;
	op = pb->pb_op;

	/* free allocated DNs */
	if ( !BER_BVISNULL( &op->o_dn ) )
		op->o_tmpfree( op->o_dn.bv_val, op->o_tmpmemctx );
	if ( !BER_BVISNULL( &op->o_ndn ) )
		op->o_tmpfree( op->o_ndn.bv_val, op->o_tmpmemctx );

	if ( !BER_BVISNULL( &op->o_req_dn ) )
		op->o_tmpfree( op->o_req_dn.bv_val, op->o_tmpmemctx );
	if ( !BER_BVISNULL( &op->o_req_ndn ) )
		op->o_tmpfree( op->o_req_ndn.bv_val, op->o_tmpmemctx );

	switch ( op->o_tag ) {
	case LDAP_REQ_MODRDN:
		if ( !BER_BVISNULL( &op->orr_newrdn ))
			op->o_tmpfree( op->orr_newrdn.bv_val, op->o_tmpmemctx );
		if ( !BER_BVISNULL( &op->orr_nnewrdn ))
			op->o_tmpfree( op->orr_nnewrdn.bv_val, op->o_tmpmemctx );
		if ( op->orr_newSup != NULL ) {
			assert( !BER_BVISNULL( op->orr_newSup ) );
			op->o_tmpfree( op->orr_newSup->bv_val, op->o_tmpmemctx );
			op->o_tmpfree( op->orr_newSup, op->o_tmpmemctx );
		}
		if ( op->orr_nnewSup != NULL ) {
			assert( !BER_BVISNULL( op->orr_nnewSup ) );
			op->o_tmpfree( op->orr_nnewSup->bv_val, op->o_tmpmemctx );
			op->o_tmpfree( op->orr_nnewSup, op->o_tmpmemctx );
		}
		slap_mods_free( op->orr_modlist, 1 );
		break;
	case LDAP_REQ_ADD:
		slap_mods_free( op->ora_modlist, 0 );
		break;
	case LDAP_REQ_MODIFY:
		slap_mods_free( op->orm_modlist, 1 );
		break;
	case LDAP_REQ_SEARCH:
		if ( op->ors_attrs != NULL ) {
			op->o_tmpfree( op->ors_attrs, op->o_tmpmemctx );
			op->ors_attrs = NULL;
		}
		break;
	default:
		break;
	}

	slapi_ch_free_string( &conn->c_authmech.bv_val );
	slapi_ch_free_string( &conn->c_dn.bv_val );
	slapi_ch_free_string( &conn->c_ndn.bv_val );
	slapi_ch_free_string( &conn->c_peer_domain.bv_val );
	slapi_ch_free_string( &conn->c_peer_name.bv_val );

	if ( conn->c_sb != NULL ) {
		ber_sockbuf_free( conn->c_sb );
	}

	slapi_int_free_object_extensions( SLAPI_X_EXT_OPERATION, op );
	slapi_int_free_object_extensions( SLAPI_X_EXT_CONNECTION, conn );

	slapi_ch_free( (void **)&pb->pb_op->o_callback );
	slapi_ch_free( (void **)&pb->pb_op );
	slapi_ch_free( (void **)&pb->pb_conn );
	slapi_ch_free( (void **)&pb->pb_rs );
}
コード例 #15
0
void Simulator::executeProgram( Program *program )
{
    int pid = program->process_control_block().processID;
    Operation* operation = program->step();
    char operationType = operation->parameters().id;

    // Create thread lambda
    auto ThreadStart = [this, operation, pid]()
    {
        handleIO(*operation, pid);
    };

    program->run();

    // Start
    if( operationType == 'A' &&
            operation->parameters().description == "start")
    {
        display("OS: starting process " + to_string(pid));
        operation = program->step();
    }

    // I/O
    if( operationType == 'I' || operationType == 'O')
    {
        display("Process: " + to_string(pid) + ": starting I/O");
        thread IO_thread(ThreadStart);
        IO_thread.detach(); // async, do not block

        program->suspend();
        suspendedPrograms_[pid] = *program;
    }

    // Processing
    else if( operationType == 'P' )
    {
        display("Process " + to_string(pid) + ": processing action");
        int quantum = 0;
        while( !operation->completed() && interrupts_.empty() )
        {
            quantum++;

            operation = program->step();
            wait( operation->parameters().cycleTime );

            if( quantum == configurationData.quantum )
            {
                // Launch a quantum interrupt to stop execution of the program
                interrupts_.push(0);
                display("Interrupt: quantum expired");
            }
        }

        if( operation->completed() )
        {
            display("Process " + to_string(pid) + ": end processing action");
        }
    }

    // The last operation in a program is an exit operation
    if( program->operations_left() <= 1 &&
            program->process_control_block().state != SUSPENDED)
    {
        program->exit();
        display("OS: removing process " + to_string(pid));
    }
}
コード例 #16
0
ファイル: Server.cpp プロジェクト: zouleipku/gStore
bool Server::parser(std::string _raw_cmd, Operation& _ret_oprt)
{
    int cmd_start_pos = 0;
    int raw_len = _raw_cmd.size();

    for (int i=0; i<raw_len; i++)
        if (_raw_cmd[i] == '\n')
        {
            _raw_cmd[i] = ' ';
        }

    while (cmd_start_pos < raw_len && _raw_cmd[cmd_start_pos] == ' ')
        cmd_start_pos ++;
    if (cmd_start_pos == raw_len)
    {
        return false;
    }

    int idx1 = raw_len;
    for (int i=cmd_start_pos; i<raw_len; i++)
        if (_raw_cmd[i] == ' ')
        {
            idx1 = i;
            break;
        }

    //cout << _raw_cmd << "\n" << cmd_start_pos << " " << idx1 << endl; //debug

    string cmd = _raw_cmd.substr(cmd_start_pos, idx1-cmd_start_pos);
    int para_start_pos = idx1;
    while (para_start_pos < raw_len && _raw_cmd[para_start_pos] == ' ')
        para_start_pos ++;

    int para_cnt;
    if (cmd == "load" || cmd == "unload")
    {
        if (cmd == "load")
        {
            _ret_oprt.setCommand(CMD_LOAD);
        }
        else
        {
            _ret_oprt.setCommand(CMD_UNLOAD);
        }
        para_cnt = 1;
    }
    else if (cmd == "import")
    {
        _ret_oprt.setCommand(CMD_IMPORT);
        para_cnt = 2;
    }
    else if (cmd == "query")
    {
        _ret_oprt.setCommand(CMD_QUERY);
        para_cnt = 1;
    }
    else if (cmd == "show")
    {
        _ret_oprt.setCommand(CMD_SHOW);
        para_cnt = 1;
    }
    else if (cmd == "insert")
    {
        _ret_oprt.setCommand(CMD_INSERT);
        para_cnt = 2;
    }
    else
    {
        return false;
    }

    vector<string> paras;
    int cur_idx = para_start_pos;
    for (int i=1; i<=para_cnt; i++)
    {
        if (cur_idx >= raw_len)
        {
            return false;
        }

        int next_idx = raw_len;
        if (i < para_cnt)
        {
            for (int j=cur_idx; j<raw_len; j++)
                if (_raw_cmd[j] == ' ')
                {
                    next_idx = j;
                    break;
                }
        }
        else
        {
            for (int j=raw_len-1; j>cur_idx; j--)
                if (_raw_cmd[j] != ' ')
                {
                    next_idx = j+1;
                    break;
                }
        }

        paras.push_back(_raw_cmd.substr(cur_idx, next_idx - cur_idx));

        cur_idx = next_idx;
        while (cur_idx < raw_len && _raw_cmd[cur_idx] == ' ')
            cur_idx ++;
    }

    if (cur_idx != raw_len)
    {
        return false;
    }

    _ret_oprt.setParameter(paras);

    return true;
}
コード例 #17
0
ファイル: BiDirScheduler.cpp プロジェクト: DrSobik/IPPS
bool BiDirScheduler::schedule(ProcessModel &pm, Resources &rc, Schedule &schedule) {
	Debugger::info << "Building schedule using simple bidirectional approach." << ENDL;

	/** Algorithm:
	 * 
	 * Lv - set of head scheduled operations;
	 * Lr - set of tail scheduled operations;
	 * Av - set of additionally head-schedulable operations;
	 * Ar - set of additianally tail-schedulable operations;
	 *  
	 *  1. Lv = Lr = 0; 
	 *	   Av = first available operations of the graph;
	 *     Ar = first available operations in the reverse graph.
	 * 
	 *  2. While  Av + Ar != 0
	 * 
	 *  2.a) select operation from Av according to some priority rule;
	 *  2.b) schedule the selected operation as soon as possible;
	 *  2.c) include the operation into Lv and exclude it from Av
	 *  2.d) select next available operation(s) which are not in Ar + Lr and insert them into Av
	 * 
	 *  2.e) select operation from Ar according to some priority rule;
	 *  2.f) schedule the selected operation as late as possible before all of the operations from Lr;
	 *  2.g) include the operation into Lr and exclude it from Ar;
	 *  2.h) select next available operation(s) (in inverse graph) which are not in Av + Lv and insert them into Ar.
	 *  
	 *	3. Shift left the start times of the operations from Lr so that they start immediately after latest from Lv finishes.
	 *  
	 * */

	QTextStream out(stdout);

	QList<ListDigraph::Node> Lv;
	QList<ListDigraph::Node> Lr;
	QList<ListDigraph::Node> Av;
	QList<ListDigraph::Node> Ar;
	QList<ListDigraph::Node> Avnext;
	QList<ListDigraph::Node> Lravail; // Currently available nodes from Lr

	QMap<ListDigraph::Node, Machine*> nodemachLr; // Assignments of the operations from Lr to the machines
	QHash<int, double> backmach; // Machines for backward operation scheduling <machine ID, time for operation finish>

	for (int i = 0; i < rc.machines().size(); i++) {
		backmach[rc.machines()[i]->ID] = 10000000;
	}

	ListDigraph::NodeMap<bool> nodesscheduled(pm.graph, false); // Scheduled nodes
	bool nodeavail; // Used for checking whether some node is available fro scheduling
	ListDigraph::Node curnode;

	Lv.clear();
	Lr.clear();
	Av.clear();
	Ar.clear();

	// Initialize the sets of operations Av
	for (ListDigraph::OutArcIt gait(pm.graph, pm.head); gait != INVALID; ++gait) {
		for (ListDigraph::OutArcIt lait(pm.graph, pm.graph.target(gait)); lait != INVALID; ++lait) {
			Av.append(pm.graph.target(lait));
		}
	}

	//out << "Operations of Av:" << endl;
	//for (int i = 0; i < Av.size(); i++) {
	//	out << Av[i] << endl;
	//}

	// Initialize the sets of operations Ar
	for (ListDigraph::InArcIt gait(pm.graph, pm.tail); gait != INVALID; ++gait) {
		for (ListDigraph::InArcIt lait(pm.graph, pm.graph.source(gait)); lait != INVALID; ++lait) {
			Ar.append(pm.graph.source(lait));
			//Ar.append(pm.graph.source(gait));
		}
	}



	//out << "Operations of Ar:" << endl;
	//for (int i = 0; i < Ar.size(); i++) {
	//	out << *pm.ops[Ar[i]] << endl;
	//}

	//getchar();

	NodeWeightComparatorGreater nwcg(&pm);

	// Run the loop
	while (Av.size() + Ar.size() > 0) {

		// Scheduling one operation from Av
		Avnext.clear();

		//out << "Scheduling operations" << endl;
		//for (int i = 0; i < Av.size(); i++) {
		//	out << pm.ops[Av[i]]->ID <<" ";
		//}
		//out<<endl;
		if (Av.size() > 0) {
			// Sort the nodes of Av
			qSort(Av.begin(), Av.end(), nwcg);

			curnode = Av[0];

			// Schedule the first operation (as soon as possible)
			//Machine &m = rc(pm.ops[Av[0]]->toolID).nextAvailable();

			// Select the fastest available machine from the corresponding tool group
			//Machine &m = rc(pm.ops[Av[0]]->toolID).fastestAvailable(pm.ops[Av[0]]->r(), pm.ops[Av[0]]->type);

			// Select the machine from the corresponding tool group to finish the operation the earliest
			Machine &m = rc(pm.ops[curnode]->toolID).earliestToFinish(pm.ops[curnode]);

			m << pm.ops[curnode];
			nodesscheduled[curnode] = true;

			// Include the operation into Lv
			Lv.append(curnode);

			// Iterate through all child nodes of the current node
			for (ListDigraph::OutArcIt oait(pm.graph, curnode); oait != INVALID; ++oait) {
				if (!Lr.contains(pm.graph.target(oait)) && !Ar.contains(pm.graph.target(oait))) {
					// Check availability
					nodeavail = true;
					for (ListDigraph::InArcIt iait(pm.graph, pm.graph.target(oait)); iait != INVALID; ++iait) {
						nodeavail = nodeavail && nodesscheduled[pm.graph.source(iait)];
					}
					if (nodeavail) {
						//out << "Now available : " << pm.graph.id(cursucc) << endl;
						// Update ready time of the newly enabled node
						pm.ops[pm.graph.target(oait)]->r(0.0);
						for (ListDigraph::InArcIt init(pm.graph, pm.graph.target(oait)); init != INVALID; ++init) {
							pm.ops[pm.graph.target(oait)]->r(Math::max(pm.ops[pm.graph.target(oait)]->r(), pm.ops[pm.graph.source(init)]->c()));
						}

						//if (!nodesscheduled[pm.graph.target(oait)]) {
						Av/*next*/.append(pm.graph.target(oait));
						//}
					}
				}
			}

			// Exclude the operation from Av
			Av.removeAt(0);
		}
		//getchar();

		//Av = Avnext;

		// Scheduling one operation from Ar
		if (Ar.size() > 0) {
			// Sort the nodes of Ar
			qSort(Ar.begin(), Ar.end(), nwcg);

			curnode = Ar.last();

			// Schedule the operation with as late as possible before all operations from Lr
			// The operation with the smallest priority is selected

			//Machine &m = rc(pm.ops[curnode]->toolID).nextAvailable();

			// Select the fastest available machine from the corresponding tool group
			//Machine &m = rc(pm.ops[curnode]->toolID).fastestAvailable(10000000, pm.ops[curnode]->type);

			// Select the random machine from the corresponding tool group
			//Machine &m = rc(pm.ops[curnode]->toolID).randomMachine();

			// Find machine which could start this operation the latest
			Machine *m = NULL;
			double lateststarttime = 0.0;
			double curstarttime;

			// Iterate over all machines able to process the operation
			QList<Machine*> machines = rc(pm.ops[curnode]->toolID).machines();
			for (int i = 0; i < machines.size(); i++) {
				curstarttime = backmach[machines[i]->ID] - machines[i]->procTime(pm.ops[curnode]);

				if (lateststarttime <= curstarttime) {
					lateststarttime = curstarttime;
					m = machines[i];
				}
			}
			
			backmach[m->ID] = lateststarttime;

			// Select the machine from the corresponding tool group to finish the operation the earliest
			//Machine &m = rc(pm.ops[curnode]->toolID).earliestToFinish(pm.ops[curnode]);

			//m << pm.ops[curnode];
			nodemachLr[curnode] = m;
			//nodesscheduled[curnode] = true;


			// Include the operation into Lr
			Lr.prepend(curnode);

			// Iterate through all parent nodes of the current node
			for (ListDigraph::InArcIt iait(pm.graph, curnode); iait != INVALID; ++iait) {
				if (!Lv.contains(pm.graph.source(iait)) && !Av.contains(pm.graph.source(iait))) {
					Ar.prepend(pm.graph.source(iait));
				}
			}

			// Exclude the operation from Av
			Ar.removeLast();
		}

		//out << "Av size = " << Av.size() << endl;

	}

	// Shift left all of the operations from Lr so that the earliest from them is started as soon as possible

	//out << "Operations in nodemachLr: " << endl;
	//for (int i = 0; i < nodemachLr.size(); i++) {
	//	out << *pm.ops[nodemachLr[i].first] << endl;
	//}

	//getchar();


	QList<ListDigraph::Node> keys;
	while (nodemachLr.size() > 0) {

		keys = nodemachLr.keys();

		// Collect currently available (immediately schedulable) nodes from Lr
		Lravail.clear();
		for (int i = 0; i < nodemachLr.size(); i++) {
			for (ListDigraph::InArcIt iait(pm.graph, keys[i]); iait != INVALID; ++iait) {
				if (Lv.contains(pm.graph.source(iait)) && nodesscheduled[pm.graph.source(iait)]) {
					Lravail.append(keys[i]);
					Lv.append(keys[i]);
					//Lr.removeOne(nodemachLr.keys()[i]);
					break;
				}
			}
		}

		//
		//Sort the nodes in Lravail
		qSort(Lravail.begin(), Lravail.end(), nwcg);

		//out << "Lravail operations before ready times update:" << endl;
		//for (int i = 0; i < Lravail.size(); i++) {
		//	out << *pm.ops[Lravail[i]] << endl;
		//}
		//getchar();

		// Update the ready time of the operations in Lravail and schedule them
		for (int i = 0; i < Lravail.size(); i++) {
			pm.ops[Lravail[i]]->r(0.0);
			for (ListDigraph::InArcIt iait(pm.graph, Lravail[i]); iait != INVALID; ++iait) {
				pm.ops[Lravail[i]]->r(Math::max(pm.ops[Lravail[i]]->r(), pm.ops[pm.graph.source(iait)]->c()));
			}

			// Schedule the available nodes
			*(nodemachLr.value(Lravail[i])) << pm.ops[Lravail[i]];
			nodesscheduled[Lravail[i]] = true;
			nodemachLr.remove(Lravail[i]);
		}

		//out << "Lravail operations after ready times update:" << endl;
		//for (int i = 0; i < Lravail.size(); i++) {
		//	out << *pm.ops[Lravail[i]] << endl;
		//}
		//getchar();
	}

	//out << "Resources after scheduling" << endl;
	//out << rc << endl;

	// Iterate over all nodes directly preceding the tail and
	//Debugger::info << "Collecting schedule data ..." << ENDL;
	schedule.objective = 0.0;
	for (ListDigraph::ArcIt ait(pm.graph); ait != INVALID; ++ait) {
		if (pm.graph.target(ait) == pm.tail) {
			if (pm.ops[pm.graph.source(ait)]->ID < 0) {
				for (ListDigraph::InArcIt iait(pm.graph, pm.graph.source(ait)); iait != INVALID; ++iait) {
					schedule.objective += pm.ops[pm.graph.source(iait)]->wT();
				}
			} else {
				schedule.objective += pm.ops[pm.graph.source(ait)]->wT();
			}
		}
	}

	//Debugger::info << "Done collecting schedule data." << ENDL;

	return true;


	// Run BFS on the reverse graph to set due date for the operations

	Operation *so;
	Operation *to;
	ReverseDigraph<ListDigraph> rg(pm.graph);
	Bfs<ReverseDigraph<ListDigraph> > bfsr(rg);
	bfsr.init();
	bfsr.addSource(pm.tail);

	//out << "Running BFS algorithm on the reverse graph ..." << endl;
	while (!bfsr.emptyQueue()) {
		curnode = bfsr.processNextNode();
		if (pm.ops[curnode]->ID < 0) continue;

		//out << "Processing node with id= " << rg.id(curnode) << " " << *(pm.ops[curnode]) << endl;

		//out << "Next available nodes:" << endl;
		for (ReverseDigraph<ListDigraph>::OutArcIt it(rg, curnode); it != INVALID; ++it) {
			// Update the due dates of the reverse target nodes
			// Rev. target d == rev. source d. - rev. source longest processing time
			so = pm.ops[rg.source(it)];
			to = pm.ops[rg.target(it)];
			to->d(so->d() - rc(so->toolID).slowestMachine(so->type).procTime(so));

			//out << "Node with id= " << rg.id(rg.target(it)) << " " << *(pm.ops[rg.target(it)]) << endl;
		}

	}
	so = to = NULL;
	//out << "Done running BFS algorithm on the reverse graph." << endl;




	return true;
}
コード例 #18
0
ファイル: dds.c プロジェクト: bhanug/likewise-open
static int
dds_expire( void *ctx, dds_info_t *di )
{
	Connection	conn = { 0 };
	OperationBuffer opbuf;
	Operation	*op;
	slap_callback	sc = { 0 };
	dds_cb_t	dc = { 0 };
	dds_expire_t	*de = NULL, **dep;
	SlapReply	rs = { REP_RESULT };

	time_t		expire;
	char		tsbuf[ LDAP_LUTIL_GENTIME_BUFSIZE ];
	struct berval	ts;

	int		ndeletes, ntotdeletes;

	int		rc;
	char		*extra = "";

	connection_fake_init( &conn, &opbuf, ctx );
	op = &opbuf.ob_op;

	op->o_tag = LDAP_REQ_SEARCH;
	memset( &op->oq_search, 0, sizeof( op->oq_search ) );

	op->o_bd = select_backend( &di->di_nsuffix[ 0 ], 0 );

	op->o_req_dn = op->o_bd->be_suffix[ 0 ];
	op->o_req_ndn = op->o_bd->be_nsuffix[ 0 ];

	op->o_dn = op->o_bd->be_rootdn;
	op->o_ndn = op->o_bd->be_rootndn;

	op->ors_scope = LDAP_SCOPE_SUBTREE;
	op->ors_tlimit = DDS_INTERVAL( di )/2 + 1;
	op->ors_slimit = SLAP_NO_LIMIT;
	op->ors_attrs = slap_anlist_no_attrs;

	expire = slap_get_time() + di->di_tolerance;
	ts.bv_val = tsbuf;
	ts.bv_len = sizeof( tsbuf );
	slap_timestamp( &expire, &ts );

	op->ors_filterstr.bv_len = STRLENOF( "(&(objectClass=" ")(" "<=" "))" )
		+ slap_schema.si_oc_dynamicObject->soc_cname.bv_len
		+ ad_entryExpireTimestamp->ad_cname.bv_len
		+ ts.bv_len;
	op->ors_filterstr.bv_val = op->o_tmpalloc( op->ors_filterstr.bv_len + 1, op->o_tmpmemctx );
	snprintf( op->ors_filterstr.bv_val, op->ors_filterstr.bv_len + 1,
		"(&(objectClass=%s)(%s<=%s))",
		slap_schema.si_oc_dynamicObject->soc_cname.bv_val,
		ad_entryExpireTimestamp->ad_cname.bv_val, ts.bv_val );

	op->ors_filter = str2filter_x( op, op->ors_filterstr.bv_val );
	if ( op->ors_filter == NULL ) {
		rs.sr_err = LDAP_OTHER;
		goto done_search;
	}

	op->o_callback = &sc;
	sc.sc_response = dds_expire_cb;
	sc.sc_private = &dc;

	(void)op->o_bd->bd_info->bi_op_search( op, &rs );

done_search:;
	op->o_tmpfree( op->ors_filterstr.bv_val, op->o_tmpmemctx );
	filter_free_x( op, op->ors_filter, 1 );

	rc = rs.sr_err;
	switch ( rs.sr_err ) {
	case LDAP_SUCCESS:
		break;

	case LDAP_NO_SUCH_OBJECT:
		/* (ITS#5267) database not created yet? */
		rs.sr_err = LDAP_SUCCESS;
		extra = " (ignored)";
		/* fallthru */

	default:
		Log2( LDAP_DEBUG_ANY, LDAP_LEVEL_ERR,
			"DDS expired objects lookup failed err=%d%s\n",
			rc, extra );
		goto done;
	}

	op->o_tag = LDAP_REQ_DELETE;
	op->o_callback = &sc;
	sc.sc_response = slap_null_cb;
	sc.sc_private = NULL;

	for ( ntotdeletes = 0, ndeletes = 1; dc.dc_ndnlist != NULL  && ndeletes > 0; ) {
		ndeletes = 0;

		for ( dep = &dc.dc_ndnlist; *dep != NULL; ) {
			de = *dep;

			op->o_req_dn = de->de_ndn;
			op->o_req_ndn = de->de_ndn;
			(void)op->o_bd->bd_info->bi_op_delete( op, &rs );
			switch ( rs.sr_err ) {
			case LDAP_SUCCESS:
				Log1( LDAP_DEBUG_STATS, LDAP_LEVEL_INFO,
					"DDS dn=\"%s\" expired.\n",
					de->de_ndn.bv_val );
				ndeletes++;
				break;

			case LDAP_NOT_ALLOWED_ON_NONLEAF:
				Log1( LDAP_DEBUG_ANY, LDAP_LEVEL_NOTICE,
					"DDS dn=\"%s\" is non-leaf; "
					"deferring.\n",
					de->de_ndn.bv_val );
				dep = &de->de_next;
				de = NULL;
				break;

			default:
				Log2( LDAP_DEBUG_ANY, LDAP_LEVEL_NOTICE,
					"DDS dn=\"%s\" err=%d; "
					"deferring.\n",
					de->de_ndn.bv_val, rs.sr_err );
				break;
			}

			if ( de != NULL ) {
				*dep = de->de_next;
				dep = &de->de_next;
				op->o_tmpfree( de, op->o_tmpmemctx );
			}
		}

		ntotdeletes += ndeletes;
	}

	rs.sr_err = LDAP_SUCCESS;

	Log1( LDAP_DEBUG_STATS, LDAP_LEVEL_INFO,
		"DDS expired=%d\n", ntotdeletes );

done:;
	return rs.sr_err;
}