コード例 #1
0
//----------------------------------------------------------------------
// Name         : sortReceive
// 
// Parameters   : ...
//
// Description  : 
//
// Return Value :
//   SORT_SUCCESS if everything goes on well.
//   SORT_FAILURE if any error encounterd. 
//
//----------------------------------------------------------------------
Lng32 SortUtil::sortReceive(void*& record,ULng32& len,void*& tupp)
{
  NABoolean status;
  status = sortAlgo_->sortReceive(record, len, tupp);
  if ((len == 0) && (!config_->partialSort_)) {
    if(scratch_)
     {
      ScratchFileMap* tempFilesMap;
      tempFilesMap = scratch_->getScrFilesMap();
      //stats_.scrNumReads_ = tempFilesMap->totalNumOfReads();
      //stats_.scrNumAwaitio_ = tempFilesMap->totalNumOfAwaitio();      
      scratch_->getTotalIoWaitTime(stats_.ioWaitTime_);    
     }
    stats_.numCompares_ += sortAlgo_->getNumOfCompares();  
    Int64 currentTimeJ = NA_JulianTimestamp();
    stats_.elapsedTime_ = currentTimeJ - stats_.beginSortTime_; 
    if (config_->logInfoEvent()) {
      char msg[500];
      str_sprintf(msg, "Sort elapsed time : %Ld; Num runs : %d; runsize :%d",
		stats_.elapsedTime_,stats_.numInitRuns_,sortAlgo_->getRunSize());
      SQLMXLoggingArea::logExecRtInfo(NULL, 0,msg, explainNodeId_);
    }
  } 
  return status;
}
コード例 #2
0
void CompilationStatsData :: translateToExternalFormat(SQL_COMPILATION_STATS_DATA *query_cmp_data)
{
  query_cmp_data->compileStartTime 
    = compileStartTime();

  query_cmp_data->compileEndTime
    = compileEndTime();

  if ( query_cmp_data->compileEndTime == 0)
    {
      query_cmp_data->compileEndTime = NA_ConvertTimestamp(NA_JulianTimestamp()) ;
    }

  str_cpy_all(query_cmp_data->compilerId,
	      compilerId(),
	      COMPILER_ID_LEN);

  query_cmp_data->cmpCpuTotal
    = cmpCpuTotal();

  query_cmp_data->cmpCpuBinder
    = cmpCpuBinder();

  query_cmp_data->cmpCpuNormalizer
    = cmpCpuNormalizer();

  query_cmp_data->cmpCpuAnalyzer
    = cmpCpuAnalyzer();

  query_cmp_data->cmpCpuOptimizer
    = cmpCpuOptimizer();
  query_cmp_data->cmpCpuGenerator
    = cmpCpuGenerator();

  query_cmp_data->metadataCacheHits
    = metadataCacheHits();

  query_cmp_data->metadataCacheLookups
    = metadataCacheLookups();

  query_cmp_data->queryCacheState
    = queryCacheState();

  query_cmp_data->histogramCacheHits
    = histogramCacheHits();

  query_cmp_data->histogramCacheLookups
    = histogramCacheLookups();

  query_cmp_data->stmtHeapSize
    = stmtHeapSize();

}
コード例 #3
0
void MdamIntervalList::logEvent(const Lng32 functionId,
                                const Lng32 intervalCount,
                                const Int64 otherListId,
                                const Lng32 callerTag) const
{
  Int64 eventTimestamp = NA_JulianTimestamp();

  printf("  %I64i  %I64i  %li  %li  %I64i  %li\n",
    eventTimestamp,
    intervalListId_,
    functionId,
    intervalCount,
    otherListId,
    callerTag);
}
コード例 #4
0
short ExExeUtilTcb::executeQuery(char * task, 
				 char * object,
				 char * query,
				 NABoolean displayStartTime,
				 NABoolean displayEndTime,
				 short &rc,
				 short * warning,
				 Lng32 * ec,
				 NABoolean moveErrorRow,
				 NABoolean continueOnError,
				 NABoolean monitorThis)
{
  short retcode = 0;
  char buf[BUFFER_SIZE];

  while (1)
    {
      switch (pqStep_)
	{
	case PROLOGUE_:
	  {
	    warning_ = 0;
	    startTime_ = NA_JulianTimestamp();
	    elapsedTime_ = 0;
	    if (displayStartTime)
	      {
		getStatusString(task, "Started", object, buf);
		if (moveRowToUpQueue(buf, 0, &rc))
		  return 1;
	      }

	    pqStep_ = EXECUTE_;
	    rc = WORK_RESCHEDULE_AND_RETURN;
	    return 1;
	  }
	  break;
	
	case EXECUTE_:
	  {
	    retcode = cliInterface()->fetchRowsPrologue(query,FALSE,monitorThis);
	    if (retcode < 0)
	      {
		pqStep_ = ERROR_RETURN_;
		break;
	      }
	    
	    pqStep_ = FETCH_ROW_;
	  }
	  break;
	
	case FETCH_ROW_:
	  {
	    retcode = (short)cliInterface()->fetch();
	    if (retcode < 0)
	      {
		pqStep_ = ERROR_RETURN_;
		break;
	      }
	    
	    if ((retcode > 0) &&
		(retcode != 100))
	      warning_ = retcode;

	    if ((retcode != 100) &&
		(cliInterface()->outputBuf()))
	      pqStep_ = RETURN_ROW_;
	    else
	      pqStep_ = CLOSE_;
	  }
	  break;
	
	case RETURN_ROW_:
	  {
	    char * ptr;
	    Lng32   len;
	    
	    cliInterface()->getPtrAndLen(1, ptr, len);
	    retcode = moveRowToUpQueue(ptr, len, &rc);
	    if (retcode)
	      return 1;
	    
	    pqStep_ = FETCH_ROW_;
	  }
	  break;
	
	case CLOSE_:
	  {
	    retcode = cliInterface()->fetchRowsEpilogue("");
	    if (retcode < 0)
	      {
		pqStep_ = ERROR_RETURN_;
		break;
	      }

	    pqStep_ = EPILOGUE_;
	  }
	  break;
	
	case EPILOGUE_:
	  {
            endTime_ = NA_JulianTimestamp();
            elapsedTime_ = endTime_ - startTime_;

	    if (displayEndTime)
	      {
		char timeBuf[200];
		getTimeAsString(elapsedTime_, timeBuf);
		getStatusString(task, "Ended", object, buf, timeBuf);
		if (moveRowToUpQueue(buf, 0, &rc))
		  return 1;
	      }

	    pqStep_ = ALL_DONE_;
	    rc = WORK_RESCHEDULE_AND_RETURN;
	    return 1;
	  }
	  break;
	
	case ERROR_RETURN_:
	  {
	    Lng32 sqlcode = 0;
	    char * stringParam1 = NULL;
	    Lng32   intParam1 = ComDiags_UnInitialized_Int;

	    retcode = (short)cliInterface()->retrieveSQLDiagnostics(getDiagsArea());
	    if (moveErrorRow)
	      {
		if (retcode == 0)
		  {
		    ComDiagsArea * da = getDiagsArea();
		    
		    sqlcode = (short)da->mainSQLCODE();
		    
		    ComCondition * cc;
		    if (sqlcode < 0)
		      cc = da->getErrorEntry(1);
		    else
		      cc = da->getWarningEntry(1);
		    
		    if (sqlcode < 0 && ec != NULL)
		      *ec = sqlcode;
		    
		    if (cc->getOptionalStringCharSet(0) == CharInfo::ISO88591 || cc->getOptionalStringCharSet(0) == CharInfo::UTF8)
		      stringParam1 = (char*)cc->getOptionalString(0);
		    else
		      stringParam1 = NULL;
		    intParam1    = cc->getOptionalInteger(0);
		  }
		else
		  {
		    sqlcode = retcode;
		  }
		
	 Lng32 errorBufLen = 
		  200 + (stringParam1 ? strlen(stringParam1) : 0);
		
		char * errorBuf = new(getHeap()) char[errorBufLen];
		
		str_sprintf(errorBuf, "%d", sqlcode);
		if (stringParam1)
		  str_sprintf(&errorBuf[strlen(errorBuf)], ", %s", stringParam1);
		if (intParam1 != ComDiags_UnInitialized_Int)
		  str_sprintf(&errorBuf[strlen(errorBuf)], ", %d", intParam1);
		
		char * outBuf = new(getHeap()) char[errorBufLen+400];
		getStatusString(task, "Error", NULL, outBuf,
				NULL, NULL,
				errorBuf);
		
		NADELETEBASIC(errorBuf, getHeap());
		
		if ((moveErrorRow) &&
		    (moveRowToUpQueue(outBuf, 0, &rc)))
		  {
		    NADELETEBASIC(outBuf, getHeap());
		    
		    return 1;
		  }

		NADELETEBASIC(outBuf, getHeap());
	      }

	    // close cursor, etc. Ignore errors.
	    cliInterface()->fetchRowsEpilogue("");

	    if (continueOnError)
	      {
		pqStep_ = ALL_DONE_;

		rc = WORK_RESCHEDULE_AND_RETURN;
		return 1;
	      }
	    else
	      {
		pqStep_ = PROLOGUE_;
		return -1;
	      }
	  }
	  break;

	case ALL_DONE_:
	  {
	    pqStep_ = PROLOGUE_;

	    if (warning)
	      *warning = warning_;

	    return 0;
	  }
	  break;
	
	}
    }
}
コード例 #5
0
ex_expr::exp_return_type ExpLOBiud::insertDesc(char *op_data[],
					       CollHeap*h,
					       ComDiagsArea** diagsArea)
{
  Lng32 rc;

  Lng32 lobOperStatus = checkLobOperStatus();
  if (lobOperStatus == DO_NOTHING_)
    return ex_expr::EXPR_OK;

  char * result = op_data[0];

  // get the lob name where data need to be inserted
  char tgtLobNameBuf[100];
  char * tgtLobName = ExpGetLOBname(objectUID_, lobNum(), tgtLobNameBuf, 100);

  if (tgtLobName == NULL)
    return ex_expr::EXPR_ERROR;

  // call function with the lobname and source value
  // to insert it in the LOB.
  // Get back offset and len of the LOB.
  Int64 descSyskey = 0;

  char * lobHandle = NULL;
  Lng32 handleLen = 0;
  char lobHandleBuf[LOB_HANDLE_LEN];
  //  if (getExeGlobals()->lobGlobals()->getCurrLobOperInProgress())
  if (lobOperStatus == CHECK_STATUS_)
    {
      lobHandle = lobHandleSaved_;
      handleLen = lobHandleLenSaved_;
    }
  else
    {
      Int64 descTS = NA_JulianTimestamp();

      lobHandle = lobHandleBuf;
      ExpLOBoper::genLOBhandle(objectUID_, lobNum(), (short)lobStorageType(),
			       -1, descTS, -1,
			       descSchNameLen_, descSchName(),
			       handleLen, lobHandle);
    }

  LobsSubOper so = Lob_None;
  if (fromFile())
    so = Lob_File;
  else if (fromString() || fromLoad())
    so = Lob_Memory;
  else if (fromLob())
    so = Lob_Foreign_Lob;
  else if (fromBuffer())
    so = Lob_Buffer;

  

  Lng32 waitedOp = 0;
#ifdef __EID
  waitedOp = 0; // nowaited op from EID/TSE process
#else
  waitedOp = 1;
#endif

  //temptemp. Remove after ExLobsOper adds nowaited support.
  waitedOp = 1;

  // temp. Pass lobLen. When ExLobsOper fixes it so len is not needed during
  // lob desc update, then remove this.
  Int64 lobLen = getOperand(1)->getLength();

  blackBoxLen_ = 0;
  if (fromExternal())
    {
      blackBoxLen_ = getOperand(1)->getLength();
      str_cpy_and_null(blackBox_, op_data[1], (Lng32)blackBoxLen_,
		       '\0', ' ', TRUE);
    }

  Lng32 cliError = 0;
  char * lobData = NULL;
  lobData= new(h) char[lobLen];
  //send lobData only if it's a lob_file operation
  if (so == Lob_File)
    {
      str_cpy_and_null(lobData,op_data[1],lobLen,'\0',' ',TRUE);
      
    }
  if (so == Lob_Buffer)
    {
      memcpy(&lobLen, op_data[2],sizeof(Int64));
    }
  LobsOper lo ;
 
  if (lobOperStatus == CHECK_STATUS_)
    lo = Lob_Check_Status;
  else if (lobHandle == NULL)       
    lo = Lob_InsertDataSimple;
  else
    lo = Lob_InsertDesc;
  
    
  rc = ExpLOBInterfaceInsert
    (getExeGlobals()->lobGlobal(), 
     tgtLobName, 
     lobStorageLocation(),
     lobStorageType(),
     getLobHdfsServer(), getLobHdfsPort(),

     handleLen, lobHandle,
     &outHandleLen_, outLobHandle_,
     blackBoxLen_, blackBox_,
     requestTag_,
     getExeGlobals()->lobGlobals()->xnId(),
     descSyskey,
     lo,
     &cliError,
     so,
     waitedOp,
     lobData, lobLen, getLobMaxSize(), getLobMaxChunkMemSize(),getLobGCLimit());
  
  if (rc == LOB_ACCESS_PREEMPT)
    {
      // save the handle so it could be used after return from preempt
      lobHandleLenSaved_ = handleLen;
      str_cpy_all(lobHandleSaved_, lobHandle, handleLen);
      
      return ex_expr::EXPR_PREEMPT;
    }

  if (rc < 0)
    {
      Lng32 intParam1 = -rc;
      ExRaiseSqlError(h, diagsArea, 
		      (ExeErrorCode)(8442), NULL, &intParam1, 
		      &cliError, NULL, (char*)"ExpLOBInterfaceInsert",
		      getLobErrStr(intParam1));
      return ex_expr::EXPR_ERROR;
    }

  // extract and update lob handle with the returned values
  if (outHandleLen_ > 0)
    {
      ExpLOBoper::extractFromLOBhandle(NULL, NULL, NULL, NULL, &descSyskey,
				       NULL, NULL, NULL, outLobHandle_);
      
      ExpLOBoper::updLOBhandle(descSyskey, 0, lobHandle); 
    }

  str_cpy_all(result, lobHandle, handleLen);

  getOperand(0)->setVarLength(handleLen, op_data[-MAX_OPERANDS]);

  if (NOT fromExternal())
    {
      getExeGlobals()->lobGlobals()->lobLoadInfo()->
	setLobHandle(lobNum(), handleLen, lobHandle);
    }

  return ex_expr::EXPR_OK;
}
コード例 #6
0
// *****************************************************************************
// *                                                                           *
// * Function: CmpSeabaseDDL::addSchemaObject                                  *
// *                                                                           *
// *    Inserts a schema object row into the OBJECTS table.                    *
// *                                                                           *
// *****************************************************************************
// *                                                                           *
// *  Parameters:                                                              *
// *                                                                           *
// *  <cliInterface>                  ExeCliInterface &               In       *
// *    is a reference to an Executor CLI interface handle.                    *
// *                                                                           *
// *  <schemaName>                    const ComSchemaName &           In       *
// *    is a reference to a ComSchemaName instance.  The catalog name must be  *
// *  set.                                                                     *
// *                                                                           *
// *  <schemaClass>                   ComSchemaClass                  In       *
// *    is the class (private or shared) of the schema to be added.            *
// *                                                                           *
// *  <ownerID>                       Int32                           In       *
// *    is the authorization ID that will own the schema.                      *
// *                                                                           *
// *  <ignoreIfExists>                NABoolean                       In       *
// *    do not return an error is schema already exists                        *
// *****************************************************************************
// *                                                                           *
// * Returns: PrivStatus                                                       *
// *                                                                           *
// *   0: Schema as added                                                      *
// *  -1: Schema was not added.  A CLI error is put into the diags area.       *
// *                                                                           *
// *****************************************************************************
int CmpSeabaseDDL::addSchemaObject(
   ExeCliInterface & cliInterface,
   const ComSchemaName & schemaName,
   ComSchemaClass schemaClass,
   Int32 ownerID,
   NABoolean ignoreIfExists)
   
{

NAString catalogName = schemaName.getCatalogNamePartAsAnsiString();
ComAnsiNamePart schemaNameAsComAnsi = schemaName.getSchemaNamePart();
NAString schemaNamePart = schemaNameAsComAnsi.getInternalName();

ComObjectName objName(catalogName,schemaNamePart,NAString(SEABASE_SCHEMA_OBJECTNAME), 
                      COM_TABLE_NAME,TRUE);
                      
   if (isSeabaseReservedSchema(objName) &&
       !Get_SqlParser_Flags(INTERNAL_QUERY_FROM_EXEUTIL))
   {
      *CmpCommon::diags() << DgSqlCode(-CAT_RESERVED_METADATA_SCHEMA_NAME)
                          << DgSchemaName(schemaName.getExternalName().data());
      return -1;
   }
                      
NAString objectNamePart = objName.getObjectNamePartAsAnsiString(TRUE);

Lng32 retcode = existsInSeabaseMDTable(&cliInterface,catalogName,schemaNamePart, 
                                       objectNamePart, COM_UNKNOWN_OBJECT, FALSE);
   if (retcode < 0)
      return -1;
  
   if (retcode == 1 ) // already exists
   {
      if (ignoreIfExists)
        return 0;
      else
        *CmpCommon::diags() << DgSqlCode(-CAT_SCHEMA_ALREADY_EXISTS)
                            << DgSchemaName(schemaName.getExternalName().data());
      return -1;
   }

char buf[4000];

ComUID schemaUID;

   schemaUID.make_UID();
   
Int64 schemaObjectUID = schemaUID.get_value();
  
Int64 createTime = NA_JulianTimestamp();

NAString quotedSchName;
NAString quotedObjName;

   ToQuotedString(quotedSchName,schemaNamePart,FALSE);
   ToQuotedString(quotedObjName,NAString(SEABASE_SCHEMA_OBJECTNAME),FALSE);

char schemaObjectLit[3] = {0};
   
   switch (schemaClass)
   {
      case COM_SCHEMA_CLASS_PRIVATE:
      {
         strncpy(schemaObjectLit,COM_PRIVATE_SCHEMA_OBJECT_LIT,2);
         break;
      }
      case COM_SCHEMA_CLASS_SHARED:
      {
         strncpy(schemaObjectLit,COM_SHARED_SCHEMA_OBJECT_LIT,2);
         break;
      }
      case COM_SCHEMA_CLASS_DEFAULT:
      default:
      {
         // Schemas are private by default, but could choose a different
         // default class here based on CQD or other attribute.
         strncpy(schemaObjectLit,COM_PRIVATE_SCHEMA_OBJECT_LIT,2);
         break;
      } 
   }
   
   str_sprintf(buf, "insert into %s.\"%s\".%s values ('%s', '%s', '%s', '%s', %Ld, %Ld, %Ld, '%s', '%s', %d, %d, 0)",
               getSystemCatalog(),SEABASE_MD_SCHEMA,SEABASE_OBJECTS,
               catalogName.data(), quotedSchName.data(), quotedObjName.data(),
               schemaObjectLit,
               schemaObjectUID,
               createTime, 
               createTime,
               COM_YES_LIT, // valid_def
               COM_NO_LIT,  // droppable
               ownerID,ownerID);
               
Int32 cliRC = cliInterface.executeImmediate(buf);
   
   if (cliRC < 0)
   {
      cliInterface.retrieveSQLDiagnostics(CmpCommon::diags());
      return -1;
   }

   return 0;

}
コード例 #7
0
MdamIntervalList::MdamIntervalList(const Lng32 callerTag)
         : firstIntervalPtr_(0), lastIntervalPtr_(0),
           intervalListId_(NA_JulianTimestamp())
{
  logEvent(5,0,-1,callerTag);
}
コード例 #8
0
// ----------------------------------------------------------------------------
// Method: registerUser
//
// registers a user in the Trafodion metadata
//
// Input:  parse tree containing a definition of the user
// Output: the global diags area is set up with the result
// ----------------------------------------------------------------------------
void CmpSeabaseDDLuser::registerUser(StmtDDLRegisterUser * pNode)
{
  // Set up a global try/catch loop to catch unexpected errors
  try
  {
    // Verify user is authorized

    verifyAuthority();

    // Verify that the specified user name is not reserved
    // TBD - add the isCatman concept
    if (isAuthNameReserved(pNode->getDbUserName()))
    {
      *CmpCommon::diags() << DgSqlCode (-CAT_AUTH_NAME_RESERVED)
                          << DgString0(pNode->getDbUserName().data());
      DDLException excp (CAT_AUTH_NAME_RESERVED, NULL, 0);
      excp.throwException();
    }


    // set up class members from parse node
    setAuthDbName(pNode->getDbUserName());
    setAuthExtName(pNode->getExternalUserName());
    setAuthImmutable(pNode->isImmutable());
    setAuthType(COM_USER_CLASS);  // we are a user
    setAuthValid(true); // assume a valid user

    Int64 createTime = NA_JulianTimestamp();
    setAuthCreateTime(createTime);
    setAuthRedefTime(createTime);  // make redef time the same as create time

    // Make sure db user has not already been registered
    if (authExists())
    {
      *CmpCommon::diags() << DgSqlCode(-CAT_AUTHID_ALREADY_EXISTS)
                          << DgString0(getAuthDbName().data());
      DDLException excp (CAT_AUTHID_ALREADY_EXISTS, NULL, 0);
      excp.throwException();
    }

    // Make sure external user has not already been registered
    if (authExists(true))
    {
      *CmpCommon::diags() << DgSqlCode(-CAT_LDAP_USER_ALREADY_EXISTS)
                          << DgString0(getAuthExtName().data());
      DDLException excp (CAT_LDAP_USER_ALREADY_EXISTS, NULL, 0);
      excp.throwException();
    }

DBUserAuth::AuthenticationConfiguration configurationNumber = DBUserAuth::DefaultConfiguration;
DBUserAuth::AuthenticationConfiguration foundConfigurationNumber = DBUserAuth::DefaultConfiguration;

    if (!validateExternalUsername(pNode->getExternalUserName().data(),
                                  configurationNumber,
                                  foundConfigurationNumber))
       return;

    // Get a unique auth ID number
    // TBD - check a parserflag (or something) to add DB__ROOT
    Int32 userID = 0;
    if (getAuthDbName() == DB__ROOT)
      userID = SUPER_USER;
    else
      userID = getUniqueUserID();

    setAuthID (userID);

    // If the BY clause was specified, then register the user on behalf of the
    // authorization ID specified in this clause.
    // Need to translate the creator name to its authID
    if (pNode->getOwner() == NULL)
    {
      // get effective user from the Context
      // TBD - replace this call with SQL_EXEC_ call
      Int32 *pUserID = GetCliGlobals()->currContext()->getDatabaseUserID();
      setAuthCreator(*pUserID);
    }
    else
    {
      const NAString creatorName =
        pNode->getOwner()->getAuthorizationIdentifier();
      // TBD: get the authID for the creatorName
      // TBD: verify creator can register users
      setAuthCreator(NA_UserIdDefault);
    }

    // Add the user to AUTHS table
    insertRow();
  }
  catch (...)
  {
    // At this time, an error should be in the diags area.
    // If there is no error, set up an internal error
    Int32 numErrors = CmpCommon::diags()->getNumber(DgSqlCode::ERROR_);
    if (numErrors == 0)
      *CmpCommon::diags() << DgSqlCode (-CAT_INTERNAL_EXCEPTION_ERROR)
                          << DgInt0(__LINE__)
                          << DgString0("register user");

  }
}
コード例 #9
0
ExWorkProcRetcode ExCancelTcb::work()
{

  ExMasterStmtGlobals *masterGlobals = 
     getGlobals()->castToExExeStmtGlobals()->castToExMasterStmtGlobals();

  CliGlobals *cliGlobals = masterGlobals->getCliGlobals();

  while ((qparent_.down->isEmpty() == FALSE) && 
         (qparent_.up->isFull() == FALSE))
  {
    ex_queue_entry *pentry_down = qparent_.down->getHeadEntry();
  
    switch (step_)
    {
      case NOT_STARTED:
      {
        if (pentry_down->downState.request == ex_queue::GET_NOMORE)
          step_ = DONE;
        else
        {
          retryCount_ = 0;
          // Priv checking is done during compilation. To support 
          // REVOKE, prevent a prepared CANCEL/SUSPEND/ACTIVATE
          // that was compiled more than 1 second ago from executing 
          // by raising the 8734 error to force an AQR. 
          Int64 microSecondsSinceCompile = NA_JulianTimestamp() - 
              masterGlobals->getStatement()->getCompileEndTime();

          if (microSecondsSinceCompile > 1000*1000)
          {

            ComDiagsArea *diagsArea =
              ComDiagsArea::allocate(getGlobals()->getDefaultHeap());
            *diagsArea << DgSqlCode(-CLI_INVALID_QUERY_PRIVS);
            reportError(diagsArea);
            step_ = DONE;
            break;
          }
          
          // Figure out which MXSSMP broker to use.
          if (cancelTdb().getAction() == ComTdbCancel::CancelByPname)
          {
            int nid = -1;
            int rc = msg_mon_get_process_info(cancelTdb().getCancelPname(),
                                &nid, &pid_);
            switch (rc)
            {
              case XZFIL_ERR_OK:
                cpu_ = (short) nid;
                break;
              case XZFIL_ERR_NOTFOUND:
              case XZFIL_ERR_BADNAME:
              case XZFIL_ERR_NOSUCHDEV:
                {
                  ComDiagsArea *diagsArea =
                    ComDiagsArea::allocate(getGlobals()->getDefaultHeap());

                  *diagsArea << DgSqlCode(-EXE_CANCEL_PROCESS_NOT_FOUND);
                  *diagsArea << DgString0(cancelTdb().getCancelPname());
                  reportError(diagsArea);

                  step_ = DONE;
                  break;
                }
              default:
                {
                  char buf[200];
                  str_sprintf(buf, "Unexpected error %d returned from "
                                   "msg_mon_get_process_info", rc);
                  ex_assert(0, buf);
                }
            }
            if (step_ != NOT_STARTED)
              break;
          }
          else if  (cancelTdb().getAction() == ComTdbCancel::CancelByNidPid)
          {
            cpu_ = (short) cancelTdb().getCancelNid();
            pid_ = cancelTdb().getCancelPid();

            // check that process exists, if not report error.
            char processName[MS_MON_MAX_PROCESS_NAME];
            int rc = msg_mon_get_process_name(cpu_, pid_, processName);
            if (XZFIL_ERR_OK == rc)
              ; // good. nid & pid are valid.
            else
            {
              if ((XZFIL_ERR_NOTFOUND  != rc) &&
                  (XZFIL_ERR_BADNAME   != rc) &&
                  (XZFIL_ERR_NOSUCHDEV != rc))
              {
                // Log rc in case it needs investigation later.
               char buf[200];
               str_sprintf(buf, "Unexpected error %d returned from "
                                "msg_mon_get_process_name", rc);
               SQLMXLoggingArea::logExecRtInfo(__FILE__, __LINE__,
                                               buf, 0);
              }
              char nid_pid_str[32];
              str_sprintf(nid_pid_str, "%d, %d", cpu_, pid_);
              ComDiagsArea *diagsArea =
                    ComDiagsArea::allocate(getGlobals()->getDefaultHeap());

              *diagsArea << DgSqlCode(-EXE_CANCEL_PROCESS_NOT_FOUND);
              *diagsArea << DgString0(nid_pid_str);
              reportError(diagsArea);

              step_ = DONE;
              break;
            }
          }
          else
          {
            char * qid = cancelTdb().qid_;
            Lng32 qid_len = str_len(qid);

            // This static method is defined in SqlStats.cpp.  It side-effects
            // the nodeName and cpu_ according to the input qid.
            if (getMasterCpu(
                  qid, qid_len, nodeName_, sizeof(nodeName_) - 1, cpu_) == -1)
            {
              ComDiagsArea *diagsArea =
                ComDiagsArea::allocate(getGlobals()->getDefaultHeap());

              *diagsArea << DgSqlCode(-EXE_RTS_INVALID_QID);

              reportError(diagsArea);

              step_ = DONE;
              break;
            }
          }

          // Testpoints for hard to reproduce problems:
          bool fakeError8028 = false;
          fakeError8028 = (getenv("HP_FAKE_ERROR_8028") != NULL);
          if ((cliGlobals->getCbServerClass() == NULL) || fakeError8028)
          {
            ComDiagsArea *diagsArea = 
              ComDiagsArea::allocate(getGlobals()->getDefaultHeap());

            *diagsArea << DgSqlCode(-EXE_CANCEL_PROCESS_NOT_FOUND);
            *diagsArea << DgString0("$ZSM000");

            reportError(diagsArea);

            step_ = DONE;
            break;
          }

          ComDiagsArea *diagsArea = NULL;
          bool fakeError2024 = false;
          fakeError2024 = (getenv("HP_FAKE_ERROR_2024") != NULL);
        
          if (fakeError2024)
          {
            cbServer_ = NULL;
            diagsArea =
                  ComDiagsArea::allocate(getGlobals()->getDefaultHeap());
            if (getenv("HP_FAKE_ERROR_8142"))
            {
               *diagsArea << DgSqlCode(-8142);
               *diagsArea << DgString0(__FILE__);
               *diagsArea << DgString1("cbServer_ is NULL");
            }
            else
               *diagsArea << DgSqlCode(-2024);
          }
          else
            cbServer_ = cliGlobals->getCbServerClass()->allocateServerProcess(
                      &diagsArea, 
                      cliGlobals->getEnvironment()->getHeap(),
                      nodeName_,
                      cpu_,
                      IPC_PRIORITY_DONT_CARE,
                      FALSE,  // usesTransactions 
                      TRUE,   // waitedCreation
                      2       // maxNowaitRequests -- cancel+(1 extra).
                      );


          if (cbServer_ == NULL || cbServer_->getControlConnection() == NULL)
          {
            ex_assert(diagsArea != NULL, 
                      "allocateServerProcess failed, but no diags");

            // look for SQLCode 2024 
            // "*** ERROR[2024] Server Process $0~string0 
            // is not running or could not be created. Operating System 
            // Error $1~int0 was returned."
            // Remap to cancel-specfic error 8028.
            if (diagsArea->contains(-2024)  &&
                cancelTdb().actionIsCancel())
            {
              diagsArea->deleteError(diagsArea->returnIndex(-2024));
              reportError(diagsArea, true, EXE_CANCEL_PROCESS_NOT_FOUND, 
                          nodeName_, cpu_);
            }
            else
              reportError(diagsArea);

            step_ = DONE;
            break;
          }

          // the reportError method was not called -- see break above.
          if (diagsArea != NULL)
            diagsArea->decrRefCount();

          //Create the stream on the IpcHeap, since we don't dispose 
          // of it immediately.  We just add it to the list of completed 
          // messages in the IpcEnv, and it is disposed of later.

          cancelStream_  = new (cliGlobals->getIpcHeap())
                CancelMsgStream(cliGlobals->getEnvironment(), this);

          cancelStream_->addRecipient(cbServer_->getControlConnection());

        }

        step_ = SEND_MESSAGE;

        break;
      }  // end case NOT_STARTED

#pragma warning (disable : 4291)

      case SEND_MESSAGE:
      {
        RtsHandle rtsHandle = (RtsHandle) this;

        if (cancelTdb().actionIsCancel())
        {
          Int64 cancelStartTime = JULIANTIMESTAMP();

          Lng32 firstEscalationInterval = cliGlobals->currContext()->
                    getSessionDefaults()->getCancelEscalationInterval();

          Lng32 secondEscalationInterval = cliGlobals->currContext()->
                    getSessionDefaults()->getCancelEscalationMxosrvrInterval();

          NABoolean cancelEscalationSaveabend = cliGlobals->currContext()->
                    getSessionDefaults()->getCancelEscalationSaveabend();

          bool cancelLogging = (TRUE == cliGlobals->currContext()->
                    getSessionDefaults()->getCancelLogging());

          CancelQueryRequest *cancelMsg = new (cliGlobals->getIpcHeap()) 
            CancelQueryRequest(rtsHandle, cliGlobals->getIpcHeap(), 
                      cancelStartTime,
                      firstEscalationInterval,
                      secondEscalationInterval,
                      cancelEscalationSaveabend,
                      cancelTdb().getCommentText(),
                      str_len(cancelTdb().getCommentText()),
                      cancelLogging,
                      cancelTdb().action_ != ComTdbCancel::CancelByQid,
                      pid_,
                      cancelTdb().getCancelPidBlockThreshold());

#pragma warning (default : 4291)

          *cancelStream_ << *cancelMsg;

          cancelMsg->decrRefCount();
        }
        else if (ComTdbCancel::Suspend == cancelTdb().action_)
        {

          bool suspendLogging = (TRUE == cliGlobals->currContext()->
                    getSessionDefaults()->getSuspendLogging());

#pragma warning (disable : 4291)
          SuspendQueryRequest * suspendMsg = new (cliGlobals->getIpcHeap()) 
            SuspendQueryRequest(rtsHandle, cliGlobals->getIpcHeap(),
                                ComTdbCancel::Force ==
                                cancelTdb().forced_,
                                suspendLogging);
#pragma warning (default : 4291)

          *cancelStream_ << *suspendMsg;

          suspendMsg->decrRefCount();
        }
        else
        {
          ex_assert(
            ComTdbCancel::Activate == cancelTdb().action_,
            "invalid action for ExCancelTcb");

          bool suspendLogging = (TRUE == cliGlobals->currContext()->
                    getSessionDefaults()->getSuspendLogging());

#pragma warning (disable : 4291)
          ActivateQueryRequest * activateMsg = new (cliGlobals->getIpcHeap()) 
            ActivateQueryRequest(rtsHandle, cliGlobals->getIpcHeap(),
                                 suspendLogging);
#pragma warning (default : 4291)

          *cancelStream_ << *activateMsg;

          activateMsg->decrRefCount();
        }

        if ((cancelTdb().getAction() != ComTdbCancel::CancelByPname) &&
            (cancelTdb().getAction() != ComTdbCancel::CancelByNidPid))
        {
          char * qid = cancelTdb().qid_;
          Lng32 qid_len = str_len(qid);

#pragma warning (disable : 4291)
          RtsQueryId *rtsQueryId = new (cliGlobals->getIpcHeap())
                           RtsQueryId( cliGlobals->getIpcHeap(), qid, qid_len);
#pragma warning (default : 4291)

          *cancelStream_ << *rtsQueryId;
          rtsQueryId->decrRefCount();
        }

        // send a no-wait request to the cancel broker.
        cancelStream_->send(FALSE);

        step_ = GET_REPLY;    
        // Come back when I/O completes.
        return WORK_OK; 

        break;
      }  // end case SEND_MESSAGE

      case GET_REPLY:
      {

        // Handle general IPC error.
        bool fakeError201 = false;
        fakeError201 = (getenv("HP_FAKE_ERROR_201") != NULL);
        if ((cbServer_->getControlConnection()->getErrorInfo() != 0) ||
            fakeError201)
        {
          ComDiagsArea *diagsArea = 
            ComDiagsArea::allocate(getGlobals()->getDefaultHeap());

          cbServer_->getControlConnection()->
              populateDiagsArea( diagsArea, getGlobals()->getDefaultHeap());

          if (fakeError201)
          {
            *diagsArea << DgSqlCode(-2034) << DgInt0(201)
                       << DgString0("I say") << DgString1("control broker");
          }

          if (diagsArea->contains(-8921))
          {
            // Should not get timeout error 8921. Get a core-file
            // of the SSMP and this process too so that this can be
            // debugged.
            cbServer_->getControlConnection()->
              dumpAndStopOtherEnd(true, false);
            genLinuxCorefile("Unexpected timeout error");
          }

          reportError(diagsArea);

          step_ = DONE;
          break;
        }

        // See if stream has the reply yet.
        if (!cancelStream_->moreObjects())
          return WORK_OK; 

#pragma warning (disable : 4291)

        ControlQueryReply *reply = new (cliGlobals->getIpcHeap()) 
              ControlQueryReply(INVALID_RTS_HANDLE, cliGlobals->getIpcHeap());

#pragma warning (default : 4291)

        *cancelStream_ >> *reply;

        if (reply->didAttemptControl())
        {
          // yeaah!
          cancelStream_->clearAllObjects();
        }
        else
        {
          if (cancelStream_->moreObjects() &&
              cancelStream_->getNextObjType() == IPC_SQL_DIAG_AREA)
          {
            ComDiagsArea *diagsArea = 
              ComDiagsArea::allocate(getGlobals()->getDefaultHeap());

            *cancelStream_ >> *diagsArea;
            cancelStream_->clearAllObjects();

            if ( retryQidNotActive_ &&
                (diagsArea->mainSQLCODE() == -EXE_SUSPEND_QID_NOT_ACTIVE) &&
                (++retryCount_ <= 60))
            {
              SQLMXLoggingArea::logExecRtInfo(__FILE__, __LINE__, 
                                             "Retrying error 8672.", 0);
              DELAY(500);
              diagsArea->decrRefCount();
              step_ = SEND_MESSAGE;
              break;
            }

            reportError(diagsArea);
          }
          else 
            ex_assert(0, "Control failed, but no diagnostics.");
        }

        step_ = DONE;
        break;
      }
      case DONE: 
      {
        if (cancelStream_)
        {
          cancelStream_->addToCompletedList();
          cancelStream_ = NULL;
        }
        if (cbServer_)
        {
          cbServer_->release();
          cbServer_ = NULL;
        }

        ex_queue_entry * up_entry = qparent_.up->getTailEntry();
        up_entry->copyAtp(pentry_down);
        up_entry->upState.parentIndex = pentry_down->downState.parentIndex;
        up_entry->upState.downIndex = qparent_.down->getHeadIndex();     
        up_entry->upState.setMatchNo(1);
        up_entry->upState.status = ex_queue::Q_NO_DATA;
        qparent_.up->insert();

        qparent_.down->removeHead();

        step_ = NOT_STARTED;
        break;
      }
      default:
        ex_assert( 0, "Unknown step_.");
    }