示例#1
0
template <typename Result, typename Range> inline Result
urldecode(Range const &range) {

	BOOST_STATIC_ASSERT(sizeof(typename Range::value_type) == 1);
	BOOST_STATIC_ASSERT(sizeof(typename Result::value_type) == 1);
	//BOOST_STATIC_ASSERT((boost::is_same<typename Range::value_type, typename Result::value_type>::value));

	Result result;
	result.reserve(range.size());

	for (typename Range::const_iterator i = range.begin(), end = range.end(); i != end; ++i) {
		switch (*i) {
		case static_cast<typename Range::value_type>('+'):
			result.push_back(static_cast<typename Range::value_type>(' '));
			break;
		case static_cast<typename Range::value_type>('%'):
			if (std::distance(i, end) > 2) {
				typename Range::const_iterator f = i, s = i;
				std::advance(f, 1);
				std::advance(s, 2);
				typename Range::value_type first = *f, second = *s;
				int digit = (first >= 'A' ? ((first & 0xDF) - 'A') + 10 : (first - '0')) * 16;
				digit += (second >= 'A') ? ((second & 0xDF) - 'A') + 10 : (second - '0');
				result.push_back(static_cast<typename Range::value_type>(digit));
				std::advance(i, 2);
			}
			else {
				result.push_back('%');
			}
			break;
		default:
			result.push_back(*i);
			break;
		}
	}
	return result;
}
示例#2
0
 SPROUT_CONSTEXPR typename std::enable_if<
 sizeof...(Attrs) + 2 == limit::value,
           result_type
           >::type call(
               expr_type const& expr,
               context_type const& ctx,
               sprout::weed::limited::category limited_category,
               Result const& res,
               Head const& head,
               Attrs const&... attrs
           ) const
 {
     return res.success()
            ? limited_category != sprout::weed::limited::stopover
            ? call(
                expr,
                res.ctx(),
                limited_category,
                sprout::weed::eval(expr, res.ctx()),
                head,
                attrs...,
                res.attr()
            )
            : result_type(
                true,
                res.current(),
                sprout::weed::attr_cnv::times<limit::value, attr_type>(head, attrs..., res.attr()),
                res.ctx()
            )
            : result_type(
                true,
                ctx.begin(),
                sprout::weed::attr_cnv::times<limit::value, attr_type>(head, attrs...),
                ctx
            )
            ;
 }
示例#3
0
template <typename Result, typename Range> inline Result
urlencode(Range const &range) {

	BOOST_STATIC_ASSERT(sizeof(typename Range::value_type) == 1);
	BOOST_STATIC_ASSERT((boost::is_same<typename Range::value_type, typename Result::value_type>::value));

	Result result;
	result.reserve(3 * range.size());

	for (typename Range::const_iterator i = range.begin(), end = range.end(); i != end; ++i) {
		if (char_traits<typename Range::value_type>::is_alpha_numeric(*i)) {
			result.push_back(*i);
			continue;
		}
		switch (*i) {
		case static_cast<typename Range::value_type>('-'):
		case static_cast<typename Range::value_type>('_'):
		case static_cast<typename Range::value_type>('.'):
		case static_cast<typename Range::value_type>('!'):
		case static_cast<typename Range::value_type>('~'):
		case static_cast<typename Range::value_type>('*'):
		case static_cast<typename Range::value_type>('('):
		case static_cast<typename Range::value_type>(')'):
		case static_cast<typename Range::value_type>('\''):
			result.push_back(*i);
			break;
		default:
			typename Range::value_type bytes[3] = { '%', (*i & 0xF0) / 16, *i & 0x0F };
			for (std::size_t i = 1; i < sizeof(bytes); ++i) {
				bytes[i] += (bytes[i] > 9) ? 'A' - 10 : '0';
			}
			result.insert(result.end(), bytes, bytes + sizeof(bytes));
			break;
		}
	}
	return result;
}
示例#4
0
文件: script.cpp 项目: lins05/mesos
void execute(const string& script)
{
  // Create a temporary directory for the test.
  Try<string> directory = environment->mkdtemp();

  CHECK_SOME(directory) << "Failed to create temporary directory";

  if (flags.verbose) {
    std::cerr << "Using temporary directory '"
              << directory.get() << "'" << std::endl;
  }

  // Determine the path for the script.
  Result<string> path =
    os::realpath(path::join(flags.source_dir, "src", "tests", script));

  if (!path.isSome()) {
    FAIL() << "Failed to locate script: "
           << (path.isError() ? path.error() : "No such file or directory");
  }

  // Fork a process to change directory and run the test.
  pid_t pid;
  if ((pid = fork()) == -1) {
    FAIL() << "Failed to fork to launch script";
  }

  if (pid > 0) {
    // In parent process.
    int status;
    while (wait(&status) != pid || WIFSTOPPED(status));
    CHECK(WIFEXITED(status) || WIFSIGNALED(status));

    if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
      FAIL() << script << " " << WSTRINGIFY(status);
    }
  } else {
    // In child process. DO NOT USE GLOG!

    // Start by cd'ing into the temporary directory.
    Try<Nothing> chdir = os::chdir(directory.get());
    if (chdir.isError()) {
      std::cerr << "Failed to chdir to '" << directory.get() << "': "
                << chdir.error() << std::endl;
      abort();
    }

    // Redirect output to /dev/null unless the test is verbose.
    if (!flags.verbose) {
      if (freopen("/dev/null", "w", stdout) == NULL ||
          freopen("/dev/null", "w", stderr) == NULL) {
        std::cerr << "Failed to redirect stdout/stderr to /dev/null:"
                  << os::strerror(errno) << std::endl;
        abort();
      }
    }

    // Set up the environment for executing the script.
    os::setenv("MESOS_SOURCE_DIR", flags.source_dir);
    os::setenv("MESOS_BUILD_DIR", flags.build_dir);
    os::setenv("MESOS_WEBUI_DIR", path::join(flags.source_dir, "src", "webui"));
    os::setenv("MESOS_LAUNCHER_DIR", path::join(flags.build_dir, "src"));

    // Enable replicated log based registry.
    os::setenv("MESOS_REGISTRY", "replicated_log");

    // Enable authentication.
    os::setenv("MESOS_AUTHENTICATE", "true");

    // Create test credentials.
    const string& credentials =
      DEFAULT_CREDENTIAL.principal() + " " + DEFAULT_CREDENTIAL.secret();

    const string& credentialsPath =
      path::join(directory.get(), "credentials");

    CHECK_SOME(os::write(credentialsPath, credentials))
      << "Failed to write credentials to '" << credentialsPath << "'";

    os::setenv("MESOS_CREDENTIALS", "file://" + credentialsPath);

    // We set test credentials here for example frameworks to use.
    os::setenv("DEFAULT_PRINCIPAL", DEFAULT_CREDENTIAL.principal());
    os::setenv("DEFAULT_SECRET", DEFAULT_CREDENTIAL.secret());

    // TODO(bmahler): Update the example frameworks to use flags and
    // remove the special DEFAULT_* environment variables above.
    os::setenv("MESOS_PRINCIPAL", DEFAULT_CREDENTIAL.principal());
    os::setenv("MESOS_SECRET", DEFAULT_CREDENTIAL.secret());

    // Create test ACLs.
    ACLs acls;
    acls.set_permissive(false);

    mesos::ACL::RunTask* run = acls.add_run_tasks();
    run->mutable_principals()->add_values(DEFAULT_CREDENTIAL.principal());

    Result<string> user = os::user();
    CHECK_SOME(user) << "Failed to get current user name";
    run->mutable_users()->add_values(user.get());

    mesos::ACL::RegisterFramework* register_ = acls.add_register_frameworks();
    register_->mutable_principals()->add_values(DEFAULT_CREDENTIAL.principal());
    register_->mutable_roles()->add_values("*");

    const string& aclsPath = path::join(directory.get(), "acls");

    CHECK_SOME(os::write(aclsPath, stringify(JSON::protobuf(acls))))
      << "Failed to write ACLs to '" << aclsPath << "'";

    os::setenv("MESOS_ACLS", "file://" + aclsPath);

    // Now execute the script.
    execl(path.get().c_str(), path.get().c_str(), (char*) NULL);

    std::cerr << "Failed to execute '" << script << "': "
              << os::strerror(errno) << std::endl;
    abort();
  }
}
void Dialog::onPlayFrame(const Result& result) {
    if(result.getValue() >= valve)
        ui->label_status->setText(trUtf8("发现火灾!"));
    else
        ui->label_status->setText(trUtf8("播放中"));
}
void btGjkPairDetector::getClosestPointsNonVirtual(const ClosestPointInput& input, Result& output, class btIDebugDraw* debugDraw)
#endif
{
	m_cachedSeparatingDistance = 0.f;

	btScalar distance=btScalar(0.);
	btVector3	normalInB(btScalar(0.),btScalar(0.),btScalar(0.));

	btVector3 pointOnA,pointOnB;
	btTransform	localTransA = input.m_transformA;
	btTransform localTransB = input.m_transformB;
	btVector3 positionOffset=(localTransA.getOrigin() + localTransB.getOrigin()) * btScalar(0.5);
	localTransA.getOrigin() -= positionOffset;
	localTransB.getOrigin() -= positionOffset;

	bool check2d = m_minkowskiA->isConvex2d() && m_minkowskiB->isConvex2d();

	btScalar marginA = m_marginA;
	btScalar marginB = m_marginB;

	gNumGjkChecks++;

	//for CCD we don't use margins
	if (m_ignoreMargin)
	{
		marginA = btScalar(0.);
		marginB = btScalar(0.);
	}

	m_curIter = 0;
	int gGjkMaxIter = 1000;//this is to catch invalid input, perhaps check for #NaN?
	m_cachedSeparatingAxis.setValue(0,1,0);

	bool isValid = false;
	bool checkSimplex = false;
	bool checkPenetration = true;
	m_degenerateSimplex = 0;

	m_lastUsedMethod = -1;

	{
		btScalar squaredDistance = BT_LARGE_FLOAT;
		btScalar delta = btScalar(0.);
		
		btScalar margin = marginA + marginB;
		
		

		m_simplexSolver->reset();
		
		for ( ; ; )
		//while (true)
		{

			btVector3 seperatingAxisInA = (-m_cachedSeparatingAxis)* input.m_transformA.getBasis();
			btVector3 seperatingAxisInB = m_cachedSeparatingAxis* input.m_transformB.getBasis();


			btVector3 pInA = m_minkowskiA->localGetSupportVertexWithoutMarginNonVirtual(seperatingAxisInA);
			btVector3 qInB = m_minkowskiB->localGetSupportVertexWithoutMarginNonVirtual(seperatingAxisInB);

			btVector3  pWorld = localTransA(pInA);	
			btVector3  qWorld = localTransB(qInB);


			if (check2d)
			{
				pWorld[2] = 0.f;
				qWorld[2] = 0.f;
			}

			btVector3 w	= pWorld - qWorld;
			delta = m_cachedSeparatingAxis.dot(w);

			// potential exit, they don't overlap
			if ((delta > btScalar(0.0)) && (delta * delta > squaredDistance * input.m_maximumDistanceSquared)) 
			{
				m_degenerateSimplex = 10;
				checkSimplex=true;
				//checkPenetration = false;
				break;
			}

			//exit 0: the new point is already in the simplex, or we didn't come any closer
			if (m_simplexSolver->inSimplex(w))
			{
				m_degenerateSimplex = 1;
				checkSimplex = true;
				break;
			}
			// are we getting any closer ?
			btScalar f0 = squaredDistance - delta;
			btScalar f1 = squaredDistance * REL_ERROR2;

			if (f0 <= f1)
			{
				if (f0 <= btScalar(0.))
				{
					m_degenerateSimplex = 2;
				} else
				{
					m_degenerateSimplex = 11;
				}
				checkSimplex = true;
				break;
			}

			//add current vertex to simplex
			m_simplexSolver->addVertex(w, pWorld, qWorld);
			btVector3 newCachedSeparatingAxis;

			//calculate the closest point to the origin (update vector v)
			if (!m_simplexSolver->closest(newCachedSeparatingAxis))
			{
				m_degenerateSimplex = 3;
				checkSimplex = true;
				break;
			}

			if(newCachedSeparatingAxis.length2()<REL_ERROR2)
            {
				m_cachedSeparatingAxis = newCachedSeparatingAxis;
                m_degenerateSimplex = 6;
                checkSimplex = true;
                break;
            }

			btScalar previousSquaredDistance = squaredDistance;
			squaredDistance = newCachedSeparatingAxis.length2();
#if 0
///warning: this termination condition leads to some problems in 2d test case see Bullet/Demos/Box2dDemo
			if (squaredDistance>previousSquaredDistance)
			{
				m_degenerateSimplex = 7;
				squaredDistance = previousSquaredDistance;
                checkSimplex = false;
                break;
			}
#endif //
			

			//redundant m_simplexSolver->compute_points(pointOnA, pointOnB);

			//are we getting any closer ?
			if (previousSquaredDistance - squaredDistance <= SIMD_EPSILON * previousSquaredDistance) 
			{ 
//				m_simplexSolver->backup_closest(m_cachedSeparatingAxis);
				checkSimplex = true;
				m_degenerateSimplex = 12;
				
				break;
			}

			m_cachedSeparatingAxis = newCachedSeparatingAxis;

			  //degeneracy, this is typically due to invalid/uninitialized worldtransforms for a btCollisionObject   
              if (m_curIter++ > gGjkMaxIter)   
              {   
                      #if defined(DEBUG) || defined (_DEBUG)

                              printf("btGjkPairDetector maxIter exceeded:%i\n",m_curIter);   
                              printf("sepAxis=(%f,%f,%f), squaredDistance = %f, shapeTypeA=%i,shapeTypeB=%i\n",   
                              m_cachedSeparatingAxis.getX(),   
                              m_cachedSeparatingAxis.getY(),   
                              m_cachedSeparatingAxis.getZ(),   
                              squaredDistance,   
                              m_minkowskiA->getShapeType(),   
                              m_minkowskiB->getShapeType());   

                      #endif   
                      break;   

              } 


			bool check = (!m_simplexSolver->fullSimplex());
			//bool check = (!m_simplexSolver->fullSimplex() && squaredDistance > SIMD_EPSILON * m_simplexSolver->maxVertex());

			if (!check)
			{
				//do we need this backup_closest here ?
//				m_simplexSolver->backup_closest(m_cachedSeparatingAxis);
				m_degenerateSimplex = 13;
				break;
			}
		}

		if (checkSimplex)
		{
			m_simplexSolver->compute_points(pointOnA, pointOnB);
			normalInB = m_cachedSeparatingAxis;

			btScalar lenSqr =m_cachedSeparatingAxis.length2();
			
			//valid normal
			if (lenSqr < 0.0001)
			{
				m_degenerateSimplex = 5;
			} 
			if (lenSqr > SIMD_EPSILON*SIMD_EPSILON)
			{
				btScalar rlen = btScalar(1.) / btSqrt(lenSqr );
				normalInB *= rlen; //normalize

				btScalar s = btSqrt(squaredDistance);
			
				btAssert(s > btScalar(0.0));
				pointOnA -= m_cachedSeparatingAxis * (marginA / s);
				pointOnB += m_cachedSeparatingAxis * (marginB / s);
				distance = ((btScalar(1.)/rlen) - margin);
				isValid = true;
				
				m_lastUsedMethod = 1;
			} else
			{
				m_lastUsedMethod = 2;
			}
		}

		bool catchDegeneratePenetrationCase = 
			(m_catchDegeneracies && m_penetrationDepthSolver && m_degenerateSimplex && ((distance+margin) < 0.01));

		//if (checkPenetration && !isValid)
		if (checkPenetration && (!isValid || catchDegeneratePenetrationCase ))
		{
			//penetration case

			//if there is no way to handle penetrations, bail out
			if (m_penetrationDepthSolver)
			{
				// Penetration depth case.
				btVector3 tmpPointOnA,tmpPointOnB;
				
				gNumDeepPenetrationChecks++;
				m_cachedSeparatingAxis.setZero();

				bool isValid2 = m_penetrationDepthSolver->calcPenDepth( 
					*m_simplexSolver, 
					m_minkowskiA,m_minkowskiB,
					localTransA,localTransB,
					m_cachedSeparatingAxis, tmpPointOnA, tmpPointOnB,
					debugDraw
					);


				if (isValid2)
				{
					btVector3 tmpNormalInB = tmpPointOnB-tmpPointOnA;
					btScalar lenSqr = tmpNormalInB.length2();
					if (lenSqr <= (SIMD_EPSILON*SIMD_EPSILON))
					{
						tmpNormalInB = m_cachedSeparatingAxis;
						lenSqr = m_cachedSeparatingAxis.length2();
					}

					if (lenSqr > (SIMD_EPSILON*SIMD_EPSILON))
					{
						tmpNormalInB /= btSqrt(lenSqr);
						btScalar distance2 = -(tmpPointOnA-tmpPointOnB).length();
						m_lastUsedMethod = 3;
						//only replace valid penetrations when the result is deeper (check)
						if (!isValid || (distance2 < distance))
						{
							distance = distance2;
							pointOnA = tmpPointOnA;
							pointOnB = tmpPointOnB;
							normalInB = tmpNormalInB;
							///todo: need to track down this EPA penetration solver degeneracy
							///the penetration solver reports penetration but the contact normal
							///connecting the contact points is pointing in the opposite direction
							///until then, detect the issue and revert the normal
							{
								btScalar d1=0;
								{
									btVector3 seperatingAxisInA = (normalInB)* input.m_transformA.getBasis();
									btVector3 seperatingAxisInB = -normalInB* input.m_transformB.getBasis();
								

									btVector3 pInA = m_minkowskiA->localGetSupportVertexWithoutMarginNonVirtual(seperatingAxisInA);
									btVector3 qInB = m_minkowskiB->localGetSupportVertexWithoutMarginNonVirtual(seperatingAxisInB);

									btVector3  pWorld = localTransA(pInA);	
									btVector3  qWorld = localTransB(qInB);
									btVector3 w	= pWorld - qWorld;
									d1 = (-normalInB).dot(w);
								}
								btScalar d0 = 0.f;
								{
									btVector3 seperatingAxisInA = (-normalInB)* input.m_transformA.getBasis();
									btVector3 seperatingAxisInB = normalInB* input.m_transformB.getBasis();
								

									btVector3 pInA = m_minkowskiA->localGetSupportVertexWithoutMarginNonVirtual(seperatingAxisInA);
									btVector3 qInB = m_minkowskiB->localGetSupportVertexWithoutMarginNonVirtual(seperatingAxisInB);

									btVector3  pWorld = localTransA(pInA);	
									btVector3  qWorld = localTransB(qInB);
									btVector3 w	= pWorld - qWorld;
									d0 = normalInB.dot(w);
								}
								if (d1>d0)
								{
									m_lastUsedMethod = 10;
									normalInB*=-1;
								} 

							}
							isValid = true;
							
						} else
						{
							m_lastUsedMethod = 8;
						}
					} else
					{
						m_lastUsedMethod = 9;
					}
				} else

				{
					///this is another degenerate case, where the initial GJK calculation reports a degenerate case
					///EPA reports no penetration, and the second GJK (using the supporting vector without margin)
					///reports a valid positive distance. Use the results of the second GJK instead of failing.
					///thanks to Jacob.Langford for the reproduction case
					///http://code.google.com/p/bullet/issues/detail?id=250

				
					if (m_cachedSeparatingAxis.length2() > btScalar(0.))
					{
						btScalar distance2 = (tmpPointOnA-tmpPointOnB).length()-margin;
						//only replace valid distances when the distance is less
						if (!isValid || (distance2 < distance))
						{
							distance = distance2;
							pointOnA = tmpPointOnA;
							pointOnB = tmpPointOnB;
							pointOnA -= m_cachedSeparatingAxis * marginA ;
							pointOnB += m_cachedSeparatingAxis * marginB ;
							normalInB = m_cachedSeparatingAxis;
							normalInB.normalize();

							isValid = true;
							m_lastUsedMethod = 6;
						} else
						{
							m_lastUsedMethod = 5;
						}
					}
				}
				
			}

		}
	}

	

	if (isValid && ((distance < 0) || (distance*distance < input.m_maximumDistanceSquared)))
	{

		m_cachedSeparatingAxis = normalInB;
		m_cachedSeparatingDistance = distance;

		output.addContactPoint(
			normalInB,
			pointOnB+positionOffset,
			distance);

	}


}
Result BPlusTree::recursiveRemove(Key clave, Node *nodoCorriente, Node *nodoIzquierda, Node *nodoDerecha,
		InnerNode *nodoPadreIzquierda, InnerNode *nodoPadreDerecha, InnerNode *nodoPadre, int posicionPadre) {

	if (nodoCorriente->isLeaf()) {

		LeafNode *nodoHojaCorriente = static_cast<LeafNode*> (nodoCorriente);
		LeafNode *nodoHojaIzquierda = static_cast<LeafNode*> (nodoIzquierda);
		LeafNode *nodoHojaDerecha = static_cast<LeafNode*> (nodoDerecha);
		int posicion = getPosition(nodoHojaCorriente, clave);
		if (posicion >= nodoHojaCorriente->keyMount || !equalKey(clave, nodoHojaCorriente->keys[posicion])) {
			return Result::NO_ENCONTRADO;
		}

		nodoHojaCorriente->occupiedSpace -= (nodoHojaCorriente->byteData[posicion].getSize() + nodoHojaCorriente->keys[posicion].getSize() + TreeConstraits::getControlSizeRecord());
		nodoHojaCorriente->keyMount--;
		for (int i = posicion; i < nodoHojaCorriente->keyMount; i++) {
			nodoHojaCorriente->keys[i] = nodoHojaCorriente->keys[i + 1];
			nodoHojaCorriente->byteData[i] = nodoHojaCorriente->byteData[i + 1];
		}

		Result resultado = Result::OK;

		// si se borro el elemento de la ultima posicion y no es la raiz
		if (posicion == nodoHojaCorriente->keyMount && nodoPadre) {
			if (posicionPadre < nodoPadre->keyMount) {
				if (nodoHojaCorriente->keyMount >= 1) {
					nodoPadre->occupiedSpace -= nodoPadre->keys[posicionPadre].getSize();
					nodoPadre->occupiedSpace += nodoHojaCorriente->keys[nodoHojaCorriente->keyMount - 1].getSize();
					nodoPadre->keys[posicionPadre] = nodoHojaCorriente->keys[nodoHojaCorriente->keyMount - 1];
				}
			} else {
				if (nodoHojaCorriente->keyMount >= 1) {
					resultado |= Result (Result::ACTUALIZAR_ULTIMA_CLAVE, nodoHojaCorriente->keys[nodoHojaCorriente->keyMount - 1]);
				} else {
					resultado |= Result (Result::ACTUALIZAR_ULTIMA_CLAVE, nodoHojaIzquierda->keys[nodoHojaIzquierda->keyMount - 1]);
				}
			}
		}

		if (nodoHojaCorriente->isUnderflow() && !(nodoHojaCorriente == root && nodoHojaCorriente->keyMount >= 1)) {

			if (nodoHojaIzquierda == NULL && nodoHojaDerecha == NULL) {
				persistNode(root);
				if (root)
					freeNodeMemory(root);
				root = nodoHojaCorriente = NULL;
				firstLeaf = 0;
				string archivoConfiguracion = fileBlockManager->getPath() + ".cnf";
				remove(archivoConfiguracion.c_str());
				return Result::OK;
			// @fusion
			} else if (( (nodoHojaIzquierda == NULL || !nodoHojaIzquierda->elementsCanTransfer())
						&& (nodoHojaDerecha == NULL	|| !nodoHojaDerecha->elementsCanTransfer()))
						|| nodoHojaCorriente->keyMount == 0) {

					if (nodoPadreIzquierda == nodoPadre) { //  cte e izq son hermanos.
						resultado |= leafNodeFusion(nodoHojaIzquierda, nodoHojaCorriente);
					}else {
						resultado |= leafNodeFusion(nodoHojaCorriente, nodoHojaDerecha);
					}
			// si la derecha mas cargada redistribuyo
			} else if ((nodoHojaIzquierda != NULL && !nodoHojaIzquierda->elementsCanTransfer())
						&& (nodoHojaDerecha != NULL	&& nodoHojaDerecha->elementsCanTransfer())) {

					if (nodoPadreDerecha == nodoPadre) {
						resultado |= redistributeLeftLeaf(nodoHojaCorriente, nodoHojaDerecha, nodoPadreDerecha, posicionPadre);
					} else {
						resultado |= leafNodeFusion(nodoHojaIzquierda, nodoHojaCorriente);
					}
			// si la izquierda mas cargada  redistribuyo
			} else	if ((nodoHojaIzquierda != NULL && nodoHojaIzquierda->elementsCanTransfer())
						&& (nodoHojaDerecha != NULL && !nodoHojaDerecha->elementsCanTransfer())) {

					if (nodoPadreIzquierda == nodoPadre) {
						redistributeRightLeaf(nodoHojaIzquierda, nodoHojaCorriente,	nodoPadreIzquierda, posicionPadre - 1);
					} else {
						resultado |= leafNodeFusion(nodoHojaCorriente, nodoHojaDerecha);
					}
			// izq cte y der son todos hermanos, me fijo cual tiene mas carga y redistribuyo
			} else	if (nodoPadreIzquierda == nodoPadreDerecha) {
					if (nodoHojaIzquierda->occupiedSpace <= nodoHojaDerecha->occupiedSpace) {
						resultado |= redistributeLeftLeaf(nodoHojaCorriente, nodoHojaDerecha, nodoPadreDerecha, posicionPadre);
					} else {
						redistributeRightLeaf(nodoHojaIzquierda, nodoHojaCorriente, nodoPadreIzquierda, posicionPadre - 1);
					}

			} else {
				if (nodoPadreIzquierda == nodoPadre) {
					redistributeRightLeaf(nodoHojaIzquierda, nodoHojaCorriente,	nodoPadreIzquierda, posicionPadre - 1);
				} else {
					resultado |= redistributeLeftLeaf(nodoHojaCorriente, nodoHojaDerecha, nodoPadreDerecha, posicionPadre);
				}
			}
		} else {
			persistNode(nodoHojaCorriente);
		}
		return resultado;

	} else {

		InnerNode *nodoInteriorCorriente = static_cast<InnerNode*> (nodoCorriente);
		InnerNode *nodoInteriorIzquierda = static_cast<InnerNode*> (nodoIzquierda);
		InnerNode *nodoInteriorDerecha = static_cast<InnerNode*> (nodoDerecha);
		Node *auxNodoIzquierda, *auxNodoDerecha;
		InnerNode *auxPadreIzquierda, *auxPadreDerecha;

		int posicion = getPosition(nodoInteriorCorriente, clave);
		if (posicion == 0) {
			auxNodoIzquierda = (nodoIzquierda == NULL) ? NULL : hidratateNode((static_cast<InnerNode*> (nodoIzquierda))->sons[nodoIzquierda->keyMount]);
			auxPadreIzquierda = nodoPadreIzquierda;
		} else {
			auxNodoIzquierda = hidratateNode(nodoInteriorCorriente->sons[posicion - 1]);
			auxPadreIzquierda = nodoInteriorCorriente;
		}

		if (posicion == nodoInteriorCorriente->keyMount) {
			auxNodoDerecha = (nodoDerecha == NULL) ? NULL : hidratateNode((static_cast<InnerNode*> (nodoDerecha))->sons[0]);
			auxPadreDerecha = nodoPadreDerecha;
		} else {
			auxNodoDerecha = hidratateNode(nodoInteriorCorriente->sons[posicion + 1]);
			auxPadreDerecha = nodoInteriorCorriente;
		}
//		if(clave.getKey().compare("438") == 0)
//			std::cout << "llamada recursiva: nodointeriorcorriente: " << nodoInteriorCorriente->number << "posicion: " << posicion << endl;
		Node* auxNodoCorriente = hidratateNode(nodoInteriorCorriente->sons[posicion]);
		Result resultadoParcial = recursiveRemove(clave, auxNodoCorriente, auxNodoIzquierda, auxNodoDerecha, auxPadreIzquierda, auxPadreDerecha, nodoInteriorCorriente, posicion);
		Result resultado = Result::OK;

		if (auxNodoIzquierda)
			freeNodeMemory(auxNodoIzquierda);
		if (auxNodoDerecha)
			freeNodeMemory(auxNodoDerecha);
		if (auxNodoCorriente)
			freeNodeMemory(auxNodoCorriente);

		if (resultadoParcial.contains(Result::NO_ENCONTRADO)) {
			return resultadoParcial;
		}

		if (resultadoParcial.contains(Result::ACTUALIZAR_ULTIMA_CLAVE)) {
			if (nodoPadre && posicionPadre < nodoPadre->keyMount) {
				nodoPadre->occupiedSpace -= nodoPadre->keys[posicionPadre].getSize();
				nodoPadre->occupiedSpace += resultadoParcial.ultimaClave.getSize();
				nodoPadre->keys[posicionPadre] = resultadoParcial.ultimaClave;
			} else {
				resultado |= Result(Result::ACTUALIZAR_ULTIMA_CLAVE, resultadoParcial.ultimaClave);
			}
		}

		if (resultadoParcial.contains(Result::FUSION_NODOS)) {
			Node* nodoHijo = hidratateNode(nodoInteriorCorriente->sons[posicion]);
			if (nodoHijo->keyMount != 0)
				posicion++;

			Key claveInteriorBorrada = nodoInteriorCorriente->keys[posicion - 1];
			for (int i = posicion; i < nodoInteriorCorriente->keyMount; i++) {
				nodoInteriorCorriente->keys[i - 1] = nodoInteriorCorriente->keys[i];
				nodoInteriorCorriente->sons[i] = nodoInteriorCorriente->sons[i + 1];
			}
			nodoInteriorCorriente->keyMount--;
			nodoInteriorCorriente->occupiedSpace -= (claveInteriorBorrada.getSize() + TreeConstraits::getControlSizeRecord());
			nodoInteriorCorriente->occupiedSpace -= nodoInteriorCorriente->keys[nodoInteriorCorriente->keyMount].getSize();

			if (nodoHijo)
				freeNodeMemory(nodoHijo);
			if (nodoInteriorCorriente->level == 1) {
				posicion--;
				nodoHijo = hidratateNode(nodoInteriorCorriente->sons[posicion]);
				nodoInteriorCorriente->occupiedSpace -= nodoInteriorCorriente->keys[posicion].getSize();
				nodoInteriorCorriente->occupiedSpace += nodoHijo->keys[nodoHijo->keyMount - 1].getSize();
				nodoInteriorCorriente->keys[posicion] = nodoHijo->keys[nodoHijo->keyMount - 1];
				if (nodoHijo)
					freeNodeMemory(nodoHijo);
			}
		}

		if (resultadoParcial.contains(Result::FUSION_NODOS)
				&& nodoInteriorCorriente->isUnderflow()
				&& !(nodoInteriorCorriente == root && nodoInteriorCorriente->keyMount >= 1)) {

			if (nodoInteriorIzquierda == NULL && nodoInteriorDerecha == NULL) {
				root = hidratateNode(nodoInteriorCorriente->sons[0]);
				root->number = 0;
				persistNode(root);
				freeNodes.push_back(nodoInteriorCorriente->sons[0]);
				serializeDataConfig();
				return Result::OK;

			} else if ((nodoInteriorIzquierda == NULL || !nodoInteriorIzquierda->elementsCanTransfer())
					&& (nodoInteriorDerecha == NULL || !nodoInteriorDerecha->elementsCanTransfer())) {

				if (nodoPadreIzquierda == nodoPadre) {
					resultado |= innerNodeFusion(nodoInteriorIzquierda, nodoInteriorCorriente, nodoPadreIzquierda, posicionPadre - 1);
				} else {
					resultado |= innerNodeFusion(nodoInteriorCorriente, nodoInteriorDerecha, nodoPadreDerecha, posicionPadre);
				}

			} else if ((nodoInteriorIzquierda != NULL && !nodoInteriorIzquierda->elementsCanTransfer())
					&& (nodoInteriorDerecha != NULL && nodoInteriorDerecha->elementsCanTransfer())) {

				if (nodoPadreDerecha == nodoPadre) {
					redistributeLeftInner(nodoInteriorCorriente, nodoInteriorDerecha, nodoPadreDerecha, posicionPadre);
				} else {
					resultado |= innerNodeFusion(nodoInteriorIzquierda, nodoInteriorCorriente, nodoPadreIzquierda, posicionPadre - 1);
				}

			} else if ((nodoInteriorIzquierda != NULL && nodoInteriorIzquierda->elementsCanTransfer())
					&& (nodoInteriorDerecha != NULL && !nodoInteriorDerecha->elementsCanTransfer())) {

				if (nodoPadreIzquierda == nodoPadre) {
					redistributeRightInner(nodoInteriorIzquierda, nodoInteriorCorriente, nodoPadreIzquierda, posicionPadre - 1);
				} else {
					resultado |= innerNodeFusion(nodoInteriorCorriente, nodoInteriorDerecha, nodoPadreDerecha, posicionPadre);
				}

			} else if (nodoPadreIzquierda == nodoPadreDerecha) {

				if (nodoInteriorIzquierda->keyMount <= nodoInteriorDerecha->keyMount) {
					redistributeLeftInner(nodoInteriorCorriente, nodoInteriorDerecha, nodoPadreDerecha, posicionPadre);
				} else {
					redistributeRightInner(nodoInteriorIzquierda, nodoInteriorCorriente, nodoPadreIzquierda, posicionPadre - 1);
				}

			} else {

				if (nodoPadreIzquierda == nodoPadre) {
					redistributeRightInner(nodoInteriorIzquierda, nodoInteriorCorriente, nodoPadreIzquierda, posicionPadre - 1);
				} else {
					redistributeLeftInner(nodoInteriorCorriente, nodoInteriorDerecha, nodoPadreDerecha, posicionPadre);
				}
			}

		} else {
			persistNode(nodoInteriorCorriente);
		}

		return resultado;
	}
}
示例#8
0
TEST(QoSIpcPipelineTest, AssuranceDetectorTwoDropCorrectionsWithEma) {
  uint64_t WINDOWS_SIZE = 10;
  uint64_t CONTENTION_COOLDOWN = 4;
  double_t FRATIONAL_THRESHOLD = 0.3;
  double_t SEVERITY_LEVEL = 1;
  double_t NEAR_LEVEL = 0.1;

  MockSlaveUsage mockSlaveUsage(QOS_PIPELINE_FIXTURE2);

  SerenityConfig conf;
  conf["Detector"] = createAssuranceDetectorCfg(
    WINDOWS_SIZE,
    CONTENTION_COOLDOWN,
    FRATIONAL_THRESHOLD,
    SEVERITY_LEVEL,
    NEAR_LEVEL);
  conf.set(ema::ALPHA, 0.9);
  conf.set(ENABLED_VISUALISATION, false);
  conf.set(VALVE_OPENED, true);

  QoSControllerPipeline* pipeline = new CpuQoSPipeline(conf);

  // First iteration.
  Result<QoSCorrections> corrections =
      pipeline->run(mockSlaveUsage.usage().get());
  EXPECT_NONE(corrections);

  ResourceUsage usage = mockSlaveUsage.usage().get();
  const int32_t LOAD_ITERATIONS = 17;
  LoadGenerator loadGen(
      [](double_t iter) { return 1; },
      new ZeroNoise(),
      LOAD_ITERATIONS);

  for (; loadGen.end(); loadGen++) {
    // Test scenario: After 10 iterations create drop in IPC
    // for executor num 3.
    double_t ipcFor3Executor = (*loadGen)();
    if (loadGen.iteration >= 11) {
      ipcFor3Executor /= 2.0;
    }

    usage.mutable_executors(PR_4CPUS)->CopyFrom(
        generateIPC(usage.executors(PR_4CPUS),
                    ipcFor3Executor,
                    (*loadGen).timestamp));

    usage.mutable_executors(PR_2CPUS)->CopyFrom(
        generateIPC(usage.executors(PR_2CPUS),
                    (*loadGen)(),
                    (*loadGen).timestamp));
    // Third iteration (repeated).
    corrections = pipeline->run(usage);

    // Assurance Detector will wait for signal to be returned to the
    // established state.
    if (loadGen.iteration == 11 || loadGen.iteration == 16) {
      EXPECT_SOME(corrections);
      ASSERT_EQ(slave::QoSCorrection_Type_KILL,
                corrections.get().front().type());
      // Make sure that we do not kill PR tasks!
      EXPECT_NE("serenityPR",
                corrections.get().front().kill().executor_id().value());
      EXPECT_NE("serenityPR2",
                corrections.get().front().kill().executor_id().value());
    } else {
      EXPECT_SOME(corrections);
      EXPECT_TRUE(corrections.get().empty());
    }
  }

  delete pipeline;
}
示例#9
0
Future<Nothing> PosixFilesystemIsolatorProcess::update(
    const ContainerID& containerId,
    const Resources& resources)
{
  if (!infos.contains(containerId)) {
    return Failure("Unknown container");
  }

  const Owned<Info>& info = infos[containerId];

  // TODO(jieyu): Currently, we only allow non-nested relative
  // container paths for volumes. This is enforced by the master. For
  // those volumes, we create symlinks in the executor directory.
  Resources current = info->resources;

  // We first remove unneeded persistent volumes.
  foreach (const Resource& resource, current.persistentVolumes()) {
    // This is enforced by the master.
    CHECK(resource.disk().has_volume());

    // Ignore absolute and nested paths.
    const string& containerPath = resource.disk().volume().container_path();
    if (strings::contains(containerPath, "/")) {
      LOG(WARNING) << "Skipping updating symlink for persistent volume "
                   << resource << " of container " << containerId
                   << " because the container path '" << containerPath
                   << "' contains slash";
      continue;
    }

    if (resources.contains(resource)) {
      continue;
    }

    string link = path::join(info->directory, containerPath);

    LOG(INFO) << "Removing symlink '" << link << "' for persistent volume "
              << resource << " of container " << containerId;

    Try<Nothing> rm = os::rm(link);
    if (rm.isError()) {
      return Failure(
          "Failed to remove the symlink for the unneeded "
          "persistent volume at '" + link + "'");
    }
  }

  // We then link additional persistent volumes.
  foreach (const Resource& resource, resources.persistentVolumes()) {
    // This is enforced by the master.
    CHECK(resource.disk().has_volume());

    // Ignore absolute and nested paths.
    const string& containerPath = resource.disk().volume().container_path();
    if (strings::contains(containerPath, "/")) {
      LOG(WARNING) << "Skipping updating symlink for persistent volume "
                   << resource << " of container " << containerId
                   << " because the container path '" << containerPath
                   << "' contains slash";
      continue;
    }

    if (current.contains(resource)) {
      continue;
    }

    string original = paths::getPersistentVolumePath(flags.work_dir, resource);

    // Set the ownership of the persistent volume to match that of the
    // sandbox directory.
    //
    // NOTE: Currently, persistent volumes in Mesos are exclusive,
    // meaning that if a persistent volume is used by one task or
    // executor, it cannot be concurrently used by other task or
    // executor. But if we allow multiple executors to use same
    // persistent volume at the same time in the future, the ownership
    // of the persistent volume may conflict here.
    //
    // TODO(haosdent): Consider letting the frameworks specify the
    // user/group of the persistent volumes.
    struct stat s;
    if (::stat(info->directory.c_str(), &s) < 0) {
      return Failure("Failed to get ownership for '" + info->directory + "': " +
                     os::strerror(errno));
    }

    // TODO(hausdorff): (MESOS-5461) Persistent volumes maintain the invariant
    // that they are used by one task at a time. This is currently enforced by
    // `os::chown`. Windows does not support `os::chown`, we will need to
    // revisit this later.
#ifndef __WINDOWS__
    LOG(INFO) << "Changing the ownership of the persistent volume at '"
              << original << "' with uid " << s.st_uid
              << " and gid " << s.st_gid;

    Try<Nothing> chown = os::chown(s.st_uid, s.st_gid, original, false);
    if (chown.isError()) {
      return Failure(
          "Failed to change the ownership of the persistent volume at '" +
          original + "' with uid " + stringify(s.st_uid) +
          " and gid " + stringify(s.st_gid) + ": " + chown.error());
    }
#endif
    string link = path::join(info->directory, containerPath);

    if (os::exists(link)) {
      // NOTE: This is possible because 'info->resources' will be
      // reset when slave restarts and recovers. When the slave calls
      // 'containerizer->update' after the executor re-registers,
      // we'll try to relink all the already symlinked volumes.
      Result<string> realpath = os::realpath(link);
      if (!realpath.isSome()) {
        return Failure(
            "Failed to get the realpath of symlink '" + link + "': " +
            (realpath.isError() ? realpath.error() : "No such directory"));
      }

      // A sanity check to make sure the target of the symlink does
      // not change. In fact, this is not supposed to happen.
      // NOTE: Here, we compare the realpaths because 'original' might
      // contain symbolic links.
      Result<string> _original = os::realpath(original);
      if (!_original.isSome()) {
        return Failure(
            "Failed to get the realpath of volume '" + original + "': " +
            (_original.isError() ? _original.error() : "No such directory"));
      }

      if (realpath.get() != _original.get()) {
        return Failure(
            "The existing symlink '" + link + "' points to '" +
            _original.get() + "' and the new target is '" +
            realpath.get() + "'");
      }
    } else {
      LOG(INFO) << "Adding symlink from '" << original << "' to '"
                << link << "' for persistent volume " << resource
                << " of container " << containerId;

      Try<Nothing> symlink = ::fs::symlink(original, link);
      if (symlink.isError()) {
        return Failure(
            "Failed to symlink persistent volume from '" +
            original + "' to '" + link + "'");
      }
    }
  }

  // Store the updated resources.
  info->resources = resources;

  return Nothing();
}
示例#10
0
文件: framework.cpp 项目: zhuk/mongo
        int Suite::run( int argc , char ** argv ){
            list<string> torun;

            for ( int i=1; i<argc; i++ ){
            
                string s = argv[i];
                
                if ( s == "-list" ){
                    for ( map<string,Suite*>::iterator i=_suites->begin() ; i!=_suites->end(); i++ )
                        cout << i->first << endl;
                    return 0;
                }

                if ( s == "-debug" ){
                    logLevel = 1;
                    continue;
                }
                
                torun.push_back( s );
                if ( _suites->find( s ) == _suites->end() ){
                    cout << "invalid test [" << s << "]  use -list to see valid names" << endl;
                    return -1;
                }
            }
            
            if ( torun.size() == 0 )
                for ( map<string,Suite*>::iterator i=_suites->begin() ; i!=_suites->end(); i++ )
                    torun.push_back( i->first );
            
            list<Result*> results;
            
            for ( list<string>::iterator i=torun.begin(); i!=torun.end(); i++ ){
                string name = *i;
                Suite * s = (*_suites)[name];
                assert( s );
                
                log() << "going to run suite: " << name << endl;
                results.push_back( s->run() );
            }
            
            cout << "**************************************************" << endl;
            cout << "**************************************************" << endl;
            cout << "**************************************************" << endl;
            
            int rc = 0;
            
            int tests = 0;
            int fails = 0;
            int asserts = 0;

            for ( list<Result*>::iterator i=results.begin(); i!=results.end(); i++ ){
                Result * r = *i;
                cout << r->toString();
                if ( abs( r->rc() ) > abs( rc ) )
                    rc = r->rc();

                tests += r->_tests;
                fails += r->_fails;
                asserts += r->_asserts;
            }
            
            cout << "TOTALS  tests:" << tests << " fails: " << fails << " asserts calls: " << asserts << endl;

            return rc;
        }
示例#11
0
// Synchronous reads on any int_fd. Returns -1 on error and
// number of bytes read on success.
inline ssize_t read(const int_fd& fd, void* data, size_t size)
{
  CHECK_LE(size, UINT_MAX);

  switch (fd.type()) {
    case WindowsFD::Type::HANDLE: {
      // Handle non-overlapped case. We just use the regular `ReadFile` since
      // seekable overlapped files require an offset, which we don't track.
      if (!fd.is_overlapped()) {
        DWORD bytes;
        const BOOL result =
          ::ReadFile(fd, data, static_cast<DWORD>(size), &bytes, nullptr);

        if (result == FALSE) {
          // The pipe "breaks" when the other process closes its handle, but we
          // still have the data and therefore do not want to return an error.
          if (::GetLastError() != ERROR_BROKEN_PIPE) {
            // Indicates an error, but we can't return a `WindowsError`.
            return -1;
          }
        }

        return static_cast<ssize_t>(bytes);
      }

      // Asynchronous handle, we can use the `read_async` function
      // and then wait on the overlapped object for a synchronous read.
      Try<OVERLAPPED> overlapped_ =
        ::internal::windows::init_overlapped_for_sync_io();

      if (overlapped_.isError()) {
        return -1;
      }

      OVERLAPPED overlapped = overlapped_.get();
      Result<size_t> result = read_async(fd, data, size, &overlapped);

      if (result.isError()) {
        return -1;
      }

      if (result.isSome()) {
        return result.get();
      }

      // IO is pending, so wait for the overlapped object.
      DWORD bytes;
      const BOOL wait_success =
        ::GetOverlappedResult(fd, &overlapped, &bytes, TRUE);

      if (wait_success == TRUE) {
        return bytes;
      }

      // On failure, there are two EOF cases for reads:
      //   1) ERROR_BROKEN_PIPE: The write end is closed and there is no data.
      //   2) ERROR_HANDLE_EOF: We hit the EOF for an asynchronous file handle.
      const DWORD error = ::GetLastError();
      if (error == ERROR_BROKEN_PIPE || error == ERROR_HANDLE_EOF) {
        return 0;
      }

      return -1;
    }
    case WindowsFD::Type::SOCKET: {
      return ::recv(fd, (char*)data, static_cast<unsigned int>(size), 0);
    }
  }

  UNREACHABLE();
}
void btGjkPairDetector::getClosestPointsNonVirtual(const ClosestPointInput& input,Result& output,class btIDebugDraw* debugDraw)
#endif
{
	m_cachedSeparatingDistance = 0.f;

	btScalar distance=btScalar(0.);
	btVector3	normalInB(btScalar(0.),btScalar(0.),btScalar(0.));
	btVector3 pointOnA,pointOnB;
	btTransform	localTransA = input.m_transformA;
	btTransform localTransB = input.m_transformB;
	btVector3 positionOffset = (localTransA.getOrigin() + localTransB.getOrigin()) * btScalar(0.5);
	localTransA.getOrigin() -= positionOffset;
	localTransB.getOrigin() -= positionOffset;

	bool check2d = m_minkowskiA->isConvex2d() && m_minkowskiB->isConvex2d();

	btScalar marginA = m_marginA;
	btScalar marginB = m_marginB;

	gNumGjkChecks++;

#ifdef DEBUG_SPU_COLLISION_DETECTION
	spu_printf("inside gjk\n");
#endif
	//for CCD we don't use margins
	if (m_ignoreMargin)
	{
		marginA = btScalar(0.);
		marginB = btScalar(0.);
#ifdef DEBUG_SPU_COLLISION_DETECTION
		spu_printf("ignoring margin\n");
#endif
	}

	m_curIter = 0;
	int gGjkMaxIter = 1000;//this is to catch invalid input, perhaps check for #NaN?
	m_cachedSeparatingAxis.setValue(0,1,0);

	bool isValid = false;
	bool checkSimplex = false;
	bool checkPenetration = true;
	m_degenerateSimplex = 0;

	m_lastUsedMethod = -1;

	{
		btScalar squaredDistance = BT_LARGE_FLOAT;
		btScalar delta = btScalar(0.);
		
		btScalar margin = marginA + marginB;
		
		

		m_simplexSolver->reset();
		
		for ( ; ; )
		//while (true)
		{

			btVector3 seperatingAxisInA = (-m_cachedSeparatingAxis)* input.m_transformA.getBasis();
			btVector3 seperatingAxisInB = m_cachedSeparatingAxis* input.m_transformB.getBasis();

#if 1

			btVector3 pInA = m_minkowskiA->localGetSupportVertexWithoutMarginNonVirtual(seperatingAxisInA);
			btVector3 qInB = m_minkowskiB->localGetSupportVertexWithoutMarginNonVirtual(seperatingAxisInB);

//			btVector3 pInA  = localGetSupportingVertexWithoutMargin(m_shapeTypeA, m_minkowskiA, seperatingAxisInA,input.m_convexVertexData[0]);//, &featureIndexA);
//			btVector3 qInB  = localGetSupportingVertexWithoutMargin(m_shapeTypeB, m_minkowskiB, seperatingAxisInB,input.m_convexVertexData[1]);//, &featureIndexB);

#else
#ifdef __SPU__
			btVector3 pInA = m_minkowskiA->localGetSupportVertexWithoutMarginNonVirtual(seperatingAxisInA);
			btVector3 qInB = m_minkowskiB->localGetSupportVertexWithoutMarginNonVirtual(seperatingAxisInB);
#else
			btVector3 pInA = m_minkowskiA->localGetSupportingVertexWithoutMargin(seperatingAxisInA);
			btVector3 qInB = m_minkowskiB->localGetSupportingVertexWithoutMargin(seperatingAxisInB);
#ifdef TEST_NON_VIRTUAL
			btVector3 pInAv = m_minkowskiA->localGetSupportingVertexWithoutMargin(seperatingAxisInA);
			btVector3 qInBv = m_minkowskiB->localGetSupportingVertexWithoutMargin(seperatingAxisInB);
			btAssert((pInAv-pInA).length() < 0.0001);
			btAssert((qInBv-qInB).length() < 0.0001);
#endif //
#endif //__SPU__
#endif


			btVector3  pWorld = localTransA(pInA);	
			btVector3  qWorld = localTransB(qInB);

#ifdef DEBUG_SPU_COLLISION_DETECTION
		spu_printf("got local supporting vertices\n");
#endif

			if (check2d)
			{
				pWorld[2] = 0.f;
				qWorld[2] = 0.f;
			}

			btVector3 w	= pWorld - qWorld;
			delta = m_cachedSeparatingAxis.dot(w);

			// potential exit, they don't overlap
			if ((delta > btScalar(0.0)) && (delta * delta > squaredDistance * input.m_maximumDistanceSquared)) 
			{
				m_degenerateSimplex = 10;
				checkSimplex=true;
				//checkPenetration = false;
				break;
			}

			//exit 0: the new point is already in the simplex, or we didn't come any closer
			if (m_simplexSolver->inSimplex(w))
			{
				m_degenerateSimplex = 1;
				checkSimplex = true;
				break;
			}
			// are we getting any closer ?
			btScalar f0 = squaredDistance - delta;
			btScalar f1 = squaredDistance * REL_ERROR2;

			if (f0 <= f1)
			{
				if (f0 <= btScalar(0.))
				{
					m_degenerateSimplex = 2;
				} else
				{
					m_degenerateSimplex = 11;
				}
				checkSimplex = true;
				break;
			}

#ifdef DEBUG_SPU_COLLISION_DETECTION
		spu_printf("addVertex 1\n");
#endif
			//add current vertex to simplex
			m_simplexSolver->addVertex(w, pWorld, qWorld);
#ifdef DEBUG_SPU_COLLISION_DETECTION
		spu_printf("addVertex 2\n");
#endif
			btVector3 newCachedSeparatingAxis;

			//calculate the closest point to the origin (update vector v)
			if (!m_simplexSolver->closest(newCachedSeparatingAxis))
			{
				m_degenerateSimplex = 3;
				checkSimplex = true;
				break;
			}

			if(newCachedSeparatingAxis.length2()<REL_ERROR2)
            {
				m_cachedSeparatingAxis = newCachedSeparatingAxis;
                m_degenerateSimplex = 6;
                checkSimplex = true;
                break;
            }

			btScalar previousSquaredDistance = squaredDistance;
			squaredDistance = newCachedSeparatingAxis.length2();
#if 0
///warning: this termination condition leads to some problems in 2d test case see Bullet/Demos/Box2dDemo
			if (squaredDistance>previousSquaredDistance)
			{
				m_degenerateSimplex = 7;
				squaredDistance = previousSquaredDistance;
                checkSimplex = false;
                break;
			}
#endif //
			

			//redundant m_simplexSolver->compute_points(pointOnA, pointOnB);

			//are we getting any closer ?
			if (previousSquaredDistance - squaredDistance <= SIMD_EPSILON * previousSquaredDistance) 
			{ 
//				m_simplexSolver->backup_closest(m_cachedSeparatingAxis);
				checkSimplex = true;
				m_degenerateSimplex = 12;
				
				break;
			}

			m_cachedSeparatingAxis = newCachedSeparatingAxis;

			  //degeneracy, this is typically due to invalid/uninitialized worldtransforms for a btCollisionObject   
              if (m_curIter++ > gGjkMaxIter)   
              {   
                      #if defined(DEBUG) || defined (_DEBUG) || defined (DEBUG_SPU_COLLISION_DETECTION)

                              printf("btGjkPairDetector maxIter exceeded:%i\n",m_curIter);   
                              printf("sepAxis=(%f,%f,%f), squaredDistance = %f, shapeTypeA=%i,shapeTypeB=%i\n",   
                              m_cachedSeparatingAxis.getX(),   
                              m_cachedSeparatingAxis.getY(),   
                              m_cachedSeparatingAxis.getZ(),   
                              squaredDistance,   
                              m_minkowskiA->getShapeType(),   
                              m_minkowskiB->getShapeType());   

                      #endif   
                      break;   

              } 


			bool check = (!m_simplexSolver->fullSimplex());
			//bool check = (!m_simplexSolver->fullSimplex() && squaredDistance > SIMD_EPSILON * m_simplexSolver->maxVertex());

			if (!check)
			{
				//do we need this backup_closest here ?
//				m_simplexSolver->backup_closest(m_cachedSeparatingAxis);
				m_degenerateSimplex = 13;
				break;
			}
		}

		if (checkSimplex)
		{
			m_simplexSolver->compute_points(pointOnA, pointOnB);
			normalInB = m_cachedSeparatingAxis;
			btScalar lenSqr =m_cachedSeparatingAxis.length2();
			
			//valid normal
			if (lenSqr < 0.0001)
			{
				m_degenerateSimplex = 5;
			} 
			if (lenSqr > SIMD_EPSILON*SIMD_EPSILON)
			{
				btScalar rlen = btScalar(1.) / btSqrt(lenSqr );
				normalInB *= rlen; //normalize
				btScalar s = btSqrt(squaredDistance);
			
				btAssert(s > btScalar(0.0));
				pointOnA -= m_cachedSeparatingAxis * (marginA / s);
				pointOnB += m_cachedSeparatingAxis * (marginB / s);
				distance = ((btScalar(1.)/rlen) - margin);
				isValid = true;
				
				m_lastUsedMethod = 1;
			} else
			{
				m_lastUsedMethod = 2;
			}
		}

		bool catchDegeneratePenetrationCase = 
			(m_catchDegeneracies && m_penetrationDepthSolver && m_degenerateSimplex && ((distance+margin) < 0.01));

		//if (checkPenetration && !isValid)
		if (checkPenetration && (!isValid || catchDegeneratePenetrationCase ))
		{
			//penetration case

			//if there is no way to handle penetrations, bail out
			if (m_penetrationDepthSolver)
			{
				// Penetration depth case.
				btVector3 tmpPointOnA,tmpPointOnB;
				
				gNumDeepPenetrationChecks++;
				m_cachedSeparatingAxis.setZero();

				bool isValid2 = m_penetrationDepthSolver->calcPenDepth( 
					*m_simplexSolver, 
					m_minkowskiA,m_minkowskiB,
					localTransA,localTransB,
					m_cachedSeparatingAxis, tmpPointOnA, tmpPointOnB,
					debugDraw
					);


				if (isValid2)
				{
					btVector3 tmpNormalInB = tmpPointOnB-tmpPointOnA;
					btScalar lenSqr = tmpNormalInB.length2();
					if (lenSqr <= (SIMD_EPSILON*SIMD_EPSILON))
					{
						tmpNormalInB = m_cachedSeparatingAxis;
						lenSqr = m_cachedSeparatingAxis.length2();
					}

					if (lenSqr > (SIMD_EPSILON*SIMD_EPSILON))
					{
						tmpNormalInB /= btSqrt(lenSqr);
						btScalar distance2 = -(tmpPointOnA-tmpPointOnB).length();
						//only replace valid penetrations when the result is deeper (check)
						if (!isValid || (distance2 < distance))
						{
							distance = distance2;
							pointOnA = tmpPointOnA;
							pointOnB = tmpPointOnB;
							normalInB = tmpNormalInB;
							isValid = true;
							m_lastUsedMethod = 3;
						} else
						{
							m_lastUsedMethod = 8;
						}
					} else
					{
						m_lastUsedMethod = 9;
					}
				} else

				{
					///this is another degenerate case, where the initial GJK calculation reports a degenerate case
					///EPA reports no penetration, and the second GJK (using the supporting vector without margin)
					///reports a valid positive distance. Use the results of the second GJK instead of failing.
					///thanks to Jacob.Langford for the reproduction case
					///http://code.google.com/p/bullet/issues/detail?id=250

				
					if (m_cachedSeparatingAxis.length2() > btScalar(0.))
					{
						btScalar distance2 = (tmpPointOnA-tmpPointOnB).length()-margin;
						//only replace valid distances when the distance is less
						if (!isValid || (distance2 < distance))
						{
							distance = distance2;
							pointOnA = tmpPointOnA;
							pointOnB = tmpPointOnB;
							pointOnA -= m_cachedSeparatingAxis * marginA ;
							pointOnB += m_cachedSeparatingAxis * marginB ;
							normalInB = m_cachedSeparatingAxis;
							normalInB.normalize();
							isValid = true;
							m_lastUsedMethod = 6;
						} else
						{
							m_lastUsedMethod = 5;
						}
					}
				}
				
			}

		}
	}

	

	if (isValid && ((distance < 0) || (distance*distance < input.m_maximumDistanceSquared)))
	{
#if 0
///some debugging
//		if (check2d)
		{
			printf("n = %2.3f,%2.3f,%2.3f. ",normalInB[0],normalInB[1],normalInB[2]);
			printf("distance = %2.3f exit=%d deg=%d\n",distance,m_lastUsedMethod,m_degenerateSimplex);
		}
#endif 

		if (m_fixContactNormalDirection)
		{
			///@workaround for sticky convex collisions
			//in some degenerate cases (usually when the use uses very small margins) 
			//the contact normal is pointing the wrong direction
			//so fix it now (until we can deal with all degenerate cases in GJK and EPA)
			//contact normals need to point from B to A in all cases, so we can simply check if the contact normal really points from B to A
			//We like to use a dot product of the normal against the difference of the centroids, 
			//once the centroid is available in the API
			//until then we use the center of the aabb to approximate the centroid
			btVector3 aabbMin,aabbMax;
			m_minkowskiA->getAabb(localTransA,aabbMin,aabbMax);
			btVector3 posA  = (aabbMax+aabbMin)*btScalar(0.5);
		
			m_minkowskiB->getAabb(localTransB,aabbMin,aabbMax);
			btVector3 posB = (aabbMin+aabbMax)*btScalar(0.5);

			btVector3 diff = posA-posB;
			if (diff.dot(normalInB) < 0.f)
				normalInB *= -1.f;
		}
		m_cachedSeparatingAxis = normalInB;
		m_cachedSeparatingDistance = distance;

		output.addContactPoint(
			normalInB,
			pointOnB+positionOffset,
			distance);

	}


}
示例#13
0
文件: Result.cpp 项目: KDE/predicate
QDebug operator<<(QDebug dbg, const Result& result)
{
    if (result.isError()) {
        dbg.nospace() << "Predicate::Result:";
        dbg.space() << "CODE=" << result.code();
        if (!result.message().isEmpty())
            dbg.space() << "MESSAGE=" << result.message();
        if (!result.messageTitle().isEmpty())
            dbg.space() << "TITLE=" << result.messageTitle();
        if (!result.sql().isEmpty())
            dbg.space() << "SQL=" << result.sql();
        if (!result.errorSql().isEmpty())
            dbg.space() << "ERR_SQL=" << result.errorSql();
        dbg.space() << "SERVER_RESULT=(CODE:" << result.serverResultCode() /*<< "NAME:" << result.serverResultName()*/ << ")";
        if (!result.serverMessage().isEmpty())
            dbg.nospace() << "MESSAGE:" << result.serverMessage();
        /*dbg.space() << "PREV_SERVER_RESULT=(CODE:" << result.previousServerResultCode() << "NAME:" <<
             result.previousServerResultName() << ")";*/
    } else {
        dbg.nospace() << "Predicate::Result: OK";
    }
    return dbg.space();
}
示例#14
0
Try<Manifest> Manifest::create(const string& jsonString)
{
    Try<JSON::Object> manifestJSON = JSON::parse<JSON::Object>(jsonString);

    if (manifestJSON.isError()) {
      return Error(manifestJSON.error());
    }

    Result<JSON::String> name = manifestJSON.get().find<JSON::String>("name");
    if (name.isNone()) {
      return Error("Failed to find \"name\" in manifest response");
    }

    Result<JSON::Array> fsLayersJSON =
      manifestJSON.get().find<JSON::Array>("fsLayers");

    if (fsLayersJSON.isNone()) {
      return Error("Failed to find \"fsLayers\" in manifest response");
    }

    Result<JSON::Array> historyArray =
      manifestJSON.get().find<JSON::Array>("history");

    if (historyArray.isNone()) {
      return Error("Failed to find \"history\" in manifest response");
    }

    if (historyArray.get().values.size() != fsLayersJSON.get().values.size()) {
      return Error(
          "\"history\" and \"fsLayers\" array count mismatch"
          "in manifest response");
    }

    vector<FileSystemLayerInfo> fsLayers;

    // We add layers in reverse order because 'fsLayers' in the manifest
    // response is ordered with the latest layer on the top. When we apply the
    // layer changes, we want the filesystem modification order to be the same
    // as its history(oldest layer applied first).
    for (size_t index = fsLayersJSON.get().values.size(); index-- > 0; ) {
      const JSON::Value& layer = fsLayersJSON.get().values[index];

      if (!layer.is<JSON::Object>()) {
        return Error(
            "Failed to parse layer as a JSON object for index: " +
            stringify(index));
      }

      const JSON::Object& layerInfoJSON = layer.as<JSON::Object>();

      // Get blobsum for layer.
      const Result<JSON::String> blobSumInfo =
        layerInfoJSON.find<JSON::String>("blobSum");

      if (blobSumInfo.isNone()) {
        return Error("Failed to find \"blobSum\" in manifest response");
      }

      // Get history for layer.
      if (!historyArray.get().values[index].is<JSON::Object>()) {
        return Error(
            "Failed to parse history as a JSON object for index: " +
            stringify(index));
      }
      const JSON::Object& historyObj =
        historyArray.get().values[index].as<JSON::Object>();

      // Get layer id.
      const Result<JSON::String> v1CompatibilityJSON =
        historyObj.find<JSON::String>("v1Compatibility");

      if (!v1CompatibilityJSON.isSome()) {
        return Error(
            "Failed to obtain layer v1 compability json in manifest for layer: "
            + stringify(index));
      }

      Try<JSON::Object> v1CompatibilityObj =
        JSON::parse<JSON::Object>(v1CompatibilityJSON.get().value);

      if (!v1CompatibilityObj.isSome()) {
        return Error(
            "Failed to parse v1 compability json in manifest for layer: "
            + stringify(index));
      }

      const Result<JSON::String> id =
        v1CompatibilityObj.get().find<JSON::String>("id");

      if (!id.isSome()) {
        return Error(
            "Failed to find \"id\" in manifest for layer: " + stringify(index));
      }

      fsLayers.emplace_back(
          FileSystemLayerInfo{
            blobSumInfo.get().value,
            id.get().value,
          });
    }

    return Manifest{name.get().value, fsLayers};
}
void CGQuitUnionAcceptHandler::execute (CGQuitUnionAccept* pPacket , Player* pPlayer)
	 throw(Error)
{
	__BEGIN_TRY __BEGIN_DEBUG_EX
		
#ifdef __GAME_SERVER__

	Assert(pPacket != NULL);
	Assert(pPlayer != NULL);

    GamePlayer* pGamePlayer = dynamic_cast<GamePlayer*>(pPlayer);
    Assert(pGamePlayer != NULL);

    PlayerCreature* pPlayerCreature = dynamic_cast<PlayerCreature*>(pGamePlayer->getCreature());
    Assert(pPlayerCreature != NULL);

#ifdef __OLD_GUILD_WAR__
	GCSystemMessage gcSM;
	gcSM.setMessage("아직 지원되지 않는 기능입니다.");
	pGamePlayer->sendPacket(&gcSM);
	return;
#endif

	SYSTEM_ASSERT(SYSTEM_GUILD);

	GCGuildResponse gcGuildResponse;

	GuildUnion *pUnion = GuildUnionManager::Instance().getGuildUnion(pPlayerCreature->getGuildID());
	if(pUnion == NULL)
	{
		gcGuildResponse.setCode(GuildUnionOfferManager::NOT_IN_UNION);
		pPlayer->sendPacket(&gcGuildResponse);

		return;
	}
	
	// 요청한놈이 지가 속한 길드의 마스터인가? || 연합의 마스터길드가 내 길드가 맞나?
	if(!g_pGuildManager->isGuildMaster (pPlayerCreature->getGuildID(), pPlayerCreature )
		|| pUnion->getMasterGuildID() != pPlayerCreature->getGuildID() 		
		)
	{
		// GC_GUILD_RESPONSE 날려준다.
		// 내용 : 길드 마스터가 아니자녀 -.-+

		gcGuildResponse.setCode(GuildUnionOfferManager::SOURCE_IS_NOT_MASTER);
		pPlayer->sendPacket(&gcGuildResponse);

		return;
	}

	uint result = GuildUnionOfferManager::Instance().acceptQuit(pPacket->getGuildID());

	gcGuildResponse.setCode(result);
	pPlayer->sendPacket(&gcGuildResponse);
////////////////////

	if(result == GuildUnionOfferManager::OK)
	{
	
		Guild*  pGuild  = g_pGuildManager->getGuild(pPacket->getGuildID());

		if(pGuild == NULL)
		{
			return;
		}
		string  TargetGuildMaster = pGuild->getMaster();

		//cout << "연합탈퇴가 수락되었다. 통보받을 유저는 : " << TargetGuildMaster.c_str() << endl;


		Statement* pStmt = NULL;

		BEGIN_DB
		{
			pStmt = g_pDatabaseManager->getConnection("DARKEDEN" )->createStatement();
			pStmt->executeQuery("INSERT INTO Messages (Receiver, Message) values('%s','%s')", TargetGuildMaster.c_str(),  g_pStringPool->c_str(375 ));

			// 탈퇴수락한뒤에 나 혼자 남아있다면?
			Result *pResult = pStmt->executeQuery("SELECT count(*) FROM GuildUnionMember WHERE UnionID='%u'", pUnion->getUnionID());
			pResult->next();

			if(pResult->getInt(1) == 0)
			{
				//cout << "연합탈퇴가 수락된후..남아있는 멤버가 없으면..연합장이면 안되니까..지워버린다" << endl;
				pStmt->executeQuery("DELETE FROM GuildUnionInfo WHERE UnionID='%u'", pUnion->getUnionID());
				GuildUnionManager::Instance().reload();

			}
		
			
			SAFE_DELETE(pStmt);
		}
		END_DB(pStmt)
		
		// 연합탈퇴하면 연합정보가 바뀌었을 수도 있다. 갱신된 정보를 다시 보내준다.
		Creature *pCreature = NULL;
		pCreature = pGamePlayer->getCreature();

		if(pCreature == NULL)   return;

		GCModifyInformation gcModifyInformation;
		makeGCModifyInfoGuildUnion(&gcModifyInformation, pCreature);

		pPlayer->sendPacket(&gcModifyInformation);

		// 통보받을 유저에게 길드Union정보를 다시 보낸다
		Creature *pTargetCreature = NULL;
		__ENTER_CRITICAL_SECTION((*g_pPCFinder))

	    pTargetCreature = g_pPCFinder->getCreature_LOCKED(TargetGuildMaster);
    	if (pTargetCreature==NULL)
	    {
    	    g_pPCFinder->unlock();
        	return;
	    }
		GCModifyInformation gcModifyInformation;
        makeGCModifyInfoGuildUnion(&gcModifyInformation, pTargetCreature);
        pTargetCreature->getPlayer()->sendPacket(&gcModifyInformation);

		__LEAVE_CRITICAL_SECTION((*g_pPCFinder))
	
		sendGCOtherModifyInfoGuildUnion(pTargetCreature);
		sendGCOtherModifyInfoGuildUnion(pCreature);

		// 다른 서버에 있는 놈들에게 변경사항을 알린다.
        GuildUnionManager::Instance().sendModifyUnionInfo(dynamic_cast<PlayerCreature*>(pTargetCreature)->getGuildID());
        GuildUnionManager::Instance().sendModifyUnionInfo(dynamic_cast<PlayerCreature*>(pCreature)->getGuildID());
				
			
	}
示例#16
0
// Generate a `Process` object for the process associated with `pid`. If
// process is not found, we return `None`; error is reserved for the case where
// something went wrong.
inline Result<Process> process(pid_t pid)
{
  // Find process with pid.
  Result<PROCESSENTRY32> entry = process_entry(pid);

  if (entry.isError()) {
    return WindowsError(entry.error());
  } else if (entry.isNone()) {
    return None();
  }

  HANDLE process_handle = ::OpenProcess(
      PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_VM_READ,
      false,
      pid);

  if (process_handle == INVALID_HANDLE_VALUE) {
    return WindowsError("os::process: Call to `OpenProcess` failed");
  }

  SharedHandle safe_process_handle(process_handle, ::CloseHandle);

  // Get Windows Working set size (Resident set size in linux).
  PROCESS_MEMORY_COUNTERS proc_mem_counters;
  BOOL get_process_memory_info = ::GetProcessMemoryInfo(
      safe_process_handle.get(),
      &proc_mem_counters,
      sizeof(proc_mem_counters));

  if (!get_process_memory_info) {
    return WindowsError("os::process: Call to `GetProcessMemoryInfo` failed");
  }

  // Get session Id.
  pid_t session_id;
  BOOL process_id_to_session_id = ::ProcessIdToSessionId(pid, &session_id);

  if (!process_id_to_session_id) {
    return WindowsError("os::process: Call to `ProcessIdToSessionId` failed");
  }

  // Get Process CPU time.
  FILETIME create_filetime, exit_filetime, kernel_filetime, user_filetime;
  BOOL get_process_times = ::GetProcessTimes(
      safe_process_handle.get(),
      &create_filetime,
      &exit_filetime,
      &kernel_filetime,
      &user_filetime);

  if (!get_process_times) {
    return WindowsError("os::process: Call to `GetProcessTimes` failed");
  }

  // Get utime and stime.
  ULARGE_INTEGER lKernelTime, lUserTime; // In 100 nanoseconds.
  lKernelTime.HighPart = kernel_filetime.dwHighDateTime;
  lKernelTime.LowPart = kernel_filetime.dwLowDateTime;
  lUserTime.HighPart = user_filetime.dwHighDateTime;
  lUserTime.LowPart = user_filetime.dwLowDateTime;

  Try<Duration> utime = Nanoseconds(lKernelTime.QuadPart * 100);
  Try<Duration> stime = Nanoseconds(lUserTime.QuadPart * 100);

  return Process(
      pid,
      entry.get().th32ParentProcessID,         // Parent process id.
      0,                                       // Group id.
      session_id,
      Bytes(proc_mem_counters.WorkingSetSize),
      utime.isSome() ? utime.get() : Option<Duration>::none(),
      stime.isSome() ? stime.get() : Option<Duration>::none(),
      entry.get().szExeFile,                   // Executable filename.
      false);                                  // Is not zombie process.
}
示例#17
0
bool exists()
{
  // This is static as the init system should not change while we are running.
  static const bool exists = []() -> bool {
    // (1) Test whether `/sbin/init` links to systemd.
    const Result<string> realpath = os::realpath("/sbin/init");
    if (realpath.isError() || realpath.isNone()) {
      LOG(WARNING) << "Failed to test /sbin/init for systemd environment: "
                   << realpath.error();

      return false;
    }

    CHECK_SOME(realpath);

    // (2) Testing whether we have a systemd version.
    const string command = realpath.get() + " --version";
    Try<string> versionCommand = os::shell(command);

    if (versionCommand.isError()) {
      LOG(WARNING) << "Failed to test command '" << command << "': "
                   << versionCommand.error();

      return false;
    }

    vector<string> tokens = strings::tokenize(versionCommand.get(), " \n");

    // We need at least a name and a version number to match systemd.
    if (tokens.size() < 2) {
      return false;
    }

    if (tokens[0] != "systemd") {
      return false;
    }

    Try<int> version = numify<int>(tokens[1]);
    if (version.isError()) {
      LOG(WARNING) << "Failed to parse systemd version '" << tokens[1] << "'";
      return false;
    }

    LOG(INFO) << "systemd version `" << version.get() << "` detected";

    // We log a warning if the version is below 218. This is because the
    // `Delegate` flag was introduced in version 218. Some systems, like RHEL 7,
    // have patched versions that are below 218 but still have the `Delegate`
    // flag. This is why we warn / inform users rather than failing. See
    // MESOS-3352.
    if (version.get() < DELEGATE_MINIMUM_VERSION) {
      LOG(WARNING)
        << "Required functionality `Delegate` was introduced in Version `"
        << DELEGATE_MINIMUM_VERSION << "`. Your system may not function"
        << " properly; however since some distributions have patched systemd"
        << " packages, your system may still be functional. This is why we keep"
        << " running. See MESOS-3352 for more information";
    }

    return true;
  }();

  return exists;
}
示例#18
0
文件: docker.cpp 项目: haosdent/mesos
// TODO(josephw): Parse this string with a protobuf.
Try<Docker::Container> Docker::Container::create(const string& output)
{
  Try<JSON::Array> parse = JSON::parse<JSON::Array>(output);
  if (parse.isError()) {
    return Error("Failed to parse JSON: " + parse.error());
  }

  // TODO(benh): Handle the case where the short container ID was
  // not sufficiently unique and 'array.values.size() > 1'.
  JSON::Array array = parse.get();
  if (array.values.size() != 1) {
    return Error("Failed to find container");
  }

  CHECK(array.values.front().is<JSON::Object>());

  JSON::Object json = array.values.front().as<JSON::Object>();

  Result<JSON::String> idValue = json.find<JSON::String>("Id");
  if (idValue.isNone()) {
    return Error("Unable to find Id in container");
  } else if (idValue.isError()) {
    return Error("Error finding Id in container: " + idValue.error());
  }

  string id = idValue.get().value;

  Result<JSON::String> nameValue = json.find<JSON::String>("Name");
  if (nameValue.isNone()) {
    return Error("Unable to find Name in container");
  } else if (nameValue.isError()) {
    return Error("Error finding Name in container: " + nameValue.error());
  }

  string name = nameValue.get().value;

  Result<JSON::Object> stateValue = json.find<JSON::Object>("State");
  if (stateValue.isNone()) {
    return Error("Unable to find State in container");
  } else if (stateValue.isError()) {
    return Error("Error finding State in container: " + stateValue.error());
  }

  Result<JSON::Number> pidValue = stateValue.get().find<JSON::Number>("Pid");
  if (pidValue.isNone()) {
    return Error("Unable to find Pid in State");
  } else if (pidValue.isError()) {
    return Error("Error finding Pid in State: " + pidValue.error());
  }

  pid_t pid = pid_t(pidValue.get().as<int64_t>());

  Option<pid_t> optionalPid;
  if (pid != 0) {
    optionalPid = pid;
  }

  Result<JSON::String> startedAtValue =
    stateValue.get().find<JSON::String>("StartedAt");
  if (startedAtValue.isNone()) {
    return Error("Unable to find StartedAt in State");
  } else if (startedAtValue.isError()) {
    return Error("Error finding StartedAt in State: " + startedAtValue.error());
  }

  bool started = startedAtValue.get().value != "0001-01-01T00:00:00Z";

  Option<string> ipAddress;
  bool findDeprecatedIP = false;
  Result<JSON::String> networkMode =
    json.find<JSON::String>("HostConfig.NetworkMode");
  if (!networkMode.isSome()) {
    // We need to fail back to the old field as Docker added NetworkMode
    // since Docker remote API 1.15.
    VLOG(1) << "Unable to detect HostConfig.NetworkMode, "
            << "attempting deprecated IP field";
    findDeprecatedIP = true;
  } else {
    // We currently rely on the fact that we always set --net when
    // we shell out to docker run, and therefore the network mode
    // matches what --net is. Without --net, the network mode would be set
    // to 'default' and we won't be able to find the IP address as
    // it will be in 'Networks.bridge' key.
    string addressLocation = "NetworkSettings.Networks." +
                             networkMode->value + ".IPAddress";

    Result<JSON::String> ipAddressValue =
      json.find<JSON::String>(addressLocation);

    if (!ipAddressValue.isSome()) {
      // We also need to failback to the old field as the IP Address
      // field location also changed since Docker remote API 1.20.
      VLOG(1) << "Unable to detect IP Address at '" << addressLocation << "',"
              << " attempting deprecated field";
      findDeprecatedIP = true;
    } else if (!ipAddressValue->value.empty()) {
      ipAddress = ipAddressValue->value;
    }
  }

  if (findDeprecatedIP) {
    Result<JSON::String> ipAddressValue =
      json.find<JSON::String>("NetworkSettings.IPAddress");

    if (ipAddressValue.isNone()) {
      return Error("Unable to find NetworkSettings.IPAddress in container");
    } else if (ipAddressValue.isError()) {
      return Error(
        "Error finding NetworkSettings.IPAddress in container: " +
        ipAddressValue.error());
    } else if (!ipAddressValue->value.empty()) {
      ipAddress = ipAddressValue->value;
    }
  }

  vector<Device> devices;

  Result<JSON::Array> devicesArray =
    json.find<JSON::Array>("HostConfig.Devices");

  if (devicesArray.isError()) {
    return Error("Failed to parse HostConfig.Devices: " + devicesArray.error());
  }

  if (devicesArray.isSome()) {
    foreach (const JSON::Value& entry, devicesArray->values) {
      if (!entry.is<JSON::Object>()) {
        return Error("Malformed HostConfig.Devices"
                     " entry '" + stringify(entry) + "'");
      }

      JSON::Object object = entry.as<JSON::Object>();

      Result<JSON::String> hostPath =
        object.at<JSON::String>("PathOnHost");
      Result<JSON::String> containerPath =
        object.at<JSON::String>("PathInContainer");
      Result<JSON::String> permissions =
        object.at<JSON::String>("CgroupPermissions");

      if (!hostPath.isSome() ||
          !containerPath.isSome() ||
          !permissions.isSome()) {
        return Error("Malformed HostConfig.Devices entry"
                     " '" + stringify(object) + "'");
      }

      Device device;
      device.hostPath = Path(hostPath->value);
      device.containerPath = Path(containerPath->value);
      device.access.read = strings::contains(permissions->value, "r");
      device.access.write = strings::contains(permissions->value, "w");
      device.access.mknod = strings::contains(permissions->value, "m");

      devices.push_back(device);
    }
  }
示例#19
0
bool ActionRedeemMotorcycle::load(Item* pItem, Slayer* pSlayer, Zone* pZone, ZoneCoord_t x, ZoneCoord_t y) const
	throw()
{
	bool bFound = false;

	__BEGIN_TRY

	// 단서가 되는 아이템이 키가 아니라면 false를 리턴.
	if (pItem->getItemClass() != Item::ITEM_CLASS_KEY) return false;

	Key* pKey = dynamic_cast<Key*>(pItem);
	ItemID_t   targetID = pKey->getTarget();

	try {

	// 키가 맞다면 키의 타겟이 되는 아이템의 아이템 ID를 얻어낸다.
	Statement* pStmt    = NULL;
	Result*    pResult  = NULL;

	// targetID가 0인 경우는.. targetID(motorcycleObject의 ItemID)가 설정이 안된 경우다.
	// 이 때는 임시로 targetID를 key의 ItemID와 같게 하면 된다...고 본다.
	// targetID가 motorcycle의 itemID로 들어가기 때문에..
	// broadcasting 등에서.. Assert()에 의해서 다운되었다...고 보여진다.  - -;
	// by sigi. 2002.12.25 x-mas T_T;
	if (targetID==0)
	{
		targetID = pKey->setNewMotorcycle(pSlayer);
/*		// (!) MotorcycleObject를 생성하고 MotorcycleItemID==Target를 받아야 한다.
		// 이 코드 제발 함수로 빼기를.. -_-; by sigi
		list<OptionType_t> optionNULL;
		Item* pMotorcycle = g_pItemFactoryManager->createItem(Item::ITEM_CLASS_MOTORCYCLE, 0, optionNULL);
		Assert(pMotorcycle != NULL);
		(pZone->getObjectRegistry()).registerObject(pMotorcycle);

		pMotorcycle->create(pSlayer->getName(), STORAGE_ZONE, pZone->getZoneID(), pSlayer->getX(), pSlayer->getY());
		pKey->setTarget(pMotorcycle->getItemID());

		targetID = pMotorcycle->getItemID();

		// targetID를 DB에도 update시켜야 한다.
		BEGIN_DB
		{
			pStmt   = g_pDatabaseManager->getConnection("DARKEDEN")->createStatement();
			pResult = pStmt->executeQuery(
						"UPDATE KeyObject SET Target=%d WHERE ItemID=%d", 
									targetID, pKey->getItemID());

			SAFE_DELETE(pStmt);
		}
		END_DB(pStmt)

		// 밑에서 pMotorcycle을 사용해도 되겠지만, 기존 코드 안 건드릴려고 여기서 지운다. 
		SAFE_DELETE(pMotorcycle);*/
	}
	else
	{
		// 한번 모터사이클이랑 키랑 연결됐는데 모터사이클을 누가 자꾸 지우나보다.
		// 키에 연결된 모터사이클이 실제로 디비에 있는지 체크하고 없으면 새로 만들어서 넣어준다.
		BEGIN_DB
		{
			pStmt = g_pDatabaseManager->getConnection("DARKEDEN")->createStatement();
			pResult = pStmt->executeQuery("SELECT ItemID FROM MotorcycleObject WHERE ItemID=%lu", targetID);

			if (!pResult->next() )
			{
				Key* pKey = dynamic_cast<Key*>(pItem);
				Assert(pKey != NULL);

				targetID = pKey->setNewMotorcycle(pSlayer);
			}

			SAFE_DELETE(pStmt);
		}
		END_DB(pStmt);
	}

	
	// 필살 방어 코드 -_-;
	if (targetID==0)
	{
		filelog("errorLog.txt", "[ActionRedeemMotorcycle] itemID=%d, motorItemID=%d", (int)pItem->getItemID(), (int)targetID);
		return false;
	}

	// DB에 쿼리하기 전에 먼저 객체가 생성되어 있지는 않은지 체크한다.
	if (g_pParkingCenter->hasMotorcycleBox(targetID)) 
	{
		// 자꾸 다운되어서 혹시나 하고..
		// 일단 주석처리한다.  by sigi. 2002.11.16
		/*
		if (!pSlayer->hasRideMotorcycle()
			&& !pSlayer->isFlag(Effect::EFFECT_CLASS_COMA))
		{
			//return false;

			// by sigi. 2002.11.14
			MotorcycleBox* pMotorcycleBox = g_pParkingCenter->getMotorcycleBox(targetID);

			// 있다면 소환한다.
			if (pMotorcycleBox!=NULL
				&& !pMotorcycleBox->isTransport())
			{
				Zone* pMotorZone = pMotorcycleBox->getZone();
				ZoneCoord_t motorX = pMotorcycleBox->getX();
				ZoneCoord_t motorY = pMotorcycleBox->getY();
				Motorcycle* pMotorcycle = pMotorcycleBox->getMotorcycle();

				// 같은 존에 있는 경우
				// 거리가 너무 가까우면 부르지 말자~
				if (pMotorZone!=pZone
					|| pSlayer->getDistance(motorX, motorY) > 15)
				{
					// 다른 zone으로 이동중이라고 표시한다.
					pMotorcycleBox->setTransport();

					// motorcycle을 slayer의 zone으로 옮긴다.
					pMotorZone->transportItem(motorX, motorY, pMotorcycle, 
												pZone, pSlayer->getX(), pSlayer->getY());

					// Use OK 대용이다.
					// Use하면 아이템이 사라지던가 그렇지 싶다. - -;
					//GCCannotUse _GCCannotUse;
					//_GCCannotUse.setObjectID(pPacket->getObjectID());
					//pGamePlayer->sendPacket(&_GCCannotUse);

					// 한동안 delay를 줘야하는데..
				}
			}

			return true;
		}
		*/

		return false;
	}

	ItemID_t     itemID;
	ItemType_t   itemType;
	string 		 optionType;
	Durability_t durability;

	BEGIN_DB
	{
		StringStream sql;
		sql << "SELECT ItemID, ItemType, OptionType, Durability "
		    << "FROM MotorcycleObject where ItemID = " << targetID;
		
		pStmt   = g_pDatabaseManager->getConnection("DARKEDEN")->createStatement();
		pResult = pStmt->executeQuery(sql.toString());

		// by sigi. 2002.10.14
		// 결과물이 없다면 모터사이클이 없는 거쥐.
		if (pResult->getRowCount() <= 0) 
		{
			bFound = false;

			itemID     = targetID;
			itemType   = 0;
			optionType = "";
			durability = 300;
		}
		else 
		{
			bFound = true;

			pResult->next();

			itemID     = pResult->getInt(1);
			itemType   = pResult->getInt(2);
			optionType = pResult->getString(3);
			durability = pResult->getInt(4);
		}


			// 모터사이클 객체를 생성한다.
			list<OptionType_t> optionTypes;
			setOptionTypeFromField(optionTypes, optionType);
			Motorcycle* pMotorcycle = new Motorcycle(itemType, optionTypes);

			Assert(pMotorcycle != NULL);

			pMotorcycle->setItemID(itemID);
			pMotorcycle->setDurability(durability);

			// 존에다 붙이기 전에 oid를 새로 할당받는다.
			(pZone->getObjectRegistry()).registerObject(pMotorcycle);
			
			// 생성한 모터사이클을 존에다 갖다붙인다.
			TPOINT pt = pZone->addItem(pMotorcycle, x, y, false);
			if (pt.x == -1)
			{
				// 오토바이를 존에다 더할 수 없었다. 씨바.
				filelog("motorError.txt", "ActionRedeemMotorcycle::load() : 모터사이클을 존에다 더할 수 없습니다. zoneID=%d, xy=(%d, %d)", (int)pZone->getZoneID(), (int)x, (int)y);	// by sigi. 2002.12.24
				throw Error("ActionRedeemMotorcycle::load() : 모터사이클을 존에다 더할 수 없습니다");
			}
			
			// by sigi. 2002.10.14
			if (!bFound)
			{
				pStmt->executeQuery(
				"INSERT IGNORE INTO MotorcycleObject (ItemID, ObjectID, ItemType, OwnerID, Storage, StorageID, X, Y, OptionType, Durability) Values (%d, %d, %d, '', %d, %d, %d, %d, '', %d)",
					itemID, pMotorcycle->getObjectID(), itemType, STORAGE_ZONE, pZone->getZoneID(), pt.x, pt.y, durability);
			}

			// 모터사이클을 뻑킹 센터에 등록해준다.
			MotorcycleBox* pBox = new MotorcycleBox(pMotorcycle, pZone, pt.x, pt.y);
			Assert(pBox != NULL);

			try {
				g_pParkingCenter->addMotorcycleBox(pBox);
			} catch (DuplicatedException& de) {	// by sigi. 2002.12.24
				filelog("motorError.txt", "%s - itemID=%d, motorid=%d", de.toString().c_str(), itemID, pMotorcycle->getObjectID());
			}

			bFound = true;
		//}
		
		SAFE_DELETE(pStmt);
	}
	END_DB(pStmt)

	} catch (Throwable& t) {	// by sigi. 2002.12.25
		filelog("motorError.txt", "%s - itemID=%d, motorItemID=%d", t.toString().c_str(), (int)pItem->getItemID(), (int)targetID);
		// 일단 다운은 막자.
		//throw;
	}

	__END_CATCH

	return bFound;
}
示例#20
0
void DataCollector::PrintResult(int turn_amount, Result result) {
	data_output_->PrintLine(Utils::ToString(turn_amount) + result.ToString());
}
示例#21
0
bool BPlusTree::removeKey(Key k) {
	if (!root)
		return false;
	Result result = BPlusTree::recursiveRemove(k, root, NULL, NULL, NULL, NULL, NULL, 0);
	return !result.contains(Result::NO_ENCONTRADO);
}
示例#22
0
void BCPattern::matchAnchored(const Expr& pattern,
                              PC start, PC end, Result& result) {
  auto pos = pattern.begin();

  for (auto inst = start; inst != end; ) {
    // Detect a match.
    if (pos == pattern.end()) {
      result.m_start = start;
      result.m_end = inst;
      return;
    }

    auto const op = peek_op(inst);

    // Skip pattern-globally ignored opcodes.
    if (m_ignores.count(op)) {
      inst = next(inst);
      continue;
    }

    // Check for alternations whenever we fail to match.
    auto nomatch = [&] {
      if (!pos->hasAlt()) return result.erase();

      // Pop the capture if we made one.
      if (pos->shouldCapture()) {
        result.m_captures.pop_back();
      }

      for (auto const& atom : pos->getAlt()) {
        // Construct the full alternate pattern.
        auto alt = Expr { atom };
        alt.insert(alt.end(), std::next(pos), pattern.end());
        auto res = result;

        // Match on the alternate.
        matchAnchored(alt, inst, end, res);

        if (res.found()) {
          result = res;
          result.m_start = start;
          return;
        }
      }
      return result.erase();
    };

    // Capture the atom if desired.
    if (pos->shouldCapture()) {
      result.m_captures.push_back(inst);
    }

    // Check for shallow match.
    if (pos->op() != op) {
      return nomatch();
    }

    auto filter = pos->getFilter();

    // Check for deep match if desired.
    if (filter && !filter(inst, result.m_captures)) {
      return nomatch();
    }

    if ((pos->op() == Op::JmpZ || pos->op() == Op::JmpNZ)) {
      // Match the taken block, if there is one.
      auto off = instrJumpOffset(inst);
      assert(off);

      auto res = result;
      matchAnchored(pos->getTaken(), inst + *off, end, res);

      if (!res.found()) {
        return nomatch();
      }

      // Grab the captures.
      result.m_captures = res.m_captures;
    }

    if (pos->hasSeq()) {
      // Match the subsequence if we have one.
      auto res = result;
      matchAnchored(pos->getSeq(), next(inst), end, res);

      if (!res.found()) {
        return nomatch();
      }

      // Set the PC.
      result.m_captures = res.m_captures;
      inst = res.m_end;
    } else {
      // Step the PC.
      inst = next(inst);
    }

    // Step the pattern.
    ++pos;
  }

  // Detect a terminal match.
  if (pos == pattern.end()) {
    result.m_start = start;
    result.m_end = end;
  }
}
示例#23
0
//////////////////////////////////////////////////////////////////////////////
// DB 로부터 특정 플레이어 아이디를 찾아서 그 여부를 클라이언트로 리턴해준다.
//////////////////////////////////////////////////////////////////////////////
void CLQueryPlayerIDHandler::execute (CLQueryPlayerID* pPacket , Player* pPlayer)
	 throw(ProtocolException , Error)
{
	__BEGIN_TRY __BEGIN_DEBUG_EX
		
#ifdef __LOGIN_SERVER__

	Assert(pPacket != NULL);
	Assert(pPlayer != NULL);

	LoginPlayer* pLoginPlayer = dynamic_cast<LoginPlayer*>(pPlayer);

	Statement* pStmt;

	try {

		pStmt = g_pDatabaseManager->getConnection("DARKEDEN")->createStatement();

		Result* pResult = pStmt->executeQuery(
			"SELECT Name FROM Player WHERE PlayerID = '%s'" , 
			pPacket->getPlayerID().c_str() 
		); 

		LCQueryResultPlayerID lcQueryResultPlayerID;

		//cout << "Query Result : " << pPacket->getPlayerID() << " is ";

		lcQueryResultPlayerID.setPlayerID(pPacket->getPlayerID());

		if (pResult->getRowCount() == 0) {
		
			lcQueryResultPlayerID.setExist(false);

			//cout << "not ";

		} else {

			lcQueryResultPlayerID.setExist(true);

		}

		//cout << "exist..." << endl;
		
		pLoginPlayer->sendPacket(&lcQueryResultPlayerID);

		// 쿼리가 여러 번 올 수 있으므로, 여전히 LWFRP 이다.
		// 문제는 누군가가 프로그램을 짜서 DOS 공격을 할 수 있으므로,
		// 최소 시간을 둬야 한다는 점이다.
		pLoginPlayer->setPlayerStatus(LPS_WAITING_FOR_CL_REGISTER_PLAYER);
			
		SAFE_DELETE(pStmt);
		//delete pStmt;		// 2002.1.16 by sigi
	} 
	catch (SQLQueryException & sqe) 
	{
		SAFE_DELETE(pStmt);
		throw;
	}
	
#endif
		
	__END_DEBUG_EX __END_CATCH
}
示例#24
0
文件: unittest.cpp 项目: ANTco/mongo
        int Suite::run( const std::vector<std::string>& suites , const std::string& filter , int runsPerTest ) {

            if (_allSuites().empty()) {
                log() << "error: no suites registered.";
                return EXIT_FAILURE;
            }

            for ( unsigned int i = 0; i < suites.size(); i++ ) {
                if ( _allSuites().count( suites[i] ) == 0 ) {
                    log() << "invalid test suite [" << suites[i] << "], use --list to see valid names" << std::endl;
                    return EXIT_FAILURE;
                }
            }

            std::vector<std::string> torun(suites);

            if ( torun.empty() ) {
                for ( SuiteMap::const_iterator i = _allSuites().begin();
                      i !=_allSuites().end(); ++i ) {

                    torun.push_back( i->first );
                }
            }

            std::vector<Result*> results;

            for ( std::vector<std::string>::iterator i=torun.begin(); i!=torun.end(); i++ ) {
                std::string name = *i;
                Suite* s = _allSuites()[name];
                fassert( 16145,  s );

                log() << "going to run suite: " << name << std::endl;
                results.push_back( s->run( filter, runsPerTest ) );
            }

            log() << "**************************************************" << std::endl;

            int rc = 0;

            int tests = 0;
            int asserts = 0;
            int millis = 0;

            Result totals ("TOTALS");
            std::vector<std::string> failedSuites;

            for ( std::vector<Result*>::iterator i=results.begin(); i!=results.end(); i++ ) {
                Result* r = *i;
                log() << r->toString();
                if ( abs( r->rc() ) > abs( rc ) )
                    rc = r->rc();

                tests += r->_tests;
                if ( !r->_fails.empty() ) {
                    failedSuites.push_back(r->toString());
                    for ( std::vector<std::string>::const_iterator j=r->_fails.begin();
                          j!=r->_fails.end(); j++ ) {
                        const std::string& s = (*j);
                        totals._fails.push_back(r->_name + "/" + s);
                    }
                }
                asserts += r->_asserts;
                millis += r->_millis;
            }

            totals._tests = tests;
            totals._asserts = asserts;
            totals._millis = millis;

            log() << totals.toString(); // includes endl

            // summary
            if ( !totals._fails.empty() ) {
                log() << "Failing tests:" << std::endl;
                for ( std::vector<std::string>::const_iterator i=totals._fails.begin();
                      i!=totals._fails.end(); i++ ) {
                    const std::string& s = (*i);
                    log() << "\t " << s << " Failed";
                }
                log() << "FAILURE - " << totals._fails.size() << " tests in "
                      << failedSuites.size() << " suites failed";
            }
            else {
                log() << "SUCCESS - All tests in all suites passed";
            }

            return rc;
        }
示例#25
0
文件: state.cpp 项目: aelovikov/mesos
Try<TaskState> TaskState::recover(
    const string& rootDir,
    const SlaveID& slaveId,
    const FrameworkID& frameworkId,
    const ExecutorID& executorId,
    const UUID& uuid,
    const TaskID& taskId,
    bool strict)
{
  TaskState state;
  state.id = taskId;
  string message;

  // Read the task info.
  string path = paths::getTaskInfoPath(
      rootDir, slaveId, frameworkId, executorId, uuid, taskId);
  if (!os::exists(path)) {
    // This could happen if the slave died after creating the task
    // directory but before it checkpointed the task info.
    LOG(WARNING) << "Failed to find task info file '" << path << "'";
    return state;
  }

  const Result<Task>& task = ::protobuf::read<Task>(path);

  if (task.isError()) {
    message = "Failed to read task info from '" + path + "': " + task.error();

    if (strict) {
      return Error(message);
    } else {
      LOG(WARNING) << message;
      state.errors++;
      return state;
    }
  }

  if (task.isNone()) {
    // This could happen if the slave died after opening the file for
    // writing but before it checkpointed anything.
    LOG(WARNING) << "Found empty task info file '" << path << "'";
    return state;
  }

  state.info = task.get();

  // Read the status updates.
  path = paths::getTaskUpdatesPath(
      rootDir, slaveId, frameworkId, executorId, uuid, taskId);
  if (!os::exists(path)) {
    // This could happen if the slave died before it checkpointed
    // any status updates for this task.
    LOG(WARNING) << "Failed to find status updates file '" << path << "'";
    return state;
  }

  // Open the status updates file for reading and writing (for truncating).
  const Try<int>& fd = os::open(path, O_RDWR);

  if (fd.isError()) {
    message = "Failed to open status updates file '" + path +
              "': " + fd.error();

    if (strict) {
      return Error(message);
    } else {
      LOG(WARNING) << message;
      state.errors++;
      return state;
    }
  }

  // Now, read the updates.
  Result<StatusUpdateRecord> record = None();
  while (true) {
    // Ignore errors due to partial protobuf read.
    record = ::protobuf::read<StatusUpdateRecord>(fd.get(), true);

    if (!record.isSome()) {
      break;
    }

    if (record.get().type() == StatusUpdateRecord::UPDATE) {
      state.updates.push_back(record.get().update());
    } else {
      state.acks.insert(UUID::fromBytes(record.get().uuid()));
    }
  }

  // Always truncate the file to contain only valid updates.
  // NOTE: This is safe even though we ignore partial protobuf
  // read errors above, because the 'fd' is properly set to the
  // end of the last valid update by 'protobuf::read()'.
  if (ftruncate(fd.get(), lseek(fd.get(), 0, SEEK_CUR)) != 0) {
    return ErrnoError(
        "Failed to truncate status updates file '" + path + "'");
  }

  // After reading a non-corrupted updates file, 'record' should be 'none'.
  if (record.isError()) {
    message = "Failed to read status updates file  '" + path +
              "': " + record.error();

    if (strict) {
      return Error(message);
    } else {
      LOG(WARNING) << message;
      state.errors++;
      return state;
    }
  }

  // Close the updates file.
  const Try<Nothing>& close = os::close(fd.get());

  if (close.isError()) {
    message = "Failed to close status updates file '" + path +
              "': " + close.error();

    if (strict) {
      return Error(message);
    } else {
      LOG(WARNING) << message;
      state.errors++;
      return state;
    }
  }

  return state;
}
示例#26
0
文件: flags.hpp 项目: 447327642/mesos
  Flags()
  {
    // We log to stderr by default, but when running tests we'd prefer
    // less junk to fly by, so force one to specify the verbosity.
    add(&Flags::verbose,
        "verbose",
        "Log all severity levels to stderr",
        false);

    add(&Flags::benchmark,
        "benchmark",
        "Run the benchmark tests (and skip other tests)",
        false);

    // We determine the defaults for 'source_dir' and 'build_dir' from
    // preprocessor definitions (at the time this comment was written
    // these were set via '-DSOURCE_DIR=...' and '-DBUILD_DIR=...' in
    // src/Makefile.am).
    Result<std::string> path = os::realpath(SOURCE_DIR);
    CHECK_SOME(path);
    add(&Flags::source_dir,
        "source_dir",
        "Where to find the source directory",
        path.get());

    path = os::realpath(BUILD_DIR);
    CHECK_SOME(path);

    add(&Flags::build_dir,
        "build_dir",
        "Where to find the build directory",
        path.get());

    add(&Flags::docker,
        "docker",
        "Where to find docker executable",
        "docker");

    add(&Flags::docker_socket,
        "docker_socket",
        "The UNIX socket path to be mounted into the\n"
        "docker executor container to provide docker\n"
        "CLI access to the docker daemon. This must be the\n"
        "path used by the slave's docker image.\n",
        "/var/run/docker.sock");

    // This help message for --modules flag is the same for
    // {master,slave,tests}/flags.hpp and should always be kept in
    // sync.
    // TODO(karya): Remove the JSON example and add reference to the
    // doc file explaining the --modules flag.
    add(&Flags::modules,
        "modules",
        "List of modules to be loaded and be available to the internal\n"
        "subsystems.\n"
        "\n"
        "Use --modules=filepath to specify the list of modules via a\n"
        "file containing a JSON-formatted string. 'filepath' can be\n"
        "of the form 'file:///path/to/file' or '/path/to/file'.\n"
        "\n"
        "Use --modules=\"{...}\" to specify the list of modules inline.\n"
        "\n"
        "Example:\n"
        "{\n"
        "  \"libraries\": [\n"
        "    {\n"
        "      \"file\": \"/path/to/libfoo.so\",\n"
        "      \"modules\": [\n"
        "        {\n"
        "          \"name\": \"org_apache_mesos_bar\",\n"
        "          \"parameters\": [\n"
        "            {\n"
        "              \"key\": \"X\",\n"
        "              \"value\": \"Y\"\n"
        "            }\n"
        "          ]\n"
        "        },\n"
        "        {\n"
        "          \"name\": \"org_apache_mesos_baz\"\n"
        "        }\n"
        "      ]\n"
        "    },\n"
        "    {\n"
        "      \"name\": \"qux\",\n"
        "      \"modules\": [\n"
        "        {\n"
        "          \"name\": \"org_apache_mesos_norf\"\n"
        "        }\n"
        "      ]\n"
        "    }\n"
        "  ]\n"
        "}");

    // This help message is duplicated from slave/flags.hpp and
    // should always be kept in sync with that.
    add(&Flags::isolation,
        "isolation",
        "Isolation mechanisms to use, e.g., 'posix/cpu,posix/mem', or\n"
        "'cgroups/cpu,cgroups/mem', or network/port_mapping\n"
        "(configure with flag: --with-network-isolator to enable),\n"
        "or 'external', or load an alternate isolator module using\n"
        "the --modules flag.");

    // This help message is duplicated from master/flags.hpp and
    // should always be kept in sync with that.
    add(&Flags::authenticators,
        "authenticators",
        "Authenticator implementation to use when authenticating frameworks\n"
        "and/or slaves. "
        "Use the default '" + master::DEFAULT_AUTHENTICATOR + "', or\n"
        "load an alternate authenticator module using --modules.",
        master::DEFAULT_AUTHENTICATOR);
  }
示例#27
0
    Result* Result::duplicate (ResultSet* rs, ResultSetIterator /* row */) {
	Result* ret = new Result(rs);
	for (BindingSetIterator it = bindings.begin(); it != bindings.end(); it++)
	    ret->set(it->first, it->second.pos, it->second.weaklyBound);
	return ret;
    }
示例#28
0
void ThroughputModePanel::RefreshResultList(void)
{
	ResultLog *rlog = ResultLog::GetInstance();

	Result *result = rlog->GetResults( wxString( wxT("throughput") ) );

	m_ListResult->DeleteAllItems();

	for( int i = result->GetRowCount()-1 ; i > -1  ; i-- )
	{
		StringValueList *row = result->GetRow( i );

		wxListItem item;
		int id = m_ListResult->GetItemCount();
		item.SetMask(wxLIST_MASK_TEXT);
		item.SetId(id);
		item.SetData( i );
		
		item.SetText( *row->Item(0)->GetData() );
		m_ListResult->InsertItem( item );

		int iD_TP_Bandwidth;
		row->Item(1)->GetData()->ToLong( (long*)&iD_TP_Bandwidth );
		wxString D_TP_Bandwidth;
		if( iD_TP_Bandwidth > 0 )
		  D_TP_Bandwidth << FROMCSTR(Int32ToString(iD_TP_Bandwidth*8));
		else
		  D_TP_Bandwidth << wxT("Inget värde");

		m_ListResult->SetItem( id, 1, D_TP_Bandwidth );


		int iU_TP_Bandwidth;
		row->Item(2)->GetData()->ToLong( (long*)&iU_TP_Bandwidth );
		wxString U_TP_Bandwidth;
		if( iU_TP_Bandwidth > 0 )
		  U_TP_Bandwidth << FROMCSTR(Int32ToString(iU_TP_Bandwidth*8));
		else
		  U_TP_Bandwidth << wxT("Inget värde");

		m_ListResult->SetItem( id, 2, U_TP_Bandwidth );


		int iHTTP_Bandwidth;
		row->Item(3)->GetData()->ToLong( (long*)&iHTTP_Bandwidth );
		wxString HTTP_Bandwidth;
		if( iHTTP_Bandwidth > 0 )
		  HTTP_Bandwidth << FROMCSTR(Int32ToString(iHTTP_Bandwidth));
		else
		  HTTP_Bandwidth << wxT("Inget värde");

		m_ListResult->SetItem( id, 3, HTTP_Bandwidth );

		int iFTP_Bandwidth;
		row->Item(4)->GetData()->ToLong( (long*)&iFTP_Bandwidth );
		wxString FTP_Bandwidth;
		if( iFTP_Bandwidth > 0 )
		  FTP_Bandwidth << FROMCSTR(Int32ToString(iFTP_Bandwidth));
		else
		  FTP_Bandwidth << wxT("Inget värde");

		m_ListResult->SetItem( id, 4, FTP_Bandwidth );
	}

	return;
}
示例#29
0
// This test runs a command without the command user field set. The
// command will verify the assumption that the command is run as the
// slave user (in this case, root).
TEST_F(SlaveTest, ROOT_RunTaskWithCommandInfoWithoutUser)
{
  Try<PID<Master> > master = StartMaster();
  ASSERT_SOME(master);

  // Need flags for 'executor_registration_timeout'.
  slave::Flags flags = CreateSlaveFlags();
  flags.isolation = "posix/cpu,posix/mem";

  Try<MesosContainerizer*> containerizer =
    MesosContainerizer::create(flags, false);
  CHECK_SOME(containerizer);

  Try<PID<Slave> > slave = StartSlave(containerizer.get());
  ASSERT_SOME(slave);

  MockScheduler sched;
  MesosSchedulerDriver driver(
      &sched, DEFAULT_FRAMEWORK_INFO, master.get(), DEFAULT_CREDENTIAL);

  EXPECT_CALL(sched, registered(&driver, _, _))
    .Times(1);

  Future<vector<Offer> > offers;
  EXPECT_CALL(sched, resourceOffers(&driver, _))
    .WillOnce(FutureArg<1>(&offers))
    .WillRepeatedly(Return()); // Ignore subsequent offers.

  driver.start();

  AWAIT_READY(offers);
  EXPECT_NE(0u, offers.get().size());

  // Launch a task with the command executor.
  TaskInfo task;
  task.set_name("");
  task.mutable_task_id()->set_value("1");
  task.mutable_slave_id()->MergeFrom(offers.get()[0].slave_id());
  task.mutable_resources()->MergeFrom(offers.get()[0].resources());

  Result<string> user = os::user();
  CHECK_SOME(user) << "Failed to get current user name"
                   << (user.isError() ? ": " + user.error() : "");

  // Command executor will run as user running test.
  CommandInfo command;
  command.set_value("test `whoami` = " + user.get());

  task.mutable_command()->MergeFrom(command);

  vector<TaskInfo> tasks;
  tasks.push_back(task);

  Future<TaskStatus> statusRunning;
  Future<TaskStatus> statusFinished;
  EXPECT_CALL(sched, statusUpdate(&driver, _))
    .WillOnce(FutureArg<1>(&statusRunning))
    .WillOnce(FutureArg<1>(&statusFinished));

  driver.launchTasks(offers.get()[0].id(), tasks);

  AWAIT_READY(statusRunning);
  EXPECT_EQ(TASK_RUNNING, statusRunning.get().state());

  AWAIT_READY(statusFinished);
  EXPECT_EQ(TASK_FINISHED, statusFinished.get().state());

  driver.stop();
  driver.join();

  Shutdown(); // Must shutdown before 'containerizer' gets deallocated.
}
 void perform_test_trivial() {
   Result s;
   typedef ParserResult<Result> Parser;
   Parser p(s);
   {
     typedef std::vector<TupleResult> Vector;
     Vector test_vector;
     add_positive_result_tuples(test_vector);
      for (Vector::const_iterator i = test_vector.begin(); i != test_vector.end(); ++i) {
       std::stringstream test_stream;
       test_stream << *i;
       const std::string test(test_stream.str());
       OKLIB_TESTTRIVIAL_RETHROW(::OKlib::Parser::Test_ParsingString<Parser>(p, test, ::OKlib::Parser::match_full));
       if (s.super_series().name() != i -> get<0>().name()) {
         std::stringstream out;
         out << "Super Series is " << s.super_series() << ", and not " << i -> get<0>();
         OKLIB_THROW(out.str());
       }
       if (s.series().name() != i -> get<1>().name()) {
         std::stringstream out;
         out << "Series is " << s.series() << ", and not " << i -> get<1>();
         OKLIB_THROW(out.str());
       }
       if (s.benchmark().name() != i -> get<2>().name()) {
         std::stringstream out;
         out << "Benchmark is " << s.benchmark() << ", and not " << i -> get<2>();
         OKLIB_THROW(out.str());
       }
       if (s.solver().name() != i -> get<3>().name()) {
         std::stringstream out;
         out << "Solver is " << s.solver() << ", and not " << i -> get<3>();
         OKLIB_THROW(out.str());
       }
       if (s.sat_status().result() != i -> get<4>().result()) {
         std::stringstream out;
         out << "Sat_Status is " << s.sat_status() << ", and not " << i -> get<4>();
         OKLIB_THROW(out.str());
       }
       if (s.average().average() != i -> get<5>().average()) {
         std::stringstream out;
         out << "Average is " << s.average() << ", and not " << i -> get<5>();
         OKLIB_THROW(out.str());
       }
       if (s.time_out().time_out() != i -> get<6>().time_out()) {
         std::stringstream out;
         out << "Time_Out is " << s.time_out() << ", and not " << i -> get<6>();
         OKLIB_THROW(out.str());
       }
       if (s != *i) {
         std::stringstream out;
         out << "Result is \"" << s <<"\", and not \"" << *i << "\"";
         OKLIB_THROW(out.str());
       }
     }
   }
 }