ClRcT clEvtCpmInit()
{
    ClNameT appName;
    ClCpmCallbacksT callbacks;
    ClVersionT version;
    ClIocPortT iocPort;
    ClRcT rc = CL_OK;

    /******************************************************************
                        CPM Related stuff
    ******************************************************************/
    /*
     * Do the CPM client init/Register
     */
    version.releaseCode = 'B';
    version.majorVersion = 0x1;
    version.minorVersion = 0x1;

    callbacks.appHealthCheck = NULL;
    callbacks.appTerminate = clEventTerminate;
    callbacks.appCSISet = NULL;
    callbacks.appCSIRmv = NULL;
    callbacks.appProtectionGroupTrack = NULL;
    callbacks.appProxiedComponentInstantiate = NULL;
    callbacks.appProxiedComponentCleanup = NULL;

    clEoMyEoIocPortGet(&iocPort);
    rc = clCpmClientInitialize(&gClEvtTestContCpmHandle, &callbacks, &version);
    rc = clCpmComponentNameGet(gClEvtTestContCpmHandle, &appName);
    rc = clCpmComponentRegister(gClEvtTestContCpmHandle, &appName, NULL);

    return CL_OK;
}
ClRcT clEvtCpmInit()
{
    ClNameT appName;
    ClCpmCallbacksT callbacks;
    ClVersionT version;
    ClIocPortT iocPort;
    ClRcT rc = CL_OK;

    version.releaseCode = 'B';
    version.majorVersion = 0x1;
    version.minorVersion = 0x1;

    callbacks.appHealthCheck = NULL;
    callbacks.appTerminate = clEventTerminate;
    callbacks.appCSISet = NULL;
    callbacks.appCSIRmv = NULL;
    callbacks.appProtectionGroupTrack = NULL;
    callbacks.appProxiedComponentInstantiate = NULL;
    callbacks.appProxiedComponentCleanup = NULL;

    clEoMyEoIocPortGet(&iocPort);

    rc = clCpmClientInitialize(&gClEvtCpmHandle, &callbacks, &version);
    if (CL_OK != rc)
    {
        clLogWrite(CL_LOG_HANDLE_APP, CL_LOG_CRITICAL, NULL,
                   CL_LOG_MESSAGE_2_LIBRARY_INIT_FAILED, "CPM Library", rc);
    }

    rc = clCpmComponentNameGet(gClEvtCpmHandle, &appName);
    rc = clCpmComponentRegister(gClEvtCpmHandle, &appName, NULL);

    return CL_OK;
}
SaAisErrorT saAmfComponentNameGet(SaAmfHandleT amfHandle,
                                  SaNameT *compName)
{
    ClRcT rc;
    
    rc = clCpmComponentNameGet(amfHandle, (ClNameT *)compName);

    return clClovisToSafError(rc);
}
/* - clLogClntCompInfoGet
 * - Gets the component name and id
 */
ClRcT
clLogClntCompInfoGet(ClLogCompInfoT  *pCompInfo)
{
    ClRcT  rc = CL_OK;

    CL_LOG_DEBUG_TRACE(("Enter"));

    CL_LOG_PARAM_CHK((NULL == pCompInfo), CL_LOG_RC(CL_ERR_NULL_POINTER));

    rc = clCpmComponentNameGet(0, &pCompInfo->compName);
    if( CL_OK != rc)
    {
        CL_LOG_DEBUG_ERROR(("clCpmComponentNameGet(): rc[0x %x]", rc));
        return rc;
    }

    clEoMyEoIocPortGet(&pCompInfo->compId);

    CL_LOG_DEBUG_TRACE(("Exit: %.*s %u", pCompInfo->compName.length,
                        pCompInfo->compName.value, pCompInfo->compId));
    return rc;
}
ClRcT
clCompAppInitialize(
    ClUint32T argc,
    ClCharT *argv[])
{
    SaNameT             appName;
    ClCpmCallbacksT     callbacks;
    ClVersionT          version;
    ClIocPortT          iocPort;
    ClRcT               rc = CL_OK;

    /*
     * Get the pid for the process and store it in global variable.
     */

    mypid = getpid();

    /*
     * Initialize and register with CPM. 'version' specifies the version of
     * AMF with which this application would like to interface. 'callbacks'
     * is used to register the callbacks this component expects to receive.
     */

    version.releaseCode                         = 'B';
    version.majorVersion                        = 01;
    version.minorVersion                        = 01;
    
    callbacks.appHealthCheck                    = NULL;
    callbacks.appTerminate                      = clCompAppTerminate;
    callbacks.appCSISet                         = clCompAppAMFCSISet;
    callbacks.appCSIRmv                         = clCompAppAMFCSIRemove;
    callbacks.appProtectionGroupTrack           = NULL;
        
    /*
     * Get IOC Address, Port and Name. Register with AMF.
     */

    clEoMyEoIocPortGet(&iocPort);

    if ( (rc = clCpmClientInitialize(&cpmHandle, &callbacks, &version)) ) 
        goto errorexit;

    /*
     * If this component will provide a service, register it now.
     */

#if HAS_EO_SERVICES


    rc = clSAFComponent0EO0ClientInstall();

#endif

    /*
     * Do the application specific initialization here.
     */

    /*
     * ---BEGIN_APPLICATION_CODE---
     */

    // ...

    /*
     * ---END_APPLICATION_CODE---
     */

    /*
     * Now register the component with AMF. At this point it is
     * ready to provide service, i.e. take work assignments.
     */

    if ( (rc = clCpmComponentNameGet(cpmHandle, &appName)) ) 
        goto errorexit;
    if ( (rc = clCpmComponentRegister(cpmHandle, &appName, NULL)) ) 
        goto errorexit;

    /*
     * Print out standard information for this component.
     */

    clprintf ("Component [%s] : PID [%d]. Initializing\n", appName.value, mypid);
    clprintf ("   IOC Address             : 0x%x\n", clIocLocalAddressGet());
    clprintf ("   IOC Port                : 0x%x\n", iocPort);

    /*
     * This is where the application code starts. If the main thread usage
     * policy is CL_EO_USE_THREAD_FOR_APP, then return from this fn only 
     * after the application terminates. If the main thread usage policy is
     * CL_EO_USE_THREAD_FOR_RECV, then return from this fn after doing the
     * application specific initialization and registration.
     */

    /*
     * ---BEGIN_APPLICATION_CODE---
     */

    // ...

    /*
     * ---END_APPLICATION_CODE---
     */

    return rc;

errorexit:

    clprintf ("Component [%s] : PID [%d]. Initialization error [0x%x]\n",
              appName.value, mypid, rc);

    return rc;
}
ClRcT clComponentCallBack(void *arg)
{

    ClRcT rc = CL_OK;
    struct timeval alarmTime;
    ClAlarmHandleT alarmHandle;
    ClNameT moidName = {strlen("\\Chassis:0\\GigeBlade:0"),
                        "\\Chassis:0\\GigeBlade:0"};
    ClNameT moidName2 = {strlen("\\Chassis:0\\GigeBlade:0\\GigePort:0"),
                        "\\Chassis:0\\GigeBlade:0\\GigePort:0"};

    ClAlarmInfoT *pAlarmInfo;
    ClCorMOIdT   moId;
    ClNameT      moIdName = {0};

    pAlarmInfo = clHeapAllocate(sizeof(ClAlarmInfoT)+strlen("HelloHelloHelloHelloHelloHelloHelloHello")+1);
    if(pAlarmInfo == NULL)
    {
        clOsalPrintf("Failed while allocating the memory for the alamr information.");
        return CL_ALARM_RC(CL_ERR_NO_MEMORY);
    }

    clCpmComponentNameGet(0,&(pAlarmInfo->compName));
    CL_DEBUG_PRINT(CL_DEBUG_ERROR, (" CompName : %s\n", pAlarmInfo->compName.value));
    clCorMoIdNameToMoIdGet(&moidName,&(pAlarmInfo->moId));

    pAlarmInfo->alarmState      = CL_ALARM_STATE_ASSERT;
    pAlarmInfo->category        = CL_ALARM_CATEGORY_QUALITY_OF_SERVICE;
    pAlarmInfo->specificProblem = 0;
    pAlarmInfo->severity        = CL_ALARM_SEVERITY_CRITICAL;
    gettimeofday(&alarmTime,NULL);
    pAlarmInfo->eventTime       = alarmTime.tv_sec;
    pAlarmInfo->len = strlen("HelloHelloHelloHelloHelloHelloHelloHello")+1;
    memcpy(pAlarmInfo->buff,"HelloHelloHelloHelloHelloHelloHelloHello",pAlarmInfo->len);

    ClEoExecutionObjT* peoObj=(ClEoExecutionObjT *)arg;
    if ( (rc = clEoMyEoObjectSet(peoObj)) != CL_OK)
    {
        CL_DEBUG_PRINT(CL_DEBUG_ERROR, (" clEoMyEoObjectSet failed, rc:0x%x \n", rc));
        return rc;
    }

	/**
	  * Raising alarm for :
	  * MOId -  /Chassis:0/GigeBlade:0
	  * Category - CL_ALARM_CATEGORY_QUALITY_OF_SERVICE
	  * Probable Cause - CL_ALARM_PROB_CAUSE_BANDWIDTH_REDUCED
	  */
    CL_DEBUG_PRINT(CL_DEBUG_ERROR,("Raising alarm for [%s] and the probable cause\
			[%d]", moidName.value, CL_ALARM_PROB_CAUSE_LOSS_OF_FRAME));
    pAlarmInfo->probCause = CL_ALARM_PROB_CAUSE_BANDWIDTH_REDUCED;
    rc = clAlarmRaise(pAlarmInfo,&alarmHandle);

	/**
	  * Raising alarm for :
	  * MOId - /Chassis:0/GigeBlade:0
	  * Category -  CL_ALARM_CATEGORY_QUALITY_OF_SERVICE
	  * Probable Cause - CL_ALARM_PROB_CAUSE_RESPONSE_TIME_EXCESSIVE
	  */
    pAlarmInfo->probCause = CL_ALARM_PROB_CAUSE_RESPONSE_TIME_EXCESSIVE;
    CL_DEBUG_PRINT(CL_DEBUG_ERROR,("Raising alarm for [%s] and the probable \
		cause [%d]", moidName.value, CL_ALARM_PROB_CAUSE_RESPONSE_TIME_EXCESSIVE));
    rc = clAlarmRaise(pAlarmInfo,&alarmHandle);
    CL_DEBUG_PRINT(CL_DEBUG_ERROR, ("Alarm Category : %d \n",pAlarmInfo->category ));
    CL_DEBUG_PRINT(CL_DEBUG_ERROR, ("Alarm severity: %d \n",pAlarmInfo->severity));

    rc = clAlarmClientResourceInfoGet(alarmHandle, &moId);
    if ( CL_OK != rc)
    {
        clOsalPrintf("Failed while asking the moid for the alarm handle [%d]. rc[0x%x] \n", alarmHandle, rc);
        return rc;
    }

    rc = clCorMoIdToMoIdNameGet(&moId, &moIdName);
    if(CL_OK != rc)
    {
        clOsalPrintf("Failed while getting the mOId name from moid . rc[0x%x]", rc) ;
        return rc;
    }

    clOsalPrintf("The MOID for the alarm handle is [%d] is [%s]\n", alarmHandle, moIdName.value);
	/**
	  * Raising alarm for :
	  * MOId - /Chassis:0/GigeBlade:0/GigePort:0
	  * Category - CL_ALARM_CATEGORY_QUALITY_OF_SERVICE
	  * Probable Cause - CL_ALARM_PROB_CAUSE_LOSS_OF_FRAME
	  */
    CL_DEBUG_PRINT(CL_DEBUG_ERROR,("Raising alarm for [%s] and the probable \
				cause [%d]", moidName2.value, CL_ALARM_PROB_CAUSE_LOSS_OF_FRAME));
    pAlarmInfo->probCause = CL_ALARM_PROB_CAUSE_LOSS_OF_FRAME;
    clCorMoIdNameToMoIdGet(&moidName2,&(pAlarmInfo->moId));

    rc = clAlarmRaise(pAlarmInfo,&alarmHandle);
    CL_DEBUG_PRINT(CL_DEBUG_ERROR, ("Alarm Category : %d \n",pAlarmInfo->category ));
    CL_DEBUG_PRINT(CL_DEBUG_ERROR, ("Alarm severity: %d \n",pAlarmInfo->severity));

    rc = clAlarmClientResourceInfoGet(alarmHandle, &moId);
    if ( CL_OK != rc)
    {
        clOsalPrintf("Failed while asking the moid for the alarm handle [%d]. rc[0x%x] \n", alarmHandle, rc);
        return rc;
    }

    rc = clCorMoIdToMoIdNameGet(&moId, &moIdName);
    if(CL_OK != rc)
    {
        clOsalPrintf("Failed while getting the mOId name from moid . rc[0x%x]", rc) ;
        return rc;
    }

    clOsalPrintf("The MOID for the alarm handle is [%d] is [%s]\n", alarmHandle, moIdName.value);
	/**
	  * Raising alarm for :
	  * MOId -  /Chassis:0/GigeBlade:0/GigePort:0
	  * Category - CL_ALARM_CATEGORY_QUALITY_OF_SERVICE 
	  * Probable Cause - CL_ALARM_PROB_CAUSE_MULTIPLEXER_PROBLEM 
	  */
    CL_DEBUG_PRINT(CL_DEBUG_ERROR,("Raising alarm for [%s] and the probable \
				cause [%d]", moidName2.value, CL_ALARM_PROB_CAUSE_MULTIPLEXER_PROBLEM));
    pAlarmInfo->probCause = CL_ALARM_PROB_CAUSE_MULTIPLEXER_PROBLEM;
    clCorMoIdNameToMoIdGet(&moidName2,&(pAlarmInfo->moId));
    rc = clAlarmRaise(pAlarmInfo,&alarmHandle);
    CL_DEBUG_PRINT(CL_DEBUG_ERROR, ("Alarm Category : %d \n",pAlarmInfo->category ));
    CL_DEBUG_PRINT(CL_DEBUG_ERROR, ("Alarm severity: %d \n",pAlarmInfo->severity));


	/**
	  * Clearing alarm for :
	  * MOId - /Chassis:0/GigeBlade:0/GigePort:0 
	  * Category - CL_ALARM_CATEGORY_QUALITY_OF_SERVICE
	  * Probable Cause - CL_ALARM_PROB_CAUSE_MULTIPLEXER_PROBLEM
	  */
    CL_DEBUG_PRINT(CL_DEBUG_ERROR,("Clearing alarm for [%s] and the probable \
				cause [%d]", moidName.value, CL_ALARM_PROB_CAUSE_MULTIPLEXER_PROBLEM));
    pAlarmInfo->alarmState = CL_ALARM_STATE_CLEAR;
    clCorMoIdNameToMoIdGet(&moidName2,&(pAlarmInfo->moId));
    rc = clAlarmRaise(pAlarmInfo,&alarmHandle);
    CL_DEBUG_PRINT(CL_DEBUG_ERROR, ("Alarm Category : %d \n",pAlarmInfo->category ));
    CL_DEBUG_PRINT(CL_DEBUG_ERROR, ("Alarm severity: %d \n",pAlarmInfo->severity));

	/**
	  * Clearing alarm for :
	  * MOId - /Chassis:0/GigeBlade:0/GigePort:0 
	  * Category - CL_ALARM_CATEGORY_QUALITY_OF_SERVICE
	  * Probable Cause - CL_ALARM_PROB_CAUSE_LOSS_OF_FRAME
	  */
    CL_DEBUG_PRINT(CL_DEBUG_ERROR,("Raising alarm for [%s] and the probable \
				cause [%d]", moidName.value, CL_ALARM_PROB_CAUSE_LOSS_OF_FRAME));
    pAlarmInfo->probCause = CL_ALARM_PROB_CAUSE_LOSS_OF_FRAME;
    rc = clAlarmRaise(pAlarmInfo,&alarmHandle);
    CL_DEBUG_PRINT(CL_DEBUG_ERROR, ("Alarm Category : %d \n",pAlarmInfo->category ));
    CL_DEBUG_PRINT(CL_DEBUG_ERROR, ("Alarm severity: %d \n",pAlarmInfo->severity));
    return rc;
}
ClRcT
clCompAppInitialize(
    ClUint32T argc,
    ClCharT *argv[])
{
    ClNameT             appName;
    ClCpmCallbacksT     callbacks;
    ClVersionT          version;
    ClIocPortT          iocPort;
    ClRcT               rc = CL_OK;

    /*
     * ---BEGIN_APPLICATION_CODE---
     */

    /*
     * Declare other local variables here.
     */

    /*
     * ---END_APPLICATION_CODE---
     */

    /*
     * Get the pid for the process and store it in global variable.
     */

    mypid = getpid();

    /*
     * Initialize and register with CPM. 'version' specifies the version of
     * AMF with which this application would like to interface. 'callbacks'
     * is used to register the callbacks this component expects to receive.
     */

    version.releaseCode                         = 'B';
    version.majorVersion                        = 01;
    version.minorVersion                        = 01;
    
    callbacks.appHealthCheck                    = NULL;
    callbacks.appTerminate                      = clCompAppTerminate;
    callbacks.appCSISet                         = clCompAppAMFCSISet;
    callbacks.appCSIRmv                         = clCompAppAMFCSIRemove;
    callbacks.appProtectionGroupTrack           = NULL;
        
    /*
     * Get IOC Address, Port and Name. Register with AMF.
     */

    clEoMyEoIocPortGet(&iocPort);

    if ( (rc = clCpmClientInitialize(&cpmHandle, &callbacks, &version)) ) 
        goto errorexit;

    /*
     * If this component will provide a service, register it now.
     */

#if HAS_EO_SERVICES

    /* Uncomment the following line if the EO is providing services and the 
       method implementations are available for all the methods defined for this EO.

    rc = clcsa102CompEOClientInstall(void);

    */
#endif

    /*
     * Do the application specific initialization here.
     */

    /*
     * ---BEGIN_APPLICATION_CODE---
     */

    clprintf(CL_LOG_SEV_INFO,"csa102: Initializing and registering with CPM...");

    /*
     * ---END_APPLICATION_CODE---
     */

    /*
     * Now register the component with AMF. At this point it is
     * ready to provide service, i.e. take work assignments.
     */

    if ( (rc = clCpmComponentNameGet(cpmHandle, &appName)) ) 
        goto errorexit;
    if ( (rc = clCpmComponentRegister(cpmHandle, &appName, NULL)) ) 
        goto errorexit;

    /*
     * Initialize the log stream
     */
    clEvalAppLogStreamOpen(appName.value, &gEvalLogStream);
    /*
     * Print out standard information for this component.
     */
    clprintf (CL_LOG_SEV_INFO, "Component [%s] : PID [%ld]. Initializing", appName.value, mypid);
    clprintf (CL_LOG_SEV_INFO, "   IOC Address             : 0x%x", clIocLocalAddressGet());
    clprintf (CL_LOG_SEV_INFO, "   IOC Port                : 0x%x", iocPort);

    /*
     * This is where the application code starts. If the main thread usage
     * policy is CL_EO_USE_THREAD_FOR_APP, then return from this fn only 
     * after the application terminates. If the main thread usage policy is
     * CL_EO_USE_THREAD_FOR_RECV, then return from this fn after doing the
     * application specific initialization and registration. Main thread usage
     * policy can be set through IDE from Component porperty -> Eo properties.
     */

    /*
     * ---BEGIN_APPLICATION_CODE---
     */
    clprintf(CL_LOG_SEV_INFO,"csa102: Instantiated as component instance %s.", appName.value);

    clprintf(CL_LOG_SEV_INFO,"%s: Waiting for CSI assignment...", appName.value);

    while (!exiting)
    {
        if (running)
        {
            clprintf(CL_LOG_SEV_INFO,"csa102: Hello World! %s", show_progress());
        }
        sleep(1);
    }


    /*
     * ---END_APPLICATION_CODE---
     */

    return rc;

errorexit:

    clprintf (CL_LOG_SEV_ERROR, "Component [%s] : PID [%ld]. Initialization error [0x%x]",
              appName.value, mypid, rc);

    return rc;
}
ClRcT clCkptSvrInitialize(void)
{
    ClRcT             rc         = CL_OK;
    /* Variable related ckptDataBackup feature thats not supported
       ClUint8T          ckptRead   = 0;
    */
    ClTimerTimeOutT   timeOut    = {0}; 
    ClIocNodeAddressT deputy = 0;
    ClIocNodeAddressT master = 0;
    ClBoolT           addressUpdate = CL_FALSE;
    SaNameT           appName    = {0};   
 
    /*
     * Allocate the memory for server control block.
     */
    rc = ckptSvrCbAlloc(&gCkptSvr);
    CKPT_ERR_CHECK(CL_CKPT_SVR,CL_LOG_SEV_ERROR, 
                   ("Checkpoint service CB create failed rc[0x %x]\n", rc), rc); 

    /*
     * Mark server as not ready.
     */
    gCkptSvr->serverUp        = CL_FALSE;
    gCkptSvr->condVarWaiting  = CL_TRUE;    

    /*
     * Create condition variable that indicate the receipt
     * of master and deputy ckpt addresses from gms.
     */
    clOsalCondCreate(&gCkptSvr->condVar);
    clOsalMutexCreate(&gCkptSvr->mutexVar);
    
    gCkptSvr->masterInfo.masterAddr = CL_CKPT_UNINIT_ADDR;
    gCkptSvr->masterInfo.deputyAddr = CL_CKPT_UNINIT_ADDR;
    gCkptSvr->masterInfo.compId     = CL_CKPT_UNINIT_VALUE; 
    gCkptSvr->masterInfo.clientHdlCount = 0;
    gCkptSvr->masterInfo.masterHdlCount = 0; 

    /*
     * Initialize gms to get the master and deputy addresses.
     */
    clOsalMutexLock(&gCkptSvr->ckptClusterSem);
    rc = clCkptMasterAddressesSet();
    master = gCkptSvr->masterInfo.masterAddr;
    deputy = gCkptSvr->masterInfo.deputyAddr;
    clOsalMutexUnlock(&gCkptSvr->ckptClusterSem);

    rc = clEoMyEoObjectGet(&gCkptSvr->eoHdl);
    rc = clEoMyEoIocPortGet(&gCkptSvr->eoPort);
   
    /*
     * Install the ckpt native table.
     */
    rc = clCkptEoClientInstall();
    CL_ASSERT(rc == CL_OK);
    
    rc = clCkptEoClientTableRegister(CL_IOC_CKPT_PORT);
    CL_ASSERT(rc == CL_OK);

    /*
     * Initialize the event client library.
     */
    ckptEventSvcInitialize();
    
    /* 
     * Initialize ckpt lib for persistent memory.
     * Obtain ckptRead flag that will tell whether ckpt server needs to 
     * read data from persistent memory or not.
     */

    /*
      Feature not yet supported see bug 6017 -- Do not forget to uncomment ckptDataBackupFinalize
      rc = ckptDataBackupInitialize(&ckptRead);
    */

    if(rc != CL_OK)
    {
        clLogWrite(CL_LOG_HANDLE_APP, CL_LOG_SEV_WARNING, NULL,
                   CL_LOG_MESSAGE_2_LIBRARY_INIT_FAILED, "ckpt", rc);
    }

    if( gCkptSvr->localAddr == master )
    {
        /*
         * The node coming up is master. If deputy exists, syncup with deputy
         * else syncup with persistant memory (if existing).
         */
        rc = clCpmComponentNameGet(gCkptSvr->amfHdl, &appName);
        if(clCpmIsCompRestarted(appName))
        {
            if((deputy != CL_CKPT_UNINIT_ADDR) && ( (ClInt32T) deputy != -1))
            {
                rc = ckptMasterDatabaseSyncup(deputy);
                /*
                 * If deputy server is not reachable then pull info from the 
                 * persistent memory.
                 */
                if(CL_RMD_TIMEOUT_UNREACHABLE_CHECK(rc))
                {
                    clLogNotice(CL_CKPT_AREA_ACTIVE, "DBS", 
                                "Database Syncup with ckpt master failed with RMD timeout error. rc 0x%x",rc);
                    /* This is dead code as the feature is not supported
                       if(ckptRead == 1)
                       {
                       rc = ckptPersistentMemoryRead();
                       }
                    */
                }
            }
        }
        /* This is dead code as the feature is not supported
           else
           {
           if(ckptRead == 1)
           {
           rc = ckptPersistentMemoryRead();
           }
           }
        */
    }
    
    /*TODO:This check is only for seleting the deputy or for what */
    clOsalMutexLock(gCkptSvr->mutexVar);    
    if( (clIocLocalAddressGet() != master) &&
        (gCkptSvr->condVarWaiting == CL_TRUE)     )
    {
        /*
         * Ensure that the node gets the master and deputy addresses before
         * proceeding further.
         */
        timeOut.tsSec            = 5;
        timeOut.tsMilliSec       = 0;
        clOsalCondWait(gCkptSvr->condVar, gCkptSvr->mutexVar, timeOut);
        gCkptSvr->condVarWaiting = CL_FALSE;
        addressUpdate = CL_TRUE;
    }
    clOsalMutexUnlock(gCkptSvr->mutexVar);    

    /*  
     * We double check again incase we had waited for the gms cluster track.
     * but with the right lock sequence below instead of shoving it in the
     * condwait above.
     */
    if(addressUpdate == CL_TRUE)
    {
        clOsalMutexLock(&gCkptSvr->ckptClusterSem);
        master = gCkptSvr->masterInfo.masterAddr;
        deputy = gCkptSvr->masterInfo.deputyAddr;
        clOsalMutexUnlock(&gCkptSvr->ckptClusterSem);
    }
    /* 
     * Announce the arrival to peer in the n/w. Master server announces to 
     * all and other servers announce to master server.
     */
    ckptSvrArrvlAnnounce();
    
    /*
     * If the node coming up is deputy, syncup the metadata and ckpt info 
     * from the master. Treat all SC capable nodes except the master as deputy.
     */
    if(  gCkptSvr->localAddr != master && clCpmIsSCCapable())
    {
        /*
         * Just freezing the deputy till syncup, not to receive any master
         * related calls, this is to ensure that deputy is in full synup with
         * master and any calls from master to update deputy will sleep on the
         * lock.
         */
        CKPT_LOCK(gCkptSvr->masterInfo.ckptMasterDBSem);
        ckptMasterDatabaseSyncup(gCkptSvr->masterInfo.masterAddr);
        CKPT_UNLOCK(gCkptSvr->masterInfo.ckptMasterDBSem);
    }
    
    /* 
     * Server is up.
     */
    gCkptSvr->serverUp = CL_TRUE;
    return rc;
    exitOnError:
    {
        return rc;
    }
}
ClRcT clCkptMasterAddressesSet()
{
    ClRcT rc = CL_OK;
#ifdef CL_CKPT_GMS 
    /*
     * GMS available.
     */
     
    /* 
     * Contact GMS to get master and backup master addresses.
     */
    ClGmsClusterNotificationBufferT notBuffer;
    memset((void*)&notBuffer , 0, sizeof(notBuffer));
    memset( &notBuffer , '\0' ,sizeof(ClGmsClusterNotificationBufferT));
    
    /*
     * Initialize the gms client library.
     */
    rc = clGmsInitialize(&gCkptSvr->gmsHdl, &ckptGmsCallbacks,
                        &gVersion);
    CKPT_ERR_CHECK(CL_CKPT_SVR,CL_LOG_SEV_ERROR,
    (" clCkptMasterAddressesSet failed rc[0x %x]\n",rc),
        rc);
        
    /* 
     * Register for current track and track changes.
     */
    rc = clGmsClusterTrack(gCkptSvr->gmsHdl, 
                           CL_GMS_TRACK_CHANGES|CL_GMS_TRACK_CURRENT, 
                           &notBuffer);
                           
    /*
     * Call the track change callback function. This is needed for getting
     * current track information.
     */
    if(rc == CL_OK && notBuffer.leader &&
       notBuffer.leader != CL_GMS_INVALID_NODE_ID)
    {
        _clCkptAddressesUpdate(&notBuffer);
    }

    if (notBuffer.notification != NULL)
      clHeapFree(notBuffer.notification);

#else
    /*
     * GMS unavailable.
     */

     /*
      * Select cpm master as ckpt master. Deputy will be unspecified.
      */
    clCpmMasterAddressGet(&gCkptSvr->masterInfo.masterAddr);
    gCkptSvr->masterInfo.deputyAddr = -1;

    /*
     * Update the TL with ckpt master address.
     */
    if(gCkptSvr->masterInfo.masterAddr == gCkptSvr->localAddr )
    {
        ClIocTLInfoT tlInfo = {0};
        ClUint32T    compId = 0; 
        SaNameT      name   = {0};
 
        clCpmComponentNameGet(gCkptSvr->amfHdl, &name);
        clCpmComponentIdGet(gCkptSvr->amfHdl, &name, &compId);
        tlInfo.compId                   = compId;
        gCkptSvr->masterInfo.compId     = compId;
        ckptOwnLogicalAddressGet(&tlInfo.logicalAddr);
        tlInfo.contextType              = CL_IOC_TL_GLOBAL_SCOPE;
        tlInfo.physicalAddr.nodeAddress = clIocLocalAddressGet();
        tlInfo.physicalAddr.portId      = CL_IOC_CKPT_PORT;
        tlInfo.haState                  = CL_IOC_TL_ACTIVE;
        rc = clIocTransparencyRegister(&tlInfo);
    }
#endif
#ifdef CL_CKPT_GMS 
exitOnError:
#endif
    {
        return rc;
    }
}
/*
 * This function will be called either from GMS track callback or 
 * IOC notification, it receives the master address & deputy and 
 * process the same
 */
ClRcT
clCkptMasterAddressUpdate(ClIocNodeAddressT  leader, 
                          ClIocNodeAddressT  deputy)
{
    ClIocTLInfoT tlInfo    = {0};
    SaNameT      name      = {0};
    ClRcT        rc        = CL_OK;
    ClBoolT      updateReq = CL_FALSE;

    /*
     * Check whether master or deputy address has changed.
     */
    if(gCkptSvr->masterInfo.masterAddr != leader)
    {
        /*
         * Master address changed.
         */
        updateReq = CL_TRUE;
        gCkptSvr->masterInfo.prevMasterAddr = gCkptSvr->masterInfo.masterAddr;    
        gCkptSvr->masterInfo.masterAddr     = leader;    
        
        /*
         * Deregister the old TL entry.
         */
        if(gCkptSvr->masterInfo.compId != CL_CKPT_UNINIT_VALUE)
        {
            rc = clIocTransparencyDeregister(gCkptSvr->masterInfo.compId);
        }
        else
        {
            clCpmComponentNameGet(gCkptSvr->amfHdl, &name);
            clCpmComponentIdGet(gCkptSvr->amfHdl, &name, 
                                &gCkptSvr->compId);
            gCkptSvr->masterInfo.compId = gCkptSvr->compId;
        }

        /*
         * Update the TL.
         */
        if(gCkptSvr->masterInfo.masterAddr == clIocLocalAddressGet())
        {
            ckptOwnLogicalAddressGet(&tlInfo.logicalAddr);
            tlInfo.compId                   = gCkptSvr->compId;
            gCkptSvr->masterInfo.compId     = gCkptSvr->compId;
            tlInfo.contextType              = CL_IOC_TL_GLOBAL_SCOPE;
            tlInfo.physicalAddr.nodeAddress = clIocLocalAddressGet();
            tlInfo.physicalAddr.portId      = CL_IOC_CKPT_PORT;
            tlInfo.haState                  = CL_IOC_TL_ACTIVE;
            rc = clIocTransparencyRegister(&tlInfo);
        }
        /*
         * update the ioc notify callbacks for the new master address 
         * Once address update is over, then we have uninstall the registered
         * callback and reregistered to new master address
         */
        clCkptIocCallbackUpdate();
    }
    
    if(gCkptSvr->masterInfo.deputyAddr != deputy)
    {
        /*
         * Deputy address has changed.
         */
        updateReq = CL_TRUE;
        gCkptSvr->masterInfo.deputyAddr = deputy ;    
    }

    /*
     * Signal the receipt of master and deputy addresses. 
     */
    clOsalMutexLock(gCkptSvr->mutexVar);
    if(gCkptSvr->condVarWaiting == CL_TRUE)
    {
        gCkptSvr->condVarWaiting = CL_FALSE;
        clOsalCondSignal(gCkptSvr->condVar);
    }
    clOsalMutexUnlock(gCkptSvr->mutexVar);

    /* 
     * Update the old master(if existing) with the new leader addresses.
     */
    if((updateReq == CL_TRUE) && 
       (((ClInt32T) gCkptSvr->masterInfo.prevMasterAddr != -1) &&
       (gCkptSvr->masterInfo.prevMasterAddr != CL_CKPT_UNINIT_ADDR)))
    {
        rc = ckptIdlHandleUpdate(gCkptSvr->masterInfo.prevMasterAddr,
                                 gCkptSvr->ckptIdlHdl,0);
        rc = VDECL_VER(clCkptLeaderAddrUpdateClientAsync, 4, 0, 0)(gCkptSvr->ckptIdlHdl,
                                    gCkptSvr->masterInfo.masterAddr,
                                    gCkptSvr->masterInfo.deputyAddr,
                                    NULL,0);
    }
    clLogNotice("ADDR", "UPDATE", "CKPT master [%d], deputy [%d]",
                gCkptSvr->masterInfo.masterAddr, gCkptSvr->masterInfo.deputyAddr);
    return rc;
}
ClRcT _clTxnAgentProcessMgrCmd(
        CL_IN   ClBufferHandleT     inMsgHandle,
        CL_IN   ClBufferHandleT     outMsgHandle,
        CL_IN   ClTxnMessageHeaderT *pMsgHdr)
{
    ClRcT   rc  = CL_OK;
    ClTxnCmdT   tCmd = {.resp = CL_OK };
    ClTxnCommHandleT commHandle = NULL;
    ClUint32T   mCount = pMsgHdr->msgCount;
    ClTimeT t1, t2;

    
    CL_FUNC_ENTER();

    clLogDebug("AGT", NULL,
            "Received processing cmd from TM. Message count [%d]", 
            pMsgHdr->msgCount);
    t1 = clOsalStopWatchTimeGet();

    while ( (CL_OK == tCmd.resp) && (pMsgHdr->msgCount > 0) )
    {

        pMsgHdr->msgCount--;

        rc = VDECL_VER(clXdrUnmarshallClTxnCmdT, 4, 0, 0)(inMsgHandle, &tCmd);
        switch (tCmd.cmd)
        {
            case CL_TXN_CMD_INIT:
                rc = clTxnAgentTxnDefnReceive(tCmd, inMsgHandle); 
                if(CL_OK != rc)
                {
                    clLogError("AGT", "MTA",
                            "Failed to process init command from manager, rc=[0x%x]",
                            rc);
                    /* Construct payload to send response back to server */
                    clTxnMutexLock(clTxnAgntCfg->actMtx);
                    
                   /* tCmd.resp = rc; */

                    rc = clTxnCommIfcNewSessionCreate(CL_TXN_MSG_AGNT_RESP, 
                                                      pMsgHdr->srcAddr, 
                                                      CL_TXN_SERVICE_AGENT_RESP_RECV, 
                                                      NULL, CL_TXN_RMD_DFLT_TIMEOUT,  
                                                      CL_TXN_COMMON_ID, /* Value is 0x1 */
                                                      &commHandle);
                    if (CL_OK == rc)
                    {
                        rc = clTxnCommIfcSessionAppendTxnCmd(commHandle, &tCmd);

                        if (CL_OK != rc)
                        {
                            clLogError("AGT", NULL,
                                    "Failed to append cmd in the response with error [0x%x]",
                                    rc); 
                            clTxnMutexUnlock(clTxnAgntCfg->actMtx);
                            break;
                        }
                        rc = clTxnCommIfcSessionRelease(commHandle);
                        if (CL_OK != rc)
                        {
                            clLogError("AGT", NULL,
                                    "Failed to release session with error[0x%x]",
                                    rc); 
                            clTxnMutexUnlock(clTxnAgntCfg->actMtx);
                            break;
                        }
                        clTxnMutexUnlock(clTxnAgntCfg->actMtx);
                    }
                    else
                        clLogError("AGT", "ATM", 
                                "Failed to create new session for key [Node:0x%x,Port:0x%x]", 
                                pMsgHdr->srcAddr.nodeAddress, pMsgHdr->srcAddr.portId);
                    break;

                }
                /* Request for the first time */
                if(mCount == (pMsgHdr->msgCount + 1) )
                {
                    rc = _clTxnAgentTxnStart(tCmd);
                    if(CL_OK != rc)
                    {
                        /*tCmd.resp = rc; */
                        clLogError("AGT", "MTA",
                                "Failed to start transaction[0x%x:0x%x], rc=[0x%x]",
                                tCmd.txnId.txnMgrNodeAddress,
                                tCmd.txnId.txnId,
                                rc);
                        break;
                    }
                    clLogDebug("AGT", "MTA",
                            "Transaction[0x%x:0x%x] started",
                            tCmd.txnId.txnMgrNodeAddress,
                            tCmd.txnId.txnId);
                }
                break;

            case CL_TXN_CMD_PREPARE:
            case CL_TXN_CMD_1PC_COMMIT:
            case CL_TXN_CMD_2PC_COMMIT:
            case CL_TXN_CMD_ROLLBACK:
                rc = clTxnAgentProcessJob(pMsgHdr, tCmd, outMsgHandle, &commHandle);
                if(CL_OK != rc)
                {
                  /*  tCmd.resp = rc; */
                    clLog(CL_LOG_ERROR, "AGT", NULL,
                            "Error in processing cmd [%s] from server. rc [0x%x]", 
                            _clTxnCmdNameGet(tCmd.cmd), rc);
                }
                if(!pMsgHdr->msgCount && 
                    ( (tCmd.cmd == CL_TXN_CMD_ROLLBACK) || 
                      (tCmd.cmd == CL_TXN_CMD_2PC_COMMIT) ) 
                  )
                {
                    rc = _clTxnAgentTxnStop(tCmd);
                    if(CL_OK != rc)
                    {
                       /* tCmd.resp = rc; */
                        clLogError("AGT", "MTA",
                                "Failed to stop transaction[0x%x:0x%x], rc=[0x%x]",
                                tCmd.txnId.txnMgrNodeAddress,
                                tCmd.txnId.txnId, rc);
                    }
                    else
                        clLogDebug("AGT", "MTA",
                                "Transaction[0x%x:0x%x] stopped",
                                tCmd.txnId.txnMgrNodeAddress,
                                tCmd.txnId.txnId);
                }
                
                /* Remove the joblist when ROLLBACK or COMMIT is complete */
                if( (tCmd.cmd == CL_TXN_CMD_ROLLBACK) || 
                    (tCmd.cmd == CL_TXN_CMD_2PC_COMMIT) ) 
                {
                    ClTxnDefnPtrT pTxnDefn = NULL;
                    clLogDebug("AGT", NULL,
                            "Received remove cmd from server");
                    rc = clTxnDbTxnDefnGet(clTxnAgntCfg->activeTxnMap, 
                                    tCmd.txnId, &pTxnDefn);
                    if(CL_OK == rc)
                    {
                        if(1 < pTxnDefn->jobCount)
                        {
                            rc = clTxnAppJobRemove(pTxnDefn, tCmd.jobId);
                            if(CL_OK != rc)
                            {
                                ClNameT name = {0};
                                clCpmComponentNameGet(0, &name);
                                clLog(CL_LOG_ERROR, "AGT", NULL,
                                     "REMOVE cmd received. Error in removing the job information for component [%s] rc [0x%x]", 
                                     name.value, rc);
                                return rc;
                            }

                        }
                        else if(1 == pTxnDefn->jobCount) /* This is the last job, delete the entire txn list */
                        {
                            ClCntNodeHandleT nodeHandle;
                            rc  = clCntNodeFind(
                                    clTxnAgntCfg->activeTxnMap, 
                                    (ClCntKeyHandleT )&(tCmd.txnId), 
                                    &nodeHandle);
                            if(rc == CL_OK)
                            {
                                rc = clCntNodeDelete(clTxnAgntCfg->activeTxnMap, nodeHandle);
                                if(CL_OK != rc)
                                {
                                    clLog(CL_LOG_ERROR, "AGT", NULL, 
                                         "REMOVE cmd received. Error in deleting txn defn for txnId [0x%x] rc [0x%x]", 
                                         tCmd.txnId.txnId, rc);
                                    return rc;
                                }
                            }

                        }
                        else
                        {
                            clLog(CL_LOG_ERROR, "AGT", NULL,
                            "Remove cmd received. There is no txndefn corresponding to txnId [0x%x]. Jobcount [%d]\n",
                             tCmd.txnId.txnId, pTxnDefn->jobCount);
                        }
                    }
                }
                
                break;
                default:
                    clLog(CL_LOG_ERROR, "AGT", NULL, 
                        "Invalid command received from TM [0x%x]", tCmd.cmd);
                    rc = CL_ERR_INVALID_PARAMETER;
                    break;
        }
    }
    if((tCmd.cmd != CL_TXN_CMD_REMOVE_JOB) && commHandle)
    {
        rc = clTxnCommIfcReadMessage(commHandle, outMsgHandle);
        if(CL_OK != rc)
        {
            clLogError("AGT", NULL,
                    "Failed to write the response with error [0x%x]",
                    rc);
        }
        else
            clLogDebug("AGT", "ATM",
                    "Successfully sent response back");
        t2 = clOsalStopWatchTimeGet();
        clLogDebug("AGT", NULL,
                "Time taken to complete command[%d], [%lld]usecs",
                tCmd.cmd, (t2-t1) );
    }

    if (CL_OK != rc)
    {
            rc = CL_GET_ERROR_CODE(rc);
    }

    CL_FUNC_EXIT();
    return (rc);
}
ClRcT clDebugLibInitialize(void)
{
    ClEoExecutionObjT  *pEoObj     = NULL;
    ClDebugObjT        *pDebugObj  = NULL;
    ClRcT              rc          = CL_OK;
    ClNameT            compName    = {0};
    
    rc = clEoMyEoObjectGet(&pEoObj);
    if (CL_OK != rc)
    {
        return rc;
    }

    pDebugObj = clHeapCalloc(1, sizeof(ClDebugObjT));
    if (NULL == pDebugObj)
    {
        clLogWrite(CL_LOG_HANDLE_APP,CL_LOG_CRITICAL,CL_DEBUG_LIB_CLIENT,
                   CL_LOG_MESSAGE_0_MEMORY_ALLOCATION_FAILED);
        return CL_DEBUG_RC(CL_ERR_NO_MEMORY);
    }

    rc = clOsalTaskKeyCreate(&pDebugObj->debugTaskKey, NULL);
    if(rc != CL_OK)
    {
        CL_DEBUG_PRINT(CL_DEBUG_ERROR, ("Debug task key create returned with [%#x]\n", rc));
        clHeapFree(pDebugObj);
        return CL_DEBUG_RC(CL_GET_ERROR_CODE(rc));
    }

    rc = clHandleDatabaseCreate(NULL, &pDebugObj->hDebugFnDB);
    if( CL_OK != rc )
    {
        CL_DEBUG_PRINT(CL_DEBUG_ERROR, ("clHandleDatabaseCreate(): rc[0x %x]",
                rc));
        clHeapFree(pDebugObj);
        return CL_DEBUG_RC(CL_ERR_NO_MEMORY);
    }

    /* Getting the compName from CPM */
    rc = clCpmComponentNameGet(0, &compName);
    if( CL_OK != rc )
    {
        CL_DEBUG_PRINT(CL_DEBUG_ERROR, ("clCpmComponentNameGet(): rc[0x %x]",
                    rc));
        clLogWrite(CL_LOG_HANDLE_APP,CL_LOG_WARNING,CL_DEBUG_LIB_CLIENT,
                   CL_LOG_MESSAGE_1_INVALID_PARAMETER, 
                   "CompNameGet is not proper");
        return rc;
    }

    pDebugObj->numFunc       = 0;
    /* Assining the compName */
    memset(pDebugObj->compName, '\0', CL_DEBUG_COMP_NAME_LEN);
    if( compName.length < CL_DEBUG_COMP_NAME_LEN )
    {
        memcpy(pDebugObj->compName, compName.value, compName.length);
        pDebugObj->compName[compName.length] = '\0';
    }
    else
    {
        clLogWrite(CL_LOG_HANDLE_APP,CL_LOG_WARNING,CL_DEBUG_LIB_CLIENT,
                   CL_LOG_MESSAGE_1_INVALID_PARAMETER,"CompName is Invalid");
        return CL_DEBUG_RC(CL_ERR_INVALID_PARAMETER);
    }

    /* Assigning compPrompt to DEFAULT */
    memset(pDebugObj->compPrompt, '\0', CL_DEBUG_COMP_PROMPT_LEN);
    strcpy(pDebugObj->compPrompt, "DEFAULT");

    rc = clEoClientInstallTablesWithCookie( pEoObj, 
                                            CL_EO_SERVER_SYM_MOD(gAspFuncTable, DEBUGCli),
                                            pDebugObj);
    if (CL_OK != rc)
    {
        CL_DEBUG_PRINT(CL_DEBUG_ERROR, ("clEoClientInstall(): rc[0x %x]", rc));
        clHandleDatabaseDestroy(pDebugObj->hDebugFnDB);
        clHeapFree(pDebugObj);
        return rc;
    }
    rc = clDebugClientTableRegister(pEoObj);
    if(CL_OK != rc)
    {
        clEoClientUninstallTables(pEoObj, 
                                  CL_EO_SERVER_SYM_MOD(gAspFuncTable, DEBUGCli));
        clHandleDatabaseDestroy(pDebugObj->hDebugFnDB);
        clHeapFree(pDebugObj);
        return rc;
    }

    rc = clEoPrivateDataSet(pEoObj, CL_EO_DEBUG_OBJECT_COOKIE_ID, pDebugObj);
    if (CL_OK != rc)
    {
        CL_DEBUG_PRINT(CL_DEBUG_ERROR, ("clEoPrivateDataSet(): rc[0x %x]", rc));
        clEoClientUninstallTables(pEoObj, 
                                  CL_EO_SERVER_SYM_MOD(gAspFuncTable, DEBUGCli));
        clHandleDatabaseDestroy(pDebugObj->hDebugFnDB);
        clHeapFree(pDebugObj);
        return rc;
    }
    
    clEoDebugRegister();

    return rc;
}