Ejemplo n.º 1
0
bool CNavMesh::raycast(position_t& start, position_t& end)
{
    if (start.x == end.x && start.y == end.y && start.z == end.z)
        return true;
    dtStatus status;

    float spos[3];
    CNavMesh::ToDetourPos(&start, spos);

    float epos[3];
    CNavMesh::ToDetourPos(&end, epos);

    float polyPickExt[3];
    polyPickExt[0] = 30;
    polyPickExt[1] = 60;
    polyPickExt[2] = 30;

    float snearest[3];

    dtQueryFilter filter;
    filter.setIncludeFlags(0xffff);
    filter.setExcludeFlags(0);

    dtPolyRef startRef;

    status = m_navMeshQuery->findNearestPoly(spos, polyPickExt, &filter, &startRef, snearest);

    if (dtStatusFailed(status))
    {
        ShowNavError("CNavMesh::raycastPoint start point invalid (%f, %f, %f) (%u)\n", spos[0], spos[1], spos[2], m_zoneID);
        outputError(status);
        return true;
    }

    if (!m_navMesh->isValidPolyRef(startRef))
    {
        ShowNavError("CNavMesh::raycastPoint startRef is invalid (%f, %f, %f) (%u)\n", start.x, start.y, start.z, m_zoneID);
        return true;
    }

    status = m_navMeshQuery->raycast(startRef, spos, epos, &filter, 0, &m_hit);

    if (dtStatusFailed(status))
    {
        ShowNavError("CNavMesh::raycastPoint raycast failed (%f, %f, %f)->(%f, %f, %f) (%u)\n", spos[0], spos[1], spos[2], epos[0], epos[1], epos[2], m_zoneID);
        outputError(status);
        return true;
    }

    // no wall was hit
    if (m_hit.t == FLT_MAX)
    {
        return true;
    }

    return false;
}
Ejemplo n.º 2
0
int16 CNavMesh::findRandomPosition(position_t start, float maxRadius, position_t* randomPosition)
{

    dtStatus status;
    int16 length = 0;

    float spos[3];
    CNavMesh::ToDetourPos(&start, spos);

    float polyPickExt[3];
    polyPickExt[0] = 30;
    polyPickExt[1] = 60;
    polyPickExt[2] = 30;

    float randomPt[3];
    float snearest[3];

    dtQueryFilter filter;
    filter.setIncludeFlags(0xffff);
    filter.setExcludeFlags(0);

    dtPolyRef startRef;
    dtPolyRef randomRef;

    status = m_navMeshQuery->findNearestPoly(spos, polyPickExt, &filter, &startRef, snearest);

    if (dtStatusFailed(status))
    {
        ShowNavError("CNavMesh::findRandomPath start point invalid (%f, %f, %f) (%u)\n", spos[0], spos[1], spos[2], m_zoneID);
        outputError(status);
        return ERROR_NEARESTPOLY;
    }

    if (!m_navMesh->isValidPolyRef(startRef))
    {
        ShowNavError("CNavMesh::findRandomPath startRef is invalid (%f, %f, %f) (%u)\n", start.x, start.y, start.z, m_zoneID);
        return ERROR_NEARESTPOLY;
    }

    status = m_navMeshQuery->findRandomPointAroundCircle(startRef, spos, maxRadius, &filter, []() -> float { return dsprand::GetRandomNumber(1.f); }, &randomRef, randomPt);

    if (dtStatusFailed(status))
    {
        ShowNavError("CNavMesh::findRandomPath Error (%u)\n", m_zoneID);
        outputError(status);
        return ERROR_NEARESTPOLY;
    }

    CNavMesh::ToFFXIPos(randomPt);
    randomPosition->x = randomPt[0];
    randomPosition->y = randomPt[1];
    randomPosition->z = randomPt[2];

    return 0;
}
Ejemplo n.º 3
0
	bool Movie::openFromFile(const std::string& filename)
	{
		int err = 0;
		bool preloaded = false;

		// Make sure everything is cleaned before opening a new movie
		stop();
		close();
		
		// Load all the decoders
		av_register_all();

		// Open the movie file
		err = avformat_open_input(&m_avFormatCtx, filename.c_str(), NULL, NULL);

		if (err != 0)
		{
			outputError(err, "unable to open file " + filename);
			return false;
		}

		// Read the general movie informations
		err = avformat_find_stream_info(m_avFormatCtx, NULL);

		if (err < 0)
		{
			outputError(err);
			close();
			return false;
		}

		if (usesDebugMessages())
			// Output the movie informations
			av_dump_format(m_avFormatCtx, 0, filename.c_str(), 0);

		// Perform the audio and video loading
		m_hasVideo = m_video->initialize();
		m_hasAudio = m_audio->initialize();
		
		if (m_hasVideo)
		{
			preloaded = m_video->preLoad();
			
			if (!preloaded) // Loading first frames failed
			{
				if (sfe::Movie::usesDebugMessages())
					std::cerr << "Movie::OpenFromFile() - Movie_video::PreLoad() failed.\n";
			}
		}
		
		return m_hasAudio || (m_hasVideo && preloaded);
	}
Ejemplo n.º 4
0
int16 CNavMesh::findRandomPath(position_t start, float maxRadius, position_t* path, uint16 pathSize)
{

  dtStatus status;
  int16 length = 0;

  float spos[3];
  spos[0] = start.x;
  spos[1] = start.y * -1;
  spos[2] = start.z * -1;

  float polyPickExt[3];
  polyPickExt[0] = 30;
  polyPickExt[1] = 60;
  polyPickExt[2] = 30;

  float randomPt[3];
  float snearest[3];

  dtQueryFilter filter;
  filter.setIncludeFlags(0xffff);
  filter.setExcludeFlags(0);

  dtPolyRef startRef;
  dtPolyRef randomRef;

  status = m_navMeshQuery->findNearestPoly(spos, polyPickExt, &filter, &startRef, snearest);

  if(dtStatusFailed(status))
  {
    ShowError("CNavMesh::findRandomPath start point invalid (%f, %f, %f)\n", spos[0], spos[1], spos[2]);
    outputError(status);
    return ERROR_NEARESTPOLY;
  }

  status = m_navMeshQuery->findRandomPointAroundCircle(startRef, spos, maxRadius, &filter, &RandomNumber, &randomRef, randomPt);

  if(dtStatusFailed(status))
  {
    ShowError("CNavMesh::findRandomPath Error\n");
    outputError(status);
    return ERROR_NEARESTPOLY;
  }

  position_t end;

  end.x = randomPt[0];
  end.y = randomPt[1] * -1;
  end.z = randomPt[2] * -1;

  return findPath(start, end, path, pathSize);
}
Ejemplo n.º 5
0
void errMsg(char* formate, ...){
    va_list argList;
    va_start(argList, formate);//获取可变参数的起始地址
    int errorNum = errno;
    outputError(formate, argList, errorNum);
    va_end(argList);
}
Ejemplo n.º 6
0
sdLaMa091_t* sdLaMa091New(void) {
  sdLaMa091_t* sdLaMa091 = (sdLaMa091_t*) malloc(sizeof(*sdLaMa091));

#ifdef DEFENSIVE_ALLOC
  if (sdLaMa091 == NULL) {
    outputError("Cannot allocate sdLaMa091 structure");
    return NULL;
  }
#endif

  sdLaMa091->imageType = UNKNOWN;

  sdLaMa091->width = 0;
  sdLaMa091->rgbWidth = 0;
  sdLaMa091->height = 0;
  sdLaMa091->stride = 0;
  sdLaMa091->numBytes = 0;
  sdLaMa091->unusedBytes = 0;
  sdLaMa091->rgbUnusedBytes = 0;

  sdLaMa091->N = DEFAULT_N;
  sdLaMa091->Vmin = DEFAULT_VMIN;
  sdLaMa091->Vmax = DEFAULT_VMAX;

  sdLaMa091->Mt = NULL;
  sdLaMa091->Ot = NULL;
  sdLaMa091->Vt = NULL;

  return sdLaMa091;
}
Ejemplo n.º 7
0
void fatal(const char *format, ...)
{
	va_list argList;
	va_start(argList, format);
	outputError(FALSE, 0, TRUE, format, argList);
	va_end(argList);
	terminate(TRUE);
}
Ejemplo n.º 8
0
void errExitEN(int errnum, const char *format, ...)
{
	va_list argList;
	va_start(argList, format);
	outputError(TRUE, errnum, TRUE, format, argList);
	va_end(argList);
	terminate(TRUE);
}
Ejemplo n.º 9
0
void err_exit(const char *format, ...)
{
	va_list argList;
	va_start(argList, format);
	outputError(TRUE, errno, FALSE, format, argList);
	va_end(argList);
	terminate(FALSE);
}
Ejemplo n.º 10
0
void
errExitEN(int errnum, const char *format, ...)
{
    va_list argList;
    va_start(argList, format);
    outputError(1, errnum, 1, format, argList);
    va_end(argList);
   // terminate(1);
}
void fatal(const char * format, ...)
{
    va_list argList;

    va_start(argList, format);
    outputError(false, 0, true, format, argList);
    va_end(argList);

    terminate(true);
}
void err_exit(const char * format, ...)
{
    va_list argList;

    va_start(argList, format);
    outputError(true, errno, false, format, argList);
    va_end(argList);

    terminate(false);
}
Ejemplo n.º 13
0
int32_t sdLaMa091SetMaximalVariance(sdLaMa091_t* sdLaMa091,
  const uint32_t maximalVariance) {
#ifdef DEFENSIVE_POINTER
  if (sdLaMa091 == NULL) {
    outputError("Cannot set a parameter of a NULL structure");
    return EXIT_FAILURE;
  }
#endif 

#ifdef DEFENSIVE_PARAM
  if (maximalVariance == 0) {
    outputError("Cannot set a parameter with a zero value");
    return EXIT_FAILURE;
  }
#endif 

  sdLaMa091->Vmax = maximalVariance;

  return EXIT_SUCCESS;
}
Ejemplo n.º 14
0
int32_t sdLaMa091SetAmplificationFactor(sdLaMa091_t* sdLaMa091,
  const uint32_t amplificationFactor) {
#ifdef DEFENSIVE_POINTER
  if (sdLaMa091 == NULL) {
    outputError("Cannot set a parameter of a NULL structure");
    return EXIT_FAILURE;
  }
#endif 

#ifdef DEFENSIVE_PARAM
  if (amplificationFactor == 0) {
    outputError("Cannot set a parameter with a zero value");
    return EXIT_FAILURE;
  }
#endif 

  sdLaMa091->N = amplificationFactor;

  return EXIT_SUCCESS;
}
Ejemplo n.º 15
0
void errMsg(const char *format, ...)
{
	va_list argList;
	int savedErrno;
	savedErrno = errno;
	/* In case we change it here */
	va_start(argList, format);
	outputError(TRUE, errno, TRUE, format, argList);
	va_end(argList);
	errno = savedErrno;
}
Ejemplo n.º 16
0
uint32_t sdLaMa091GetAmplificationFactor(const sdLaMa091_t* sdLaMa091) {
#ifdef DEFENSIVE_POINTER
  if (sdLaMa091 == NULL) {
    outputError("Cannot get a parameter of a NULL structure");
    errno = ERROR_OCCURED;

    return EXIT_FAILURE;
  }
#endif 

  return sdLaMa091->N;
}
Ejemplo n.º 17
0
uint32_t sdLaMa091GetMinimalVariance(const sdLaMa091_t* sdLaMa091) {
#ifdef DEFENSIVE_POINTER
  if (sdLaMa091 == NULL) {
    outputError("Cannot get a parameter of a NULL structure");
    errno = ERROR_OCCURED;

    return EXIT_FAILURE;
  }
#endif 

  return sdLaMa091->Vmin;
}
void errMsg(const char * format, ...)
{
    va_list argList;
    int savedErrno;

    savedErrno = errno;

    va_start(argList, format);
    outputError(true, errno, true, format, argList);
    va_end(argList);

    errno = savedErrno;
}
Ejemplo n.º 19
0
void errMsg(const char *format, ...)
{
	va_list argList;
	int savedErrno;

	savedErrno = errno;

	va_start(argList, format);
	outputError(TRUE, errno, TRUE, format, argList);
	va_end(argList);

	terminate(FALSE);
}
Ejemplo n.º 20
0
int32_t sdLaMa091SetMinimalVariance(sdLaMa091_t* sdLaMa091,
  const uint32_t minimalVariance) {
#ifdef DEFENSIVE_POINTER
  if (sdLaMa091 == NULL) {
    outputError("Cannot set a parameter of a NULL structure");
    return EXIT_FAILURE;
  }
#endif 

  sdLaMa091->Vmin = minimalVariance;

  return EXIT_SUCCESS;
}
Ejemplo n.º 21
0
void
COSErr::
exit(const char *format, ...)
{
  va_list argList;

  va_start(argList, format);

  outputError(true, errno, true, format, argList);

  va_end(argList);

  terminate(true);
}
Ejemplo n.º 22
0
/* Display error message including 'errno' diagnostic, and
   return to caller */
void
COSErr::
message(const char *format, ...)
{
  va_list argList;

  int savedErrno = errno;       /* In case we change it here */

  va_start(argList, format);

  outputError(true, errno, true, format, argList);

  va_end(argList);

  errno = savedErrno;
}
Ejemplo n.º 23
0
int main(int argc, char *argv[])
{
	ifstream inFile;
	ofstream outFile;

	bool error;
	string input;
	
	vector<Token>TokenList;

	Scanner analyze;

	inFile.open(argv[1]);
	outFile.open(argv[2]);

	while(getline(inFile,input))
	{
		error=analyze.identifier(input);

		if(error==true)
		{
			analyze.initiateError(outFile);
			return 0;
		}
	}
	TokenList=analyze.tokenify();

	Parser parse(TokenList);

	try
	{
		parse.parse();
	}

	catch(string a)
	{
		Token temp=outputError(parse);
		outFile<<"Failure!"<<endl;
		outFile<<"  "<<"("<<temp.getChar()<<","<<"\""<<temp.getInfo()<<"\""<<","<<temp.fetchLineNum()<<")"<<endl;
		return 0;
	}
	
	parse.outToFile(outFile);
	return 0;
}
Ejemplo n.º 24
0
void ExternalLanguage::receivedStderr( K3Process *, char * buffer, int buflen )
{
	QStringList lines = QStringList::split( '\n', QString::fromLocal8Bit( buffer, buflen ), false );
	QStringList::iterator end = lines.end();
	
	for ( QStringList::iterator it = lines.begin(); it != end; ++it )
	{
		if ( isStderrOutputFatal( *it ) )
		{
			outputError( *it );
			outputtedError( *it );
		}
		else
		{
			outputWarning( *it );
			outputtedWarning( *it );
		}
	}
}
Ejemplo n.º 25
0
int32_t sdLaMa091Free(sdLaMa091_t* sdLaMa091) {
#ifdef DEFENSIVE_POINTER
  if (sdLaMa091 == NULL) {
    outputError("Cannot free a NULL strucutre");
    return EXIT_FAILURE;
  }
#endif

  if (sdLaMa091->Mt != NULL)
    free(sdLaMa091->Mt);
  if (sdLaMa091->Ot != NULL)
    free(sdLaMa091->Ot);
  if (sdLaMa091->Vt != NULL)
    free(sdLaMa091->Vt);

  free(sdLaMa091);

  return EXIT_SUCCESS;
}
Ejemplo n.º 26
0
bool CNavMesh::load(char* path)
{
  this->path = path;
  this->unload();

  m_navMesh = new dtNavMesh();

  FILE* fp = fopen(path, "rb");

  if (!fp)
  {
    ShowError("CNavMesh::load Error loading navmesh (%s)\n", path);
    return false;
  }

  // Read header.
  NavMeshSetHeader header;
  fread(&header, sizeof(NavMeshSetHeader), 1, fp);
  if (header.magic != NAVMESHSET_MAGIC)
  {
    fclose(fp);
    return false;
  }
  if (header.version != NAVMESHSET_VERSION)
  {
    fclose(fp);
    return false;
  }

  m_navMesh = dtAllocNavMesh();
  if (!m_navMesh)
  {
    fclose(fp);
    return false;
  }

  dtStatus status = m_navMesh->init(&header.params);
  if (dtStatusFailed(status))
  {
    ShowError("CNavMesh::load Could not initialize detour for (%s)", path);
    outputError(status);
	fclose(fp);
    return false;
  }

  // Read tiles.
  for (int i = 0; i < header.numTiles; ++i)
  {
    NavMeshTileHeader tileHeader;
    fread(&tileHeader, sizeof(tileHeader), 1, fp);
    if (!tileHeader.tileRef || !tileHeader.dataSize)
            break;

    unsigned char* data = (unsigned char*)dtAlloc(tileHeader.dataSize, DT_ALLOC_PERM);
    if (!data) break;
    memset(data, 0, tileHeader.dataSize);
    fread(data, tileHeader.dataSize, 1, fp);

    m_navMesh->addTile(data, tileHeader.dataSize, DT_TILE_FREE_DATA, tileHeader.tileRef, 0);

  }

  fclose(fp);

  m_navMeshQuery = new dtNavMeshQuery();

  // init detour nav mesh path finder
  status = m_navMeshQuery->init(m_navMesh, MAX_NAV_POLYS);

  if(dtStatusFailed(status))
  {
    ShowError("CNavMesh::load Error loading navmeshquery (%s)\n", path);
    outputError(status);
    return false;
  }

  return true;
}
Ejemplo n.º 27
0
int16 CNavMesh::findPath(position_t start, position_t end, position_t* path, uint16 pathSize)
{

  dtStatus status;

  float spos[3];
  spos[0] = start.x;
  spos[1] = start.y * -1;
  spos[2] = start.z * -1;

  float epos[3];
  epos[0] = end.x;
  epos[1] = end.y * -1;
  epos[2] = end.z * -1;

  dtQueryFilter filter;
  filter.setIncludeFlags(0xffff);
  filter.setExcludeFlags(0);

  float polyPickExt[3];
  polyPickExt[0] = 10;
  polyPickExt[1] = 20;
  polyPickExt[2] = 10;

  dtPolyRef startRef;
  dtPolyRef endRef;

  dtPolyRef nearestRef;
  float enearest[3];
  float snearest[3];

  status = m_navMeshQuery->findNearestPoly(spos, polyPickExt, &filter, &startRef, snearest);

  if(dtStatusFailed(status))
  {
    ShowError("CNavMesh::findPath start point invalid (%f, %f, %f)\n", spos[0], spos[1], spos[2]);
    outputError(status);
    return ERROR_NEARESTPOLY;
  }

  status = m_navMeshQuery->findNearestPoly(epos, polyPickExt, &filter, &endRef, enearest);

  if(dtStatusFailed(status))
  {
    ShowError("CNavMesh::findPath end point invalid (%f, %f, %f)\n", epos[0], epos[1], epos[2]);
    outputError(status);
    return ERROR_NEARESTPOLY;
  }

  if (!m_navMesh->isValidPolyRef(startRef) || !m_navMesh->isValidPolyRef(endRef))
  {
    ShowError("CNavMesh::findPath Couldn't find path (%f, %f, %f)->(%f, %f, %f) \n", start.x, start.y, start.z, end.x, end.y, end.z);
    return ERROR_NEARESTPOLY;
  }

  dtPolyRef m_polys[MAX_NAV_POLYS];
  int npolys;
  float straightPath[MAX_NAV_POLYS*3];
  unsigned char straightPathFlags[MAX_NAV_POLYS];
  dtPolyRef straightPathPolys[MAX_NAV_POLYS];
  int nstraightPath = 0;

  int16 pos = 0;

  // not sure what this is for?
  int32 pathCount = 0;

  status = m_navMeshQuery->findPath(startRef, endRef, snearest, enearest, &filter, m_polys, &pathCount, MAX_NAV_POLYS);

  if(dtStatusFailed(status))
  {
    ShowError("CNavMesh::findPath findPath error\n");
    outputError(status);
    return -1;
  }

  if (pathCount > 0)
  {

    int32 straightPathCount = MAX_NAV_POLYS * 3;

    status = m_navMeshQuery->findStraightPath(snearest, enearest, m_polys, pathCount, straightPath, straightPathFlags, straightPathPolys, &straightPathCount, MAX_NAV_POLYS);

    if(dtStatusFailed(status))
    {
      ShowError("CNavMesh::findPath findStraightPath error\n");
      outputError(status);
      return -1;
    }

    // i starts at 3 so the start position is ignored
    for ( int i = 3; i < straightPathCount*3; )
    {
      path[pos].x = straightPath[i++];
      path[pos].y = straightPath[i++] * -1;
      path[pos].z = straightPath[i++] * -1;
      pos++;

      if(pos == pathSize)
      {
        ShowError("CNavMesh::findPath Path is too long to hold in array!\n");
        break;
      }
    }

  }

  return pos;
}
Ejemplo n.º 28
0
void SDCC::processInput( ProcessOptions options )
{
    resetLanguageProcess();

    MicroInfo * info = MicroLibrary::self()->microInfoWithID( options.m_picID );
    if (!info)
    {
        outputError( i18n("Could not find PIC with ID \"%1\".").arg(options.m_picID) );
        return;
    }

    m_processOptions = options;

    *m_languageProcess << ("sdcc");


    //BEGIN Pass custom sdcc options
#define ARG(text,option) if ( KTLConfig::text() ) *m_languageProcess << ( QString("--%1").arg(option) );
    // General
    ARG( sDCC_nostdlib,			"nostdlib" )
    ARG( sDCC_nostdinc,			"nostdinc" )
    ARG( sDCC_less_pedantic,		"less-pedantic" )
    ARG( sDCC_std_c89,			"std-c89" )
    ARG( sDCC_std_c99,			"std-c99" )

    // Code generation
    ARG( sDCC_stack_auto,			"stack-auto" )
    ARG( sDCC_int_long_reent,		"int-long-reent" )
    ARG( sDCC_float_reent,			"float-reent" )
    ARG( sDCC_fommit_frame_pointer,	"fommit-frame-pointer" )
    ARG( sDCC_no_xinit_opt,			"no-xinit-opt" )
    ARG( sDCC_all_callee_saves,		"all-callee-saves" )

    // Optimization
    ARG( sDCC_nooverlay,			"nooverlay" )
    ARG( sDCC_nogcse,			"nogcse" )
    ARG( sDCC_nolabelopt,			"nolabelopt" )
    ARG( sDCC_noinvariant,			"noinvariant" )
    ARG( sDCC_noinduction,			"noinduction" )
    ARG( sDCC_no_peep,			"no-peep" )
    ARG( sDCC_noloopreverse,		"noloopreverse" )
    ARG( sDCC_opt_code_size,		"opt-code-size" )
    ARG( sDCC_opt_code_speed,		"opt-code-speed" )
    ARG( sDCC_peep_asm,			"peep-asm" )
    ARG( sDCC_nojtbound,			"nojtbound" )

    // PIC16 Specific
    if ( info->instructionSet()->set() == AsmInfo::PIC16 )
    {
        ARG( sDCC_nodefaultlibs,		"nodefaultlibs" )
        ARG( sDCC_pno_banksel,			"pno-banksel" )
        ARG( sDCC_pstack_model_large,	"pstack-model=large" )
        ARG( sDCC_debug_xtra,			"debug-xtra" )
        ARG( sDCC_denable_peeps,		"denable-peeps" )
        ARG( sDCC_calltree,			"calltree" )
        ARG( sDCC_fstack,			"fstack" )
        ARG( sDCC_optimize_goto,		"optimize-goto" )
        ARG( sDCC_optimize_cmp,			"optimize-cmp" )
        ARG( sDCC_optimize_df,			"optimize-df" )
    }
#undef ARG

    if ( !KTLConfig::miscSDCCOptions().isEmpty() )
        *m_languageProcess << ( KTLConfig::miscSDCCOptions() );
    //END Pass custom sdcc options


    *m_languageProcess << ("--debug"); // Enable debugging symbol output
    *m_languageProcess << ("-S"); // Compile only; do not assemble or link

    QString asmSwitch;
    switch ( info->instructionSet()->set() )
    {
    case AsmInfo::PIC12:
        // Last time I checked, SDCC doesn't support Pic12, and probably never will, but whatever...
        asmSwitch = "-mpic12";
        break;
    case AsmInfo::PIC14:
        asmSwitch = "-mpic14";
        break;
    case AsmInfo::PIC16:
        asmSwitch = "-mpic16";
        break;
    }

    *m_languageProcess << (asmSwitch);

    *m_languageProcess << ( "-"+options.m_picID.lower() );

    *m_languageProcess << ( options.inputFiles().first() );

    *m_languageProcess << ("-o");
    *m_languageProcess << ( options.intermediaryOutput() );

    if ( !start() )
    {
        KMessageBox::sorry( LanguageManager::self()->logView(), i18n("Compilation failed. Please check you have sdcc installed.") );
        processInitFailed();
        return;
    }
}
Ejemplo n.º 29
0
//
// case 0: depart-level
//	dep-id => [pid,...] => [{pid,*,*}, ...]
//	host=[auto]
// case 1: pid-level
//	pid, *, *
//	host=[auto]
// case 2: mid-level
//	pid, mid, *
//	host=[auto]
// case 3: host-level
//	pid, mid, *
//	host=ip
// case 4: expand-to-individual-hosts
//	pid,mid,iid as in [0-2] (no case #3)
//	host=[auto]
//
static void handleRequest(QueryParameters& parameters)
{
	// step 1: context
	const char *strContext = parameters.getString("context", "resource");
	int context;
	if (!strcmp(strContext, "business")) {
		context = CT_BUSINESS;
	}
	else if (!strcmp(strContext, "resource")) {
		context = CT_RESOURCE;
	}
	else {
		outputError(501, "Invalid context parameter");
		return;
	}

	// step 2: group - how to combine stats together
	int totalView = 0;
	const char *strGroup = parameters.getString("group", "total");
	if (!strcmp(strGroup, "total")) {
		totalView = 1;
	}
	else if (!strcmp(strGroup, "list")) {
		totalView = 0;
	}
	else {
		outputError(501, "invalid group parameter, which should be total|list.");
		return;
	}
	
	// step 3: time period, span, align
	int64_t startDtime, endDtime;
	int spanUnit, spanCount;
	if (parseDtimeSpan(parameters, startDtime, endDtime, spanUnit, spanCount) < 0)
		return;

	// move ahead one span for some calculation need its previous stats
	startDtime -= spanLength(spanUnit, spanCount);
	int mergeCount = (endDtime - startDtime) / spanLength(spanUnit, spanCount);

//	char buf1[128], buf2[128];
//	APPLOG_DEBUG("parsed start=%s, end=%s, mergeCount=%d", 
//		formatDtime(buf1, sizeof buf1, startDtime),
//		formatDtime(buf2, sizeof buf2, endDtime), mergeCount);

	StatMerger merger(NULL, NULL, NULL, NULL, spanUnit, spanCount, mergeCount);
	merger.periodStartTime = startDtime;
	
	// step 4: ids
// TODO: group by department...
//	uint16_t did = parameters.getInt("did", 0);
	uint16_t pid = parameters.getInt("pid", 0);
	uint16_t mid = parameters.getInt("mid", 0);

	if (pid == 0) {
		outputError(501, "pid can not be 0(ANY) now");
		return;
	}

	int cpuTotal = 0, cpuCores = 0; std::tr1::unordered_set<int> cpuIds;
	int memory = 0;
	int loadAvg = 0;
	int netAll = 0; std::tr1::unordered_set<int> netIds;
	int diskAll = 0; std::tr1::unordered_set<int> diskIds;

	// step 4.1: parse iids
	const char *strIid = parameters.getString("iid", "all");
	if (strcmp(strIid, "all") == 0) {
		cpuTotal = 1;	// no cpu-cores
		memory = 1;
		loadAvg = 1;
		netAll = 1;
		diskAll = 1;
	}
	else {
		char ss[1024]; 
		strncpy(ss, strIid, sizeof ss); ss[sizeof(ss) - 1] = 0;

		char *endptr, *nptr = strtok_r(ss, MULTIVAL_SEPARATORS, &endptr);
		while (nptr != NULL) {
			if (!strcmp(nptr, "cpu-total")) cpuTotal = 1;
			else if (!strcmp(nptr, "cpu-cores")) cpuCores = 1;
			else if (!strncmp(nptr, "cpu-", 4)) cpuIds.insert(strtol(nptr + 4, NULL, 0));
			else if (!strcmp(nptr, "mem")) memory = 1;
			else if (!strcmp(nptr, "load-avg")) loadAvg = 1;
			else if (!strcmp(nptr, "net-all")) netAll = 1;
			// TODO: mapping net-name to its id
			else if (!strncmp(nptr, "net-", 4)) netIds.insert(strtol(nptr + 4, NULL, 0));
			else if (!strcmp(nptr, "disk-all")) diskAll = 1;
			// TODO: mapping disk-name to its id
			else if (!strncmp(nptr, "disk-", 5)) diskIds.insert(strtol(nptr + 5, NULL, 0));
			else {
				outputError(501, "invalid iid parameter");
				return;
			}

			nptr = strtok_r(NULL, MULTIVAL_SEPARATORS, &endptr);
		}
	}

	// step 4.2: get all possible iids first
	local_key_set_t ids;
	host_set_t hosts;

	// step 4.3: get hosts and mapping iids with hosts
	const char *strHost = parameters.getString("host", "auto");
	if (strcmp(strHost, "auto")) {
		// individual host(s)
		char ss[1024];
		strncpy(ss, strHost, sizeof ss); ss[sizeof(ss) - 1] = 0;

		char *endptr, *nptr = strtok_r(ss, MULTIVAL_SEPARATORS, &endptr);
		while (nptr != NULL) {
			stat_ip_t hip;
			if (inet_pton(AF_INET, nptr, &hip.ip.ip4) == 1) {
				hip.ver = 4; 
			}
			else if (inet_pton(AF_INET6, nptr, &hip.ip.ip6[0]) == 1) {
				hip.ver = 6;
			}
			else {
				outputError(501, "invalid host parameter");
				return;
			}

			hosts.insert(hip);
			nptr = strtok_r(NULL, MULTIVAL_SEPARATORS, &endptr);
		}
	}

	unsigned char buf[8192], rspBuf[8192];
	Memorybuffer msg(buf, sizeof buf, false);
	MemoryBuffer rsp(rspBuf, sizeof rspBuf, false);

	struct proto_h16_head *h = (struct proto_h16_head *)msg.data();
	memset(h, sizeof(*h), 0);
	msg.setWptr(sizeof(*h));

	h->cmd = CMD_STAT_GET_SYSTEM_STATS_REQ;
	h->syn = nextSyn++;
	h->ack = 0;
	h->ver = 1;
	
	msg.writeUint8(context);
	msg.writeUint8(totalView);
	msg.writeInt64(startDtime);
	msg.writeInt64(endDtime);
	msg.writeUint8(spanUnit);
	msg.writeUint8(spanCount);
	msg.writeUint16(pid);
	msg.writeUint16(mid);

	msg.writeUint16(hosts.size());
	for (hosts::iterator iter = hosts.begin(); iter != hosts.end(); ++iter) {
		if (encodeTo(msg, *iter) < 0)
			break;
	}
	
	beyondy::TimedoutCountdown timer(10*1000);
	ClientConnection client(storageAddress, 10*1000, 3);
	if (client.request(&msg, &rsp) < 0) {
		APPLOG_ERROR("request to %s failed: %m", storageAddress);
		return -1;
	}

	struct proto_h16_res *h2 = (struct proto_h16_res *)rsp.data();
	rsp.setRptr(sizeof(*h2));

	if (combiner.parseFrom(&rsp) < 0) {
		APPLOG_ERROR("parse combiner from rsp-msg failed");
		return -1;
	}

	// further merge
	StatCombiner combiner(spanUnit, spanCount, startDtime, mergeCount);
	int gtype = combiner.groupType();

	// output
	printf("Status: 200 OK\r\n");
	printf("Content-Type: application/json\r\n");
	printf("\r\n");

	int64_t spanInterval = spanLength(spanUnit, spanCount);
	int64_t ts = startDtime + spanInterval;
	char buf[128];
	printf("{\"start\":\"%s\"", formatDtime(buf, sizeof buf, ts));
	printf(",\"end\":\"%s\"", formatDtime(buf, sizeof buf, endDtime));
	printf(",\"span\":\"%s\"", formatSpan(buf, sizeof buf, spanUnit, spanCount));
	printf(",\"stats\":[");
	for (int i = 1; i < mergeCount; ++i) {
		
		printf("%s{\"dtime\":\"%s\"", i == 1 ? "" : ",", formatDtime(buf, sizeof buf, ts));
		printf(",\"data\":[");

		bool first = true;
		if (!cpuIds.empty()) {
			outputCpuCombinedGauges(gtype, combiner.mergedGauges[i-1], combiner.mergedGauges[i], first, cpuIds);
		}

		if (memory) {
			outputMemCombinedGauges(gtype, combiner.mergedGauges[i-1], combiner.mergedGauges[i], first);
		}

		if (loadAvg) {
			outputLoadavgCombinedGauges(gtype, combiner.mergedGauges[i-1], combiner.mergedGauges[i], first);
		}

		if (!netIds.empty()) {
			outputNetCombinedGauges(gtype, combiner.mergedGauges[i-1], combiner.mergedGauges[i], first, netIds);
		}

		if (!diskIds.empty()) {
			outputDiskCombinedGauges(gtype, combiner.mergedGauges[i-1], combiner.mergedGauges[i], first, diskIds);
		}

		printf("]}");

		ts += spanInterval;
	}

	printf("]}");
	return;
}
Ejemplo n.º 30
0
static int parseDtimeSpan(QueryParameters& parameters, int64_t& startDtime, int64_t& endDtime, int& spanUnit, int& spanCount)
{
	int lastUnit, lastCount = 0;
	int alignUnit, alignCount, width;
	char *eptr;

	const char *strLast = parameters.getString("last", NULL);
	if (strLast != NULL) {
		endDtime = time(NULL)*1000;
		lastCount = strtol(strLast, &eptr, 0);
		if ((lastUnit = timeUnit(eptr)) == FT_UNKNOWN) {
			outputError(501, "invalid time unit for last parameter");
			return -1;
		}
	}
	else {
		const char *strStart = parameters.getString("start", NULL);
		const char *strEnd = parameters.getString("end", NULL);
		if (strStart == NULL || strEnd == NULL) {
			outputError(501, "No last is provided, neither start/end. one of them must be provifded.");
			return -1;
		}

		startDtime = parseDtime(strStart);
		endDtime = parseDtime(strEnd);
	}

	const char *strSpan = parameters.getString("span", "auto");
	if (!strcmp(strSpan, "auto")) {
		spanCount = 0;
	}
	else {
		 spanCount = strtol(strSpan, &eptr, 0);
		if ((spanUnit = timeUnit(eptr)) == FT_UNKNOWN) {
			outputError(501, "Invalid time unit for span");
			return -1;
		}
	}

	const char *strAlign = parameters.getString("align", "auto");
	if (!strcmp(strAlign, "auto")) {
		alignCount = 0;
	}
	else {
		alignCount = strtol(strAlign, &eptr, 0);
		if ((alignUnit = timeUnit(eptr)) == FT_UNKNOWN) {
			outputError(502, "Invalid time unit for align");
			return -1;
		}
	}

	if ((width = parameters.getInt("width", -1)) == -1) {
		outputError(503, "No width parameter is set");
		return -1;
	}

	if (lastCount > 0) {
		endDtime = time(NULL) * 1000;
		if (alignCount != 0) {
			endDtime = alignTimeUp(endDtime, alignUnit, alignCount);
		}

		switch (lastUnit) {
		case FT_SECOND:
			startDtime = endDtime - lastCount * 1000;
			break;
		case FT_MINUTE:
			startDtime = endDtime - lastCount * 1000 * 60;
			break; 
		case FT_HOUR:
			startDtime = endDtime - lastCount * 1000 * 60 * 60;
			break;
		default:
			outputError(501, "TODO: support more lastUnit");
			return -1;
		}
	}
	else {
		if (alignCount > 0) {
			endDtime = alignTimeUp(endDtime, alignUnit, alignCount);
			startDtime = alignTimeDown(startDtime, alignUnit, alignCount);
		}
	}

	if (spanCount < 1) {
		// automatically determine span
		// at most, one pixel, one point
		int64_t msPerPx = (endDtime - startDtime) / width;
// larger than, unit, count
// { 60 * 60 * 1000, FT_HOUR, -1 },
// { M(30), FT_HOUR, 1 },
// { M(15), FT_MINUTE, 30},
		if (msPerPx > 3600 * 1000) {
			spanUnit = FT_HOUR;
			spanCount = msPerPx / (3600*1000);
		}
		else if (msPerPx > 30 * 60 * 1000) {
			spanUnit = FT_HOUR;
			spanCount = 1;
		}
		else if (msPerPx > 15 * 60 * 1000) {
			spanUnit = FT_MINUTE;
			spanCount = 30;
		}
		else if (msPerPx > 5 * 60 * 1000) {
			spanUnit = FT_MINUTE;
			spanCount = 15;
		}
		else if (msPerPx > 1 * 60 * 1000) {
			spanUnit = FT_MINUTE;
			spanCount = 5;
		}
		else {
			spanUnit = FT_MINUTE;
			spanCount = 1;
		}
				
/*
		if (msPerPx > 3M) {
			spanUnit = FT_YEAR;
			spanCount = UPPER(periodInterval/1Y);
		}
		else if (msPerPx > 1M) {
			spanUnit = FT_QUARTER;
		}
		else if (msPerPx > 7d) {
			spanUnit = FT_MONTH;
		}
		else if (msPerPx > 1d) {
			spanUnit = FT_WEEK;
		}
		> 12h => 1d
		> 8h => 12h
		> 6h => 8h
		> 4h => 6h
		> 3h => 4h
		> 2h => 3h
		> 1h => 2h
		> 30m => 1h
		> 20m => 30m
		> 15m => 20m
		> 10m => 15m
		> 5m => 10m
		> 1m => 5m	
		> 30s => 1m
		> 20s => 30s
		> 15s
		> 10s
		> 5s
		> 1s
		else if (msPerPx > 1H) {
			spanUnit = FT_DAY;
		}
		else if (msPerPx > 1M) {
			spanUnit = FT_HOUR;
		}
		else if (msPerPx > 1s) {
			spanUnit = FT_MINUTE;
		}
		else {
			spanUnit = FT_SECOND;
		}
*/
	}

	// align start/end time with span unit too
	endDtime = alignTimeUp(endDtime, spanUnit, spanCount);
	startDtime = alignTimeDown(startDtime, spanUnit, spanCount);

	return 0;
}