void timeStamp(ClCharT timeStr [], ClUint32T    len)
{
    time_t  timer ;
    struct  tm *t = NULL;
    ClCharT * pBuff =NULL;

   struct tm *localtimebuf = clHeapAllocate(sizeof(struct tm));;
   if(localtimebuf == NULL)
   {
      CL_DEBUG_PRINT(CL_DEBUG_ERROR,( "\nMemory Allocation failed\n"));
      return ;
   }
   ClCharT *asctimebuf   = clHeapAllocate(BUFFER_LENGTH*sizeof(ClCharT));
   if(asctimebuf == NULL)
   {
      CL_DEBUG_PRINT(CL_DEBUG_ERROR,( "\nMemory Allocation failed\n"));
      return ;
   }

   memset(&timer,0,sizeof(time_t));
    time(&timer);
    t = localtime_r(&timer,localtimebuf);
    pBuff=asctime_r(t,asctimebuf);
    strncpy(timeStr,pBuff,len-1);
    timeStr[strlen(timeStr) - 1] ='\0';
	clHeapFree(localtimebuf);
	clHeapFree(asctimebuf);
}
ClRcT clSnmpnameTableIndexTlvGet(ClPtrT pIndexInfo, ClAlarmUtilTlvInfoPtrT pTlvList)
{
    ClAlarmUtilTlvT * pTlv = NULL;
    ClSnmpnameTableIndexInfoT * pnameTableIndex = (ClSnmpnameTableIndexInfoT *)pIndexInfo;

    if(!pIndexInfo || !pTlvList)
    {
        CL_DEBUG_PRINT(CL_DEBUG_ERROR, ("NULL arguments received!"));
        return CL_ERR_NULL_POINTER;
    }
    pTlvList->pTlv = (ClAlarmUtilTlvT *) clHeapAllocate (1 * sizeof (ClAlarmUtilTlvT));
    if (pTlvList->pTlv == NULL)
    {
        clLog(CL_LOG_ERROR, CL_SNMP_AREA, CL_SNMP_GEN_OP_COTX, "nameTableIndexTlvGet unable to allocate memory!");
        return (CL_ERR_NO_MEMORY);
    }
    pTlvList->numTlvs = 1;

    pTlv = pTlvList->pTlv + 0;
    pTlv->value = clHeapAllocate (sizeof (ClUint32T));
    if (pTlv->value == NULL)
    {
        clHeapFree(pTlvList->pTlv);
        return (CL_ERR_NO_MEMORY);
    }
    memcpy(pTlv->value, &(pnameTableIndex->nodeAdd), sizeof (ClUint32T));
    pTlv->length = sizeof (ClUint32T);
    pTlv->type = CL_COR_UINT32;
    return CL_OK;
}
/*
 * This Api is used for packaging the fault structure
 * on query from the debug prompt
 */
ClRcT 
clFaultRecordPack(ClFaultRecordPtr hRec,ClCharT** retStr){

	ClUint32T categoryStringIndex=0,severityStringIndex=0,probableCauseStringIndex=0;
	
    if(hRec->seqNum==0)
    {
        clFaultCliStrPrint(retStr, "no record found");
    }
    else
    {
        ClCharT *str1 = NULL;
        ClCharT *tmp = NULL;


        str1 = clHeapAllocate(2000);/* The allocation size is a close indication
                                       of the number of bytes used to store the
                                       fault record structure */	   
        if(!str1)
            return CL_FAULT_RC(CL_ERR_NO_MEMORY);

        tmp = clHeapAllocate(2000);/* The allocatino size is a close measure of
                                      the number of bytes used to store each 
                                      attribute of a fault record structure 
                                      attached with a meaningful message
                                      preceeding it */
        if(!tmp)
            return CL_FAULT_RC(CL_ERR_NO_MEMORY);

        sprintf (tmp,"existing record found\n");
        strcat(str1,tmp);

        categoryStringIndex = clFaultInternal2CategoryTranslate((hRec->event).category);
        sprintf (tmp," Category........... %s\n",clFaultCategoryString[categoryStringIndex]);
        strcat(str1,tmp);

        sprintf (tmp," SpecificProblem.... %d\n",(hRec->event).specificProblem);
        strcat(str1,tmp);

        severityStringIndex = clFaultInternal2SeverityTranslate((hRec->event).severity);
        sprintf (tmp," Severity........... %s\n",clFaultSeverityString[severityStringIndex]);
        strcat(str1,tmp);

        if((hRec->event).cause >= CL_ALARM_PROB_CAUSE_LOSS_OF_SIGNAL &&
               (hRec->event).cause <= CL_ALARM_PROB_CAUSE_ENCLOSURE_DOOR_OPEN)
            probableCauseStringIndex = (hRec->event).cause;
        sprintf (tmp," cause.............. %s\n",clFaultProbableCauseString[probableCauseStringIndex]);
        strcat(str1,tmp);

        sprintf (tmp," SequenceNumber..... %d\n",(hRec->seqNum)-1);
        strcat(str1,tmp);
        clFaultCliStrPrint(retStr, str1);
        clHeapFree(str1);
        clHeapFree(tmp);
    }
	return CL_OK;
}
/*
 * The cnt add function
 * The information is read from COR and then populated in the container
 * This api would be called as and when the object is created and the corresponding entry 
 * within the container needs to be added.
 */
ClRcT clAlarmPayloadCntAdd(ClAlarmInfoT *pAlarmInfo)
{
	ClRcT rc = CL_OK;
	ClCntNodeHandleT nodeH;
    ClAlarmPayloadCntT *payloadInfo;
    
    ClAlarmPayloadCntKeyT *pCntKey = clHeapAllocate(sizeof(ClAlarmPayloadCntKeyT));
    if(NULL == pCntKey)
    {
          CL_DEBUG_PRINT (CL_DEBUG_CRITICAL,("Memory allocation failed with rc 0x%x ", rc));
          return CL_ALARM_RC(CL_ALARM_ERR_NO_MEMORY);
    }    

    payloadInfo = NULL;
    pCntKey->probCause = pAlarmInfo->probCause;
    pCntKey->specificProblem = pAlarmInfo->specificProblem;
    pCntKey->moId = pAlarmInfo->moId;

    payloadInfo = clHeapAllocate(sizeof(ClAlarmPayloadCntT)+pAlarmInfo->len);
    if(NULL == payloadInfo)
    {
          CL_DEBUG_PRINT (CL_DEBUG_CRITICAL,("Memory allocation failed with rc 0x%x ", rc));
          clHeapFree(pCntKey);
          return CL_ALARM_RC(CL_ALARM_ERR_NO_MEMORY);
    }    
    payloadInfo->len = pAlarmInfo->len;
    memcpy(payloadInfo->buff, pAlarmInfo->buff, payloadInfo->len);

	clOsalMutexLock(gClAlarmPayloadCntMutex);        
    rc = clCntNodeFind(gPayloadCntHandle,(ClCntKeyHandleT)pCntKey,&nodeH);
	if(rc != CL_OK)
	{
		rc = clCntNodeAdd((ClCntHandleT)gPayloadCntHandle,
							(ClCntKeyHandleT)pCntKey,
							(ClCntDataHandleT)payloadInfo,
							NULL);
		if (CL_OK != rc)
		{
			CL_DEBUG_PRINT(CL_DEBUG_ERROR,("clCntNodeAdd failed with rc = %x\n", rc));
            clHeapFree(payloadInfo);
            clHeapFree(pCntKey);
        }
        CL_DEBUG_PRINT(CL_DEBUG_TRACE,("clCntNodeAdd adding payloadInfo->len : %d\n",payloadInfo->len));
	}
	else
	{
		CL_DEBUG_PRINT(CL_DEBUG_INFO,("Node already exist\n"));
        clHeapFree(payloadInfo);
        clHeapFree(pCntKey);
	}
	clOsalMutexUnlock(gClAlarmPayloadCntMutex);
	return rc;
}
static void
generate_time_of_day(char **data, ClSizeT *data_len)
{
    time_t t;

    // minimal error checking
    if (data == 0 || data_len == 0)
    {
        printf("generate_time_of_day passed null pointer\n");
        return;
    }

    // magic number, but well, that's what ctime_r needs
    *data_len = 26;
    *data = (char*)clHeapAllocate(*data_len);
    if (*data == 0)
    {
        *data_len = 0;
        return;
    }
    time(&t);
    ctime_r(&t, *data);
    *(*data + 24) = 0;
    (*data_len) -= 1;
    return;
}
ClRcT _clGmsDbOpen(
            CL_IN      const    ClUint64T   numOfGroups,
            CL_INOUT   ClGmsDbT** const     gmsDb)
{
    if (gmsDb == NULL) 
    {
        return CL_GMS_RC(CL_ERR_NULL_POINTER);
    }

    
    *gmsDb = (ClGmsDbT *) clHeapAllocate(sizeof(ClGmsDbT)
                                        * numOfGroups);

    if (*gmsDb == NULL)
    {
        return CL_GMS_RC(CL_ERR_NO_MEMORY);
    }

    memset(*gmsDb, 0, sizeof(ClGmsDbT)* numOfGroups);

    clLog(DBG,GEN,DB,
            "Created GMS master database successfully");

    return CL_OK;
}
static void appEventCallback( SaEvtSubscriptionIdT	subscriptionId, SaEvtEventHandleT     eventHandle, SaSizeT eventDataSize)
{
    SaAisErrorT  saRc = SA_AIS_OK;
    static ClPtrT   resTest = 0;
    static ClSizeT  resSize = 0;
    if (resTest != 0)
    {
        // Maybe try to save the previously allocated buffer if it's big
        // enough to hold the new event message.
        clHeapFree((char *)resTest);
        resTest = 0;
        resSize = 0;
    }
    resTest = clHeapAllocate(eventDataSize + 1);
    if (resTest == 0)
    {
        printf("Failed to allocate space for event\n");
        return;
    }
    *(((char *)resTest) + eventDataSize) = 0;
    resSize = eventDataSize;
    saRc = saEvtEventDataGet(eventHandle, resTest, &resSize);
    if (saRc!= SA_AIS_OK)
    {
        printf("Failed to get event data [0x%x]\n",saRc);
    }
    printf ("Received event from internal node: %s\n", (char *)resTest);
    return;
}
ClRcT clMsgQueueCkptDataMarshal(ClMsgQueueCkptDataT *qCkptData, ClCachedCkptDataT *outData)
{
    ClRcT rc = CL_OK;
    ClUint8T *copyData;
    ClUint32T network_byte_order;

    saNameCopy(&outData->sectionName, &qCkptData->qName);
    outData->sectionAddress.iocPhyAddress = qCkptData->qAddress;
    outData->dataSize = CL_MSG_QUEUE_DATA_SIZE;

    outData->data = (ClUint8T *) clHeapAllocate(outData->dataSize);
    copyData = outData->data;

    network_byte_order = (ClUint32T) htonl((ClUint32T)qCkptData->qServerAddress.nodeAddress);
    memcpy(copyData, &network_byte_order, sizeof(ClUint32T));
    copyData = copyData + sizeof(ClUint32T);

    network_byte_order = (ClUint32T) htonl((ClUint32T)qCkptData->qServerAddress.portId);
    memcpy(copyData, &network_byte_order, sizeof(ClUint32T));
    copyData = copyData + sizeof(ClUint32T);

    network_byte_order = (ClUint32T) htonl((ClUint32T)qCkptData->state);
    memcpy(copyData, &network_byte_order, sizeof(ClUint32T));
    copyData = copyData + sizeof(ClUint32T);

    network_byte_order = (ClUint32T) htonl((ClUint32T)qCkptData->creationFlags);
    memcpy(copyData, &network_byte_order, sizeof(ClUint32T));
    copyData = copyData + sizeof(ClUint32T);

    return rc;
}
void clEvtContTestDbInit()
{
    ClRcT rc = CL_OK;
    ClUint32T noOfApp;

    rc = clCntLlistCreate(clEvtContSubKeyCompare, clEvtContSubDataDelete,
                          clEvtContSubDataDelete, CL_CNT_NON_UNIQUE_KEY,
                          &gEvtContSubInfo);
    if (CL_OK != rc)
    {
        clOsalPrintf("Creating linked list failed for sub \r\n");
        exit(-1);
    }

    rc = clCntLlistCreate(clEvtContPubKeyCompare, clEvtContPubDataDelete,
                          clEvtContPubDataDelete, CL_CNT_UNIQUE_KEY,
                          &gEvtContPubInfo);
    if (CL_OK != rc)
    {
        clOsalPrintf("Creating linked list failed for pub \r\n");
        exit(-1);
    }

    clEvtContGetApp(&noOfApp);
    clHeapAllocate(noOfApp * sizeof(ClEvtContSubInfoStorageT));

    return;
}
ClRcT clCpmNodeNameGet(ClUint32T argc, ClCharT *argv[], ClCharT **retStr)
{
    ClRcT rc = CL_OK;
    ClNameT nodeName={0};
    *retStr = NULL;
    if(argc > 1 )
    {
        ClCharT tempStr[0x100];
        rc = CL_CPM_RC(CL_ERR_INVALID_PARAMETER);
        snprintf(tempStr, sizeof(tempStr),
                 "Usage: nodename\n");
        *retStr = (ClCharT *) clHeapAllocate(strlen(tempStr) + 1);
        if (*retStr)
            strcpy(*retStr, tempStr);
        goto out;
    }
    rc = clCpmLocalNodeNameGet(&nodeName);
    if(rc != CL_OK)
    {
        rc = CL_CPM_RC(CL_ERR_UNSPECIFIED);
        goto out;
    }
    *retStr = clHeapCalloc(1,nodeName.length+1);
    if(!*retStr)
    {
        rc = CL_CPM_RC(CL_ERR_NO_MEMORY);
        goto out;
    }
    strncpy(*retStr,nodeName.value,nodeName.length);
    rc = CL_OK;

    out:
    return rc;
}
/* 
 * this api is used to print the error messages 
 * within the context where the fault cli comman
 * is being used
 */
void clFaultCliStrPrint(ClCharT** ppRet, ClCharT* pErrMsg, ...)
{
    ClUint32T   len = strlen(pErrMsg) + 100; 
    va_list     arg;

    va_start(arg, pErrMsg);
    *ppRet = (ClCharT *)clHeapAllocate(len);
    if( NULL != *ppRet )
    {
        memset(*ppRet, '\0', len);
        vsnprintf(*ppRet, len, pErrMsg, arg);
        va_end(arg);
        return;
    }
    else
    {
        va_end(arg);
        return;
    }
    

    /*
    ClUint32T len = strlen(str);

    *retStr = clHeapAllocate(len+1);
    if(NULL == retStr)
    {
        clLogWrite(CL_LOG_HANDLE_SYS, CL_LOG_CRITICAL,	CL_FAULT_SERVER_LIB,
				CL_LOG_MESSAGE_0_MEMORY_ALLOCATION_FAILED);
        return;
    }
    snprintf(*retStr, len+1, str);
    return;
    */
}
/*
 * This api would be called as and when the object is no more and the corresponding entry 
 * within the container needs to be deleted.
 */
ClRcT clAlarmPayloadCntDelete(ClCorMOIdPtrT pMoId, ClAlarmProbableCauseT probCause, ClAlarmSpecificProblemT specificProblem)
{
	ClRcT rc = CL_OK;
	ClCntNodeHandleT nodeH;
    ClAlarmPayloadCntKeyT *pCntKey = clHeapAllocate(sizeof(ClAlarmPayloadCntKeyT));
    if(NULL == pCntKey)
    {
          CL_DEBUG_PRINT (CL_DEBUG_CRITICAL,("Memory allocation failed with rc 0x%x ", rc));
          return (rc);
    }    
    pCntKey->probCause = probCause;
    pCntKey->specificProblem = specificProblem;
    pCntKey->moId = *pMoId;

    clOsalMutexLock(gClAlarmPayloadCntMutex);        
    rc = clCntNodeFind(gPayloadCntHandle,(ClCntKeyHandleT)pCntKey,&nodeH);
	if(CL_OK == rc)
	{
    	rc = clCntAllNodesForKeyDelete(gPayloadCntHandle,(ClCntKeyHandleT)pCntKey);
    	if (CL_OK != rc)
	    {
        	CL_DEBUG_PRINT(CL_DEBUG_ERROR, ("clCntAllNodesForKeyDelete failed w rc:0x%x\n", rc));
	    }        
	}
	else
	{
		CL_DEBUG_PRINT(CL_DEBUG_ERROR, ("Node does not exist with rc:0x%x\n", rc));
	}
    clHeapFree(pCntKey);
	clOsalMutexUnlock(gClAlarmPayloadCntMutex);    
	return rc;
}
void cpmFillCompConfig(const ClCpmMgmtCompT *compInfo,
                       ClCpmCompConfigT *compConfig)
{
    ClUint32T i = 0;
    
    strncpy(compConfig->compName, compInfo->compName, CL_MAX_NAME_LENGTH-1);
    compConfig->compProperty = compInfo->compProperty;
    compConfig->compProcessRel = compInfo->compProcessRel;
    strncpy(compConfig->instantiationCMD,
            compInfo->instantiationCMD,
            CL_MAX_NAME_LENGTH-1);

    /**
     * Put the image name as first argument.
     */
    
    compConfig->argv[0] = (ClCharT*) clHeapAllocate(strlen(compInfo->instantiationCMD)+1);
    if (!compConfig->argv[0])
    {
        clLogError(CPM_LOG_AREA_CPM, CPM_LOG_CTX_CPM_MGM,
                   "Unable to allocate memory");
        goto failure;
    }

    strncpy(compConfig->argv[0],
            compInfo->instantiationCMD,
            strlen(compInfo->instantiationCMD));
    
    for (i = 1; compInfo->argv[i]; ++i)
    {
        compConfig->argv[i] = (ClCharT*) clHeapAllocate(strlen(compInfo->argv[i]) + 1);
        if (!compConfig->argv[i])
        {
            clLogError(CPM_LOG_AREA_CPM, CPM_LOG_CTX_CPM_MGM,
                       "Unable to allocate memory");
            goto failure;
        }

        strncpy(compConfig->argv[i],
                compInfo->argv[i],
                strlen(compInfo->argv[i]));
    }
    compConfig->argv[i] = NULL;

failure:
    return;
}
ClRcT clCkptEntryUpdate(ClCachedCkptSvcInfoT *serviceInfo,
                        const ClCachedCkptDataT *sectionData)
{
    ClRcT rc;

    SaCkptSectionIdT ckptSectionId = {        /* Section id for checkpoints   */
        sectionData->sectionName.length,
        (SaUint8T *) sectionData->sectionName.value
    };

    ClUint8T *ckptedData, *copyData;
    ClSizeT ckptedDataSize = sectionData->dataSize + sizeof(ClIocAddressT);
    ClUint32T network_byte_order;
    ClInt32T tries = 0;
    ClTimerTimeOutT delay = { 0,  500 };

    ckptedData = (ClUint8T *) clHeapAllocate(ckptedDataSize);
    if(ckptedData == NULL)
    {
        rc = CL_ERR_NO_MEMORY;
        clLogError("CCK", "UPD", "Failed to allocate memory. error code [0x%x].", rc);
        goto out1;
    }

    /* Marshall section data*/
    copyData = ckptedData;
    network_byte_order = (ClUint32T) htonl((ClUint32T)sectionData->sectionAddress.iocPhyAddress.nodeAddress);
    memcpy(copyData, &network_byte_order, sizeof(ClUint32T));
    copyData = copyData + sizeof(ClUint32T);
    network_byte_order = (ClUint32T) htonl((ClUint32T)sectionData->sectionAddress.iocPhyAddress.portId);
    memcpy(copyData, &network_byte_order, sizeof(ClUint32T));
    copyData = copyData + sizeof(ClUint32T);
    memcpy(copyData, sectionData->data, sectionData->dataSize);

    /* Try to update the section */
retry:
    rc = clCkptSectionOverwrite(serviceInfo->ckptHandle,         /* Checkpoint handle  */
                                (ClCkptSectionIdT *)&ckptSectionId,         /* Section ID         */
                                ckptedData,             /* Initial data       */
                                ckptedDataSize);        /* Size of data       */
    if (CL_ERR_TRY_AGAIN == CL_GET_ERROR_CODE(rc))
    {
        if ((++tries < 5) && (clOsalTaskDelay(delay) == CL_OK))
        {
            goto retry;
        }
    }
    if (rc != CL_OK)
    {
        clLogError("CCK", "UPD", "CkptSectionUpdate failed with rc [0x%x].",rc);
        goto out2;
    }

out2:
    clHeapFree(ckptedData);
out1:
    return rc;
}
/* happens only once during the booting of the system */
ClRcT clCorMOIdNodeNameMapAdd(ClCorMOIdPtrT pMoId, ClNameT *nodeName)
{
    ClRcT rc;
    /* Add the mapping in both the hash tables */
    /* In this table key is node Name and value is MoId */
    /* allocate MoId first */
    ClCorMOIdPtrT keyMoId = clHeapAllocate(sizeof(ClCorMOIdT));
	ClNameT		  *dataNodeName  = clHeapAllocate (sizeof(ClNameT));
	ClNameT		  *keyNodeName  = clHeapAllocate (sizeof(ClNameT));
    ClCorNodeDataPtrT dataNode = clHeapAllocate(sizeof(ClCorNodeDataT));
    if(dataNode == NULL)
    { 
        CL_DEBUG_PRINT(CL_DEBUG_ERROR,("Failed to allocate Node Data")); 
        return CL_COR_SET_RC(CL_COR_ERR_NO_MEM) ;
    }
    memset(&dataNode->nodeName, 0, sizeof(ClNameT));
    dataNode->pMoId = clHeapAllocate(sizeof(ClCorMOIdT));

    if( keyMoId == NULL || dataNodeName == NULL || dataNode->pMoId == NULL || keyNodeName == NULL)
    {
		clLogWrite(CL_LOG_HANDLE_APP, CL_LOG_DEBUG, NULL,
				CL_LOG_MESSAGE_0_MEMORY_ALLOCATION_FAILED);
		CL_DEBUG_PRINT(CL_DEBUG_ERROR,(CL_COR_ERR_STR(CL_COR_ERR_NO_MEM)));
		return CL_COR_SET_RC(CL_COR_ERR_NO_MEM);
    }

    memcpy(keyMoId, pMoId, sizeof(ClCorMOIdT));
    memcpy(dataNodeName, nodeName, sizeof(ClNameT));
    memcpy(dataNode->pMoId, pMoId, sizeof(ClCorMOIdT));
    memcpy(&dataNode->nodeName, nodeName, sizeof(ClNameT));
    memcpy(keyNodeName, nodeName, sizeof(ClNameT));

    rc = clCntNodeAdd(nodeNameToMoIdTableHandle, (ClCntKeyHandleT) dataNodeName, (ClCntDataHandleT )dataNode , NULL);
    
    if(CL_OK != rc)
        CL_COR_RETURN_ERROR(CL_DEBUG_ERROR, "Could not add node in nodeNameToMoIdHandle", rc);    
    
    /* MOID to Node Name map - In this table key is MOId and value is node name   */
    rc = clCntNodeAdd(moIdToNodeNameTableHandle, (ClCntKeyHandleT) keyMoId, (ClCntDataHandleT)keyNodeName, NULL);

    if(CL_OK != rc)
        CL_COR_RETURN_ERROR(CL_DEBUG_ERROR, "Could not add node in moIdToNodeNameHandle", rc);    
    
    return CL_OK;
}
static void
generate_load_average(char **data, ClSizeT *data_len)
{
    int fd;
    char *tmp_ptr;
    char buf[500];                  //insane over doing it
    ssize_t num_read;

    // minimal error checking
    if (data == 0 || data_len == 0)
    {
        printf("generate_load_average passed null pointer\n ");
        return;
    }
    if ((fd = open("/proc/loadavg", O_RDONLY, 0)) == -1)
    {
        printf( "failed to open /proc/loadavg\n");
        return;
    }
    num_read = read(fd, buf, sizeof buf);
    if (num_read == 0 || num_read == -1)
    {
        printf( "bogus result from read of loadavg\n");
        return;
    }
    close(fd);
    *data_len = num_read + 1;
    *data = (char*)clHeapAllocate(*data_len);
    if (data == 0)
    {
        printf(
                "failed to allocate memory for loadavg contents\n");
        *data_len = 0;
        close(fd);
        return;
    }
    *(*data + (*data_len) - 1) = 0;    
    strncpy(*data, buf, *data_len);
    tmp_ptr = strchr(*data, ' ');
    if (tmp_ptr == 0)
    {
        return;
    }
    tmp_ptr = strchr(tmp_ptr + 1, ' ');
    if (tmp_ptr == 0)
    {
        return;
    }
    tmp_ptr = strchr(tmp_ptr + 1, ' ');
    if (tmp_ptr == 0)
    {
        return;
    }
    *tmp_ptr = 0;
    return;
}
ClRcT clCpmEventPayLoadExtract(ClEventHandleT eventHandle,
                               ClSizeT eventDataSize,
                               ClCpmEventTypeT cpmEventType,
                               void *payLoad)
{
    ClRcT rc = CL_OK;
    ClBufferHandleT payLoadMsg = 0;
    void *eventData = NULL;

    eventData = clHeapAllocate(eventDataSize);
    if (eventData == NULL)
    {
        clLogWrite(CL_LOG_HANDLE_APP, CL_LOG_SEV_DEBUG, CL_CPM_CLIENT_LIB,
                   CL_LOG_MESSAGE_0_MEMORY_ALLOCATION_FAILED);
        CPM_CLIENT_CHECK(CL_LOG_SEV_ERROR, ("Unable to malloc \n"),
                         CL_CPM_RC(CL_ERR_NO_MEMORY));
    }
    rc = clEventDataGet (eventHandle, eventData,  &eventDataSize);
    if (rc != CL_OK)
    {
        clOsalPrintf("Event Data Get failed. rc=[0x%x]\n", rc);
        goto failure;
    }

    rc = clBufferCreate(&payLoadMsg);
    CL_CPM_CHECK_1(CL_LOG_SEV_ERROR, CL_CPM_LOG_1_BUF_CREATE_ERR, rc, rc,
                   CL_LOG_HANDLE_APP);
    rc = clBufferNBytesWrite(payLoadMsg, (ClUint8T *)eventData,
                             eventDataSize);
    CL_CPM_CHECK_1(CL_LOG_SEV_ERROR, CL_CPM_LOG_1_BUF_WRITE_ERR, rc, rc,
                   CL_LOG_HANDLE_APP);

    switch(cpmEventType)
    {
    case CL_CPM_COMP_EVENT:
        rc = VDECL_VER(clXdrUnmarshallClCpmEventPayLoadT, 4, 0, 0)(payLoadMsg, payLoad);
        CL_CPM_CHECK_0(CL_LOG_SEV_ERROR, CL_LOG_MESSAGE_0_INVALID_BUFFER, rc,
                       CL_LOG_HANDLE_APP);
        break;
    case CL_CPM_NODE_EVENT:
        rc = VDECL_VER(clXdrUnmarshallClCpmEventNodePayLoadT, 4, 0, 0)(payLoadMsg, payLoad);
        CL_CPM_CHECK_0(CL_LOG_SEV_ERROR, CL_LOG_MESSAGE_0_INVALID_BUFFER, rc,
                       CL_LOG_HANDLE_APP);
        break;
    default:
        clOsalPrintf("Invalid event type received.\n");
        goto failure;
        break;
    }

failure:
    clBufferDelete(&payLoadMsg);
    clHeapFree(eventData);
    return rc;
}
ClRcT clEoNotificationCallbackInstall(ClIocPhysicalAddressT compAddr, ClPtrT pFunc, ClPtrT pArg, ClHandleT *pHandle)
{
    ClRcT rc = CL_OK;
    ClUint32T i = 0;
    ClEoCallbackRecT **tempDb;
    
    if(pFunc == NULL || pHandle == NULL)
    {
        return CL_EO_RC(CL_ERR_INVALID_PARAMETER);
    }

    rc = clOsalMutexLock(&gpCallbackDb.lock);
    if(rc != CL_OK)
    {
        /* Print an error message here */
        return rc;
    }

re_check:
    for(; i < gpCallbackDb.numRecs; i++)
    {
        if(gpCallbackDb.pDb[i] == NULL)
        {
            ClEoCallbackRecT *pRec = {0};

            pRec =(ClEoCallbackRecT *)clHeapAllocate(sizeof(ClEoCallbackRecT));

            pRec->node = compAddr.nodeAddress;
            pRec->port = compAddr.portId;
            pRec->pFunc = *((ClCpmNotificationFuncT*)&pFunc);
            pRec->pArg = pArg;

            *pHandle = i;

            gpCallbackDb.pDb[i] = pRec;
            goto out;
        }
    }
    
    tempDb = clHeapRealloc(gpCallbackDb.pDb, sizeof(ClEoCallbackRecT *) * gpCallbackDb.numRecs * 2);
    if(tempDb == NULL)
    {
        rc  = CL_EO_RC(CL_ERR_NO_MEMORY);
        goto out;
    }
    memset(tempDb + gpCallbackDb.numRecs, 0, sizeof(ClEoCallbackRecT *) * gpCallbackDb.numRecs);
    gpCallbackDb.pDb =  tempDb;
    gpCallbackDb.numRecs *= 2;
    goto re_check;

out :
    clOsalMutexUnlock(&gpCallbackDb.lock);
    return rc;
}
ClRcT clCpmMiddlewareRestartCommand(ClUint32T argc, ClCharT **argv, ClCharT **retStr)
{
    ClRcT rc = CL_CPM_RC(CL_ERR_NO_MEMORY);
    ClIocNodeAddressT nodeAddress = 0;
    ClBoolT graceful = CL_TRUE;
    ClBoolT nodeReset = CL_FALSE;

    *retStr = clHeapAllocate(2*CL_MAX_NAME_LENGTH+1);
    if (!*retStr)
    {
        goto out;
    }

    rc = CL_CPM_RC(CL_ERR_INVALID_PARAMETER);
    if (argc < 2 || argc > 4)
    {
        strncpy(*retStr,
                "Usage : middlewareRestart node-address [graceful] [node-reset]\n"
                "        node-address - Address of the node to be restarted\n"
                "        graceful - value >= 1 indicates graceful restart\n"
                "                 - value 0 indicates ungraceful restart\n"
                "                 default value is 1\n"
                "        node-reset - value >= 1 indicates node is reset\n"
                "                   - value 0 indicates middleware is restarted\n"
                "                 default value is 0\n",
                2*CL_MAX_NAME_LENGTH);
        goto out;
    }

    if(argc >= 2)
        nodeAddress = cpmCliStrToInt(argv[1]);
    
    if(argc >= 3)
        graceful = cpmCliStrToInt(argv[2]) ? CL_TRUE : CL_FALSE;

    if(argc >= 4)
        nodeReset = cpmCliStrToInt(argv[3]) ? CL_TRUE : CL_FALSE;

    rc = clCpmMiddlewareRestart(nodeAddress, graceful, nodeReset);
    if (rc != CL_OK)
    {
        snprintf(*retStr,
                 2*CL_MAX_NAME_LENGTH,
                 "Restarting middleware failed with error [%#x]",
                 rc);
        goto out;
    }

    return CL_OK;
    
    out:
    return rc;
}
ClRcT VDECL(_corObjectGetNextOp) (ClUint32T cData, ClBufferHandleT  inMsgHandle,
                                  ClBufferHandleT  outMsgHandle)
{
    ClRcT rc = CL_OK;
    corObjGetNextInfo_t* pData = NULL; 
    CL_FUNC_ENTER();

    if(gCorInitStage == CL_COR_INIT_INCOMPLETE)
    {
        clLogError("OBN", "EXP", "The COR server Initialization is in progress....");
        return CL_COR_SET_RC(CL_COR_ERR_TRY_AGAIN);
    }

    pData = clHeapAllocate(sizeof(corObjGetNextInfo_t));
    if(pData == NULL)
    {
        CL_DEBUG_PRINT(CL_DEBUG_ERROR, ( "NULL input parameter") );
        return CL_COR_SET_RC(CL_COR_ERR_NULL_PTR);   
    }
    if((rc = clXdrUnmarshallcorObjGetNextInfo_t(inMsgHandle, (void *)pData)) != CL_OK)
	{
		clHeapFree(pData);
		CL_DEBUG_PRINT(CL_DEBUG_ERROR,("Failed to Unmarshall corObjGetNextInfo_t"));
		return rc;
	}

  	clCorClientToServerVersionValidate(version, rc);
  	if(rc != CL_OK)
	{
		clHeapFree(pData);
		return CL_COR_SET_RC(CL_COR_ERR_VERSION_UNSUPPORTED);
	}
	
    switch(pData->operation)
    {
        case COR_OBJ_OP_NEXTMO_GET:
		{
              ClCorObjectHandleT nxtOH;
              rc =  _clCorNextMOGet(pData->objHdl, pData->classId, pData->svcId, &nxtOH);
              /* Write to the message*/
              clBufferNBytesWrite (outMsgHandle, (ClUint8T *)&nxtOH, sizeof(ClCorObjectHandleT));
        } 
        break;
        default:
             CL_DEBUG_PRINT(CL_DEBUG_ERROR, ( "INVALID OPERATION, rc = %x", rc) );
             rc = CL_COR_SET_RC(CL_COR_ERR_INVALID_PARAM);
        break;
    }
   
    CL_FUNC_EXIT();
	clHeapFree(pData);
    return rc;
}
ClRcT clCpmRestart(ClUint32T argc, ClCharT **argv, ClCharT **retStr)
{
    ClRcT rc = CL_CPM_RC(CL_ERR_NO_MEMORY);

    *retStr = clHeapAllocate(2*CL_MAX_NAME_LENGTH+1);
    if (!*retStr)
    {
        goto out;
    }

    rc = CL_CPM_RC(CL_ERR_INVALID_PARAMETER);
    if (argc < 2 || argc > 3)
    {
        strncpy(*retStr, 
                "Usage : nodeRestart node-address [graceful]\n"
                "        node-address - Address of the node to be restarted\n"
                "        graceful - value >= 1 indicates graceful restart\n"
                "                 - value 0 indicates ungraceful restart\n"
                "                 default value is 1\n",
                2*CL_MAX_NAME_LENGTH);
    }
    else if (argc == 2)
    {
        rc = clCpmNodeRestart(cpmCliStrToInt(argv[1]), CL_TRUE);
        if (rc != CL_OK)
        {
            snprintf(*retStr,
                     2*CL_MAX_NAME_LENGTH,
                     "Restarting node failed with error [%#x]",
                     rc);
            goto out;
        }
    }
    else if (argc == 3)
    {
        rc = clCpmNodeRestart(cpmCliStrToInt(argv[1]),
                              cpmCliStrToInt(argv[2]) ? CL_TRUE: CL_FALSE);
        if (rc != CL_OK)
        {
            snprintf(*retStr,
                     2*CL_MAX_NAME_LENGTH,
                     "Restarting node failed with error [%#x]",
                     rc);
            goto out;
        }
    }

    return CL_OK;
    
out:
    return rc;
}
ClRcT cpmInvocationAdd(ClUint32T cbType,
                       void *data,
                       ClInvocationT *invocationId,
                       ClUint32T flags)
{
    ClRcT rc = CL_OK;
    ClCpmInvocationT *temp = NULL;
    ClUint32T invocationKey = 0;

    if (cbType < 0x1LL || cbType >= CL_CPM_MAX_CALLBACK || invocationId == NULL)
        CL_CPM_CHECK(CL_LOG_SEV_ERROR, ("Invalid parameter passed \n"),
                     CL_CPM_RC(CL_ERR_INVALID_PARAMETER));

    temp =
            (ClCpmInvocationT *) clHeapAllocate(sizeof(ClCpmInvocationT));
    if (temp == NULL)
        CL_CPM_CHECK(CL_LOG_SEV_ERROR, ("Unable to allocate memory \n"),
                     CL_CPM_RC(CL_ERR_NO_MEMORY));

    clOsalMutexLock(gpClCpm->invocationMutex);

    invocationKey = gpClCpm->invocationKey++;
    CL_CPM_INVOCATION_ID_GET((ClUint64T) cbType, (ClUint64T) invocationKey,
                             *invocationId);

    temp->invocation = *invocationId;
    temp->data = data;
    temp->flags = flags;

    rc = clCntNodeAdd(gpClCpm->invocationTable, (ClCntKeyHandleT)&temp->invocation,
                      (ClCntDataHandleT) temp, NULL);
    if (rc != CL_OK)
    {
        clLogError("NEW", "INVOCATION", "Invocation add for key [%#llx] returned [%#x]", 
                   temp->invocation, rc);
        goto withLock;
    }

    clLogDebug("NEW", "INVOCATION", "Added entry for invocation [%#llx]", temp->invocation);

    clOsalMutexUnlock(gpClCpm->invocationMutex);
    return rc;

  withLock:
    clOsalMutexUnlock(gpClCpm->invocationMutex);
  failure:
    if (temp != NULL)
        clHeapFree(temp);

    return rc;
}
ClRcT clHalLibInitialize()
{
    ClRcT rc= CL_OK ; 
    CL_FUNC_ENTER();
    if (CL_TRUE == halInitDone)
    {
        clLogCritical(CL_LOG_AREA_UNSPECIFIED,CL_LOG_CONTEXT_UNSPECIFIED,"\n clHalLibInitialize Called Again \n");
        CL_FUNC_EXIT();
        return (CL_HAL_SET_RC(CL_ERR_INVALID_STATE));
    }
#ifdef DEBUG
    rc= dbgAddComponent(COMP_PREFIX, COMP_NAME, COMP_DEBUG_VAR_PTR);
    if (CL_OK != rc)
    {
        clLogError(CL_LOG_AREA_UNSPECIFIED,CL_LOG_CONTEXT_UNSPECIFIED,"dbgAddComponent Failed \n ");
        CL_FUNC_EXIT();
        return rc;
    }
#endif
    
    memset(&halDevObjTable,0, sizeof(HalDeviceObjTableT));

    halDevObjTable.pphalDeviceObj=(HalDeviceObjectT **)clHeapAllocate((halConfig.
        halNumDevObject)*sizeof(HalDeviceObjectT *));

    if (NULL == halDevObjTable.pphalDeviceObj)
    {
        clLogCritical(CL_LOG_AREA_UNSPECIFIED,CL_LOG_CONTEXT_UNSPECIFIED,"\n clHalLibInitialize Error no memory HAL\n");
        CL_FUNC_EXIT();
        return(CL_HAL_SET_RC(CL_ERR_NO_MEMORY));
    }

    memset(halDevObjTable.pphalDeviceObj,0, ((halConfig.
        halNumDevObject)*sizeof(HalDeviceObjectT *)));
        
    halInitDone = CL_TRUE; 

    /* Create device object(s) from the Configuration Info */
    rc = halDevObjTableCreate ();
    if (rc != CL_OK)
    {
        clLogCritical(CL_LOG_AREA_UNSPECIFIED,CL_LOG_CONTEXT_UNSPECIFIED,"\n halDevObjTableCreate  Failed");
        CL_FUNC_EXIT();
        return rc ;
    }
    clLogTrace(CL_LOG_AREA_UNSPECIFIED,CL_LOG_CONTEXT_UNSPECIFIED,"\nclHalLibInitialize CL_OK\n");
    CL_FUNC_EXIT();
    return (CL_OK) ;
}
ClRcT cliEOSetState(ClUint32T argc, ClCharT **argv, ClCharT **retStr)
{
    ClRcT rc = CL_OK;
    ClEoIdT eoId;
    ClEoStateT state;
    ClCharT tempStr[256];

    if (argc < THREE_ARGUMENT)
    {
        sprintf(tempStr, "%s%s%s", "Usage: EOStateSet <eoId> <state>\n",
                "\teoId[DEC]: Id assigned to an EO\n",
                "\tState[STRING]: SUSPEND/RESUME\n");
        rc = CL_CPM_RC(CL_ERR_INVALID_PARAMETER);
        goto done;
    }
    else
    {
        eoId = cpmCliStrToInt(argv[1]);
        
        if (0 == strcmp(argv[2], "SUSPEND"))
            state = CL_EO_STATE_SUSPEND;
        else if (0 == strcmp(argv[2], "RESUME"))
            state = CL_EO_STATE_RESUME;
        else
        {
            sprintf(tempStr, "\n Improper state: State: SUSPEND/RESUME\n");
            rc = CL_CPM_RC(CL_ERR_INVALID_PARAMETER);
            goto done;
        }

        rc = clCpmExecutionObjectStateSet(clIocLocalAddressGet(), eoId, state);
        if (rc == CL_OK)
            sprintf(tempStr, "\n State update Successful");
        else
            sprintf(tempStr, "\n State update Failed");
    }

  done:
    *retStr = (ClCharT *) clHeapAllocate(strlen(tempStr) + 1);
    if (*retStr == NULL)
        CL_CPM_CHECK(CL_DEBUG_ERROR, ("\n MAlloc Failed \n"),
                     CL_CPM_RC(CL_ERR_NO_MEMORY));
    strcpy(*retStr, tempStr);

  failure:
    return rc;
}
static ClRcT gmsLeaderElect (
                    CL_IN   ClUint32T argc,
                    CL_IN   ClCharT** argv,
                    CL_OUT  ClCharT** ret)
{
    ClRcT    rc = CL_OK;
    ClGmsClusterLeaderElectRequestT         req = {0};
    ClGmsClusterLeaderElectResponseT        res = {0};


    /* Allocate maximum possible */ 
    *ret = clHeapAllocate(1020);
    if( *ret == NULL ){
        clLog (ERROR,GEN,NA,
                "Memory allocation failed");
        return CL_ERR_NO_MEMORY;
    }
    memset(*ret,0,1020);

    if (argc != 2)
    {
        _clGmsCliMakeError( ret, LEADER_ELECT_USAGE );
        return CL_OK;
    }

    req.gmsHandle = 0;
    req.preferredLeaderNode = atoi(argv[1]);
    req.clientVersion = gmsGlobalInfo.config.versionsSupported.versionsSupported[0] ;

    rc = clGmsClusterLeaderElectHandler(&req, &res);
    if ((rc != CL_OK) && (rc != CL_ERR_ALREADY_EXIST))
    {
        _clGmsCliPrint(ret, "ClusterLeaderElect failed with rc 0x%x \n",rc);
        return rc;
    }

    if (rc == CL_ERR_ALREADY_EXIST)
    {
        _clGmsCliPrint(ret, "Node [%d] is already the leader node\n",req.preferredLeaderNode);
    }

    _clGmsCliPrint(ret, "New leader = %d\nNew Deputy = %d\nLeadership Changed = %s\n",
            res.leader,res.deputy,(res.leadershipChanged == CL_TRUE) ? "Yes" : "No");

    return CL_OK;
}
ClRcT clSnmpocTrainDefaultInstXlator (CL_IN const struct ClMedAgentId *pAgntId,
                     CL_IN ClCorMOIdPtrT         hmoId,
                     CL_IN ClCorAttrPathPtrT containedPath,
                     CL_OUT void**         pRetInstData,
                     CL_OUT ClUint32T     *pInstLen,
                     CL_OUT ClPtrT        pCorAttrValueDescList,
                     CL_IN ClMedInstXlationOpEnumT instXlnOp,
                     CL_IN ClPtrT cookie)
{
    ClUint32T   len = 0;
    ClSNMPRequestInfoT *pInst = NULL;

    clLog(CL_LOG_DEBUG, CL_SNMP_AREA, CL_SNMP_GEN_XLA_COTX, "Default Instant Xlation for MOID : ");
    CL_MED_COR_STR_MOID_PRINT(hmoId);

    if(!pAgntId || !pRetInstData || !pInstLen)
    {
        clLog(CL_LOG_ERROR, CL_SNMP_AREA, CL_SNMP_GEN_XLA_COTX, "clSnmpInstXlator received NULL arguments!");
        return CL_ERR_NULL_POINTER;   
    }

    pInst = (ClSNMPRequestInfoT*)*pRetInstData;

    if (pInst == NULL)
    {
        pInst = (ClSNMPRequestInfoT *) clHeapAllocate (sizeof (ClSNMPRequestInfoT));
        if (pInst == NULL)
        {
            clLog(CL_LOG_ERROR, CL_SNMP_AREA, CL_SNMP_GEN_XLA_COTX, "clSnmpocTrainDefaultInstXlator Unable to allocate memory for the instance translation!");
            return (CL_ERR_NO_MEMORY);
        }
        *pInstLen = sizeof (ClSNMPRequestInfoT);
        memset(pInst, 0, *pInstLen);
        *pRetInstData = (void**)pInst;
    }
    for(len = 0; len < pAgntId->len; len++)
    {
        pInst->oid[len] = pAgntId->id[len];
    }

    pInst->tableType = CL_OCTRAIN_SCALARS;
    return CL_OK;
}
static void cpmCliPrint(ClCharT **retStr, const ClCharT *fmt, ...)
{
    va_list args;
    ClCharT tempStr[CL_MAX_NAME_LENGTH] = {0};

    va_start(args, fmt);
    vsnprintf(tempStr, CL_MAX_NAME_LENGTH-1, fmt, args);
    va_end(args);

    *retStr = (ClCharT *) clHeapAllocate(strlen(tempStr) + 1);
    if (!*retStr) 
    {
        clLogError(CPM_LOG_AREA_CPM, CPM_LOG_CTX_CPM_CLI,
                   "Failed to allocate memory, error [%#x]",
                   CL_CPM_RC(CL_ERR_NULL_POINTER));
        return;
    }
    strcpy(*retStr, tempStr);
}
/**
 * Create newly transaction-job definition
 */
ClRcT clTxnNewAppJobCreate(
        CL_OUT  ClTxnAppJobDefnPtrT  *pNewTxnJob)
{
    ClRcT               rc  = CL_OK;
    ClTxnAppJobDefnT    *pTxnJob;

    CL_FUNC_ENTER();

    if (NULL == pNewTxnJob)
    {
        CL_FUNC_EXIT();
        return CL_ERR_NULL_POINTER;
    }

    *pNewTxnJob = NULL;
    
    pTxnJob = (ClTxnAppJobDefnT *)clHeapAllocate( sizeof(ClTxnAppJobDefnT));
    if (NULL == pTxnJob)
    {
        CL_FUNC_EXIT();
        return CL_ERR_NO_MEMORY;
    }

    memset(pTxnJob, 0, sizeof(ClTxnAppJobDefnT));
    rc = clCntLlistCreate(_clTxnCmpKeyCompare,
                          _clTxnCompEntryDelete, _clTxnCompEntryDestroy,
                          CL_CNT_UNIQUE_KEY,
                          (ClCntHandleT *) &(pTxnJob->compList) );

    if (CL_OK != rc)
    {
        clHeapFree(pTxnJob);
    }
    else
    {
        CL_DEBUG_PRINT(CL_DEBUG_TRACE, ("Creating new txn-job %p, compList:%p", 
                        (ClPtrT) pTxnJob, (ClPtrT) pTxnJob->compList));
        *pNewTxnJob = pTxnJob;
    }

    CL_FUNC_EXIT();
    return (CL_GET_ERROR_CODE(rc));
}
ClRcT clProvResourcesGet(ClCorMOIdListT** ppMoIdList)
{
    if (!pProvMoIdList)
    {
        clLogDebug("PRV", "RESLISTGET", "No prov resources configured.");
        return CL_OK;
    }

    *ppMoIdList = clHeapAllocate(sizeof(ClCorMOIdListT) + pProvMoIdList->moIdCnt * sizeof(ClCorMOIdT));
    if (!(*ppMoIdList))
    {
        clLogError("PRV", "RESLISTGET", "Failed to allocate memory.");
        return CL_PROV_RC(CL_ERR_NO_MEMORY);
    }

    memcpy(*ppMoIdList, pProvMoIdList, sizeof(ClCorMOIdListT) + pProvMoIdList->moIdCnt * sizeof(ClCorMOIdT));

    return CL_OK;
}
static void csa112Comp_appEventCallback(SaEvtSubscriptionIdT subscriptionId, SaEvtEventHandleT eventHandle, SaSizeT eventDataSize)
{
    SaAisErrorT     rc = SA_AIS_OK;
    static ClPtrT   resTest = 0;
    
    clprintf(CL_LOG_SEV_INFO,"We've got an event to receive\n");

    /* A high performance implementation would keep the buffer
       if it was big enough for the next event, OR even faster
       preallocate buffer(s) of the the maximum event size which
       can be known by controlling what processes publish to
       a particular event channel.

       This tutorial will simply free an realloc the event buffer.
    */
    if (resTest != 0)
    {
        clHeapFree((char *)resTest);
        resTest = 0;
    }
    resTest = clHeapAllocate(eventDataSize + 1);
    if (resTest == 0)
    {
        clprintf(CL_LOG_SEV_ERROR, "Failed to allocate space for event");
        return;
    }

    /* This API can be used outside of the callback routine, which is why
       you need to pass the size of the buffer you've allocated. */
    rc = saEvtEventDataGet(eventHandle, resTest, &eventDataSize);
    if (rc!= SA_AIS_OK)
    {
        clprintf(CL_LOG_SEV_ERROR, "Failed to get event data [0x%x]",rc);
        return;
    }
    
    /* This tutorial just prints the event.  Rather then rely on the correct
       null termination at the publisher side, I'm going to append a 0 at
       the end before printing it. */
    *(((char *)resTest) + eventDataSize) = 0;
    clprintf(CL_LOG_SEV_INFO,"received event: %s\n", (char *)resTest);
}