ClRcT
clLogStreamOwnerCheckpointCreate(ClLogSOEoDataT  *pSoEoEntry,
                                 SaNameT         *pCkptName,
                                 ClHandleT       *phCkpt)
{
    ClRcT         rc     = CL_OK;
    ClCkptCheckpointCreationAttributesT  creationAtt    = {0};
    ClCkptOpenFlagsT                     openFlags      = 0;
    ClLogSvrCommonEoDataT                *pCommonEoData = NULL;
    ClUint32T                            sectionSize    = 0;
    ClInt32T                             tries = 0;
    ClIocNodeAddressT                    localAddr = clIocLocalAddressGet();
    static ClTimerTimeOutT delay = { 0,  500};

    CL_LOG_DEBUG_TRACE(("Enter"));
    
    rc = clLogStreamOwnerEoEntryGet(NULL, &pCommonEoData);
    if( CL_OK != rc )
    {
        return rc;
    }

    creationAtt.creationFlags     = CL_CKPT_CHECKPOINT_COLLOCATED | CL_CKPT_ALL_OPEN_ARE_REPLICAS;
    creationAtt.checkpointSize    = pCommonEoData->maxStreams * CL_LOG_SO_SEC_SIZE; 
    creationAtt.retentionDuration = CL_STREAMOWNER_CKPT_RETENTION_DURATION;
    creationAtt.maxSections       = pCommonEoData->maxStreams;
    sectionSize                   = pCommonEoData->maxComponents * sizeof(ClLogCompKeyT); 
    creationAtt.maxSectionSize    = CL_LOG_SO_SEC_SIZE + sectionSize;
    creationAtt.maxSectionIdSize  = CL_LOG_SO_SEC_ID_SIZE;

    openFlags = CL_CKPT_CHECKPOINT_CREATE | CL_CKPT_CHECKPOINT_WRITE | CL_CKPT_CHECKPOINT_READ;

    reopen:
    rc = clCkptCheckpointOpen(pCommonEoData->hSvrCkpt, pCkptName, &creationAtt, openFlags, 5000L, &pSoEoEntry->hCkpt);
    if( rc != CL_OK )
    {
        /*
         * No replica found and we are the only master.
         * Delete and try re-opening the checkpoint
         */
        if(CL_GET_ERROR_CODE(rc) == CL_ERR_NO_RESOURCE &&
           pCommonEoData->masterAddr == localAddr)
        {
            if(tries++ < 1)
            {
                clLogNotice("CKP", "GET", "No replica for log checkpoint."
                            "Deleting ckpt [%.*s] and retrying the ckpt open",
                            pCkptName->length, pCkptName->value);
                clCkptCheckpointDelete(pCommonEoData->hSvrCkpt, pCkptName);
                clOsalTaskDelay(delay);
                goto reopen;
            }
        }
        CL_LOG_DEBUG_ERROR(("clCkptCheckpointOpen(): rc[0x %x]", rc));
    }    

    CL_LOG_DEBUG_TRACE(("Exit"));
    return rc;
}    
/*******************************************************************************
Feature  API: clTcCkptDelete

Description : This API will first call Checkpoint Close and then 
              Checkpoint delete. The latter function requires the
			  name given to the checkpoint, during Checkpoint open.

Arguments In: 
	1. ClTcCkptDataT : contains the ckpt handle
	2. Checkpoint Name

Arguments Out:
	1. ClTcCkptDataT : returns time taken to write the section

Return Value:
	integer 0 if success, non zero if failure
*******************************************************************************/
int clTcCkptDelete ( 
	const char*	   ckpt_name,
	ClTcCkptDataT* ckpt_data )
{
	ClRcT 		ret_code = CL_OK;
	ClNameT 	ckpt_name_t={0};
    ClTimeT startTime = 0;
    ClTimeT endTime = 0;
	ClTimeT time_taken_us =0;

	/* Initialize name struct for ckpt
	 */
	strncpy(ckpt_name_t.value, ckpt_name,CL_MAX_NAME_LENGTH-1);
	ckpt_name_t.length = strlen(ckpt_name_t.value);

	/* time check 1 start 
	 */
    startTime = clOsalStopWatchTimeGet();

	/* Delete checkpoint (test: check memory profile to ensure all resources
	 * are actually released)
	 */
	ret_code = clCkptCheckpointDelete( ckpt_svc_hdl, &ckpt_name_t);
	if ( ret_code != CL_OK )
	{
		printf("clTcCkptDelete: Failed to delete checkpoint %s: 0x%d \n",
			   ckpt_name, ret_code); 
	}
	ret_code = clCkptCheckpointClose((ClCkptHdlT)ckpt_data->ckpt_hdl);
	if ( ret_code != CL_OK )
	{
		printf("clTcCkptDelete: Failed to close checkpoint %s: 0x%d \n",
			   ckpt_name, ret_code); 
	}


	/* time check 1 end 
	 */
    endTime = clOsalStopWatchTimeGet();
	time_taken_us = endTime - startTime;

	ckpt_data->time_taken_ms = 0;
	ckpt_data->time_taken_us  = time_taken_us;

	return ret_code;
}
SaAisErrorT saCkptCheckpointUnlink(SaCkptHandleT ckptHandle,
                                   const SaNameT *checkpointName)
{
    ClRcT         rc    = CL_OK;
    SaAisErrorT   safRc = SA_AIS_OK;

    /*
     * Call the corresponding ckpt client library function.
     */
    rc = clCkptCheckpointDelete((ClCkptSvcHdlT) ckptHandle,
            (SaNameT *)checkpointName);

    /*
     * Translate the clovis error type to SAF error type.
     */
    clErrorTxlate(rc, &safRc);
    
    return safRc;
}
/*******************************************************************************
Feature  API: clTcCkptCreate

Description : Create a checkpoint given a name and the number of sections. In 
addition the nature of the checkpoint needs to be specified, synchronous versus 
asynchronous. If asynchronous collocated versus non collocated.

This API will not attempt to validate arguments, the thinking being that 
this is a volitional act by the invoker of this API to ensure that invalid 
parameters can be handled gracefully by the subsystem

Arguments In: 
	1. Checkpoint Name
	2. Section Name Prefix; if NULL no section names; if not NULL then the 
	                        section names will range from 
							<section_name_Prefix>1 to <section_name_prefix>9999
	3. Number of Sections
	4. Size of section
	5. Synchronous/Asynchronous Collocated/Asynhrnous Noncollocated
	6. Output data:

Arguments Out:
	1. ClTcCkptDataT : returns time taken to create ckpt, and ckpt_handle

Return Value:
	integer 0 if success, non zero if failure
*******************************************************************************/
int
clTcCkptCreate (
	const char 		*ckpt_name,
	const char 		*section_name_prefix,
	int				num_sections,
	int				section_size,
	ClTcCkptTypeE	ckpt_type,
	ClTcCkptDataT	*ckpt_data )
{

	ClRcT 								ret_code = CL_OK;
	ClNameT 							ckpt_name_t = {0};
	ClCkptCheckpointCreationAttributesT	ckpt_cr_attr;
	ClCkptOpenFlagsT					ckpt_open_flags;
	ClTimeT								timeout;

	int									section_num;
	ClCharT								section_id_name[ CL_MAX_NAME_LENGTH ];
	ClUint8T							*section_name_ptr;
    ClCkptSectionIdT          			section_id;
    ClCkptSectionCreationAttributesT    section_cr_attr;
#ifdef PRE_ALLOCATE_SECTION
	ClPtrT							    section_data;
#endif

    ClTimeT startTime = 0;
    ClTimeT endTime = 0;
    ClTimeT time_taken_us = 0;

	/* First ensure that the Initialize function is called
	 */
	ret_code = clTcCkptSvcInit();
	if (ret_code != CL_OK)
	{
		printf("clTcCkptCreate: failed to initialze service \n");
		return ret_code;
	}

	/* Initiailze name struct for ckpt
	 */
	strncpy(ckpt_name_t.value, ckpt_name, CL_MAX_NAME_LENGTH-1);
	ckpt_name_t.length = strlen(ckpt_name_t.value);

	/* Get the max size for a  name of sectionId
	 */
	if (section_name_prefix != NULL)
	{
		snprintf(section_id_name,CL_MAX_NAME_LENGTH, "%s%05d", section_name_prefix, num_sections );
	}
	else
	{
		snprintf(section_id_name,CL_MAX_NAME_LENGTH, "s%05d", num_sections);	 
	}


	/* Initialize check point creation flags
	 */
	switch (ckpt_type)
	{
		case TC_CKPT_SYNC:
			ckpt_cr_attr.creationFlags = CL_CKPT_WR_ALL_REPLICAS;
			break;

		case TC_CKPT_ASYNC_COLLOC:
			ckpt_cr_attr.creationFlags = CL_CKPT_CHECKPOINT_COLLOCATED;
			break;

		case TC_CKPT_ASYNC_NON_COLLOC:
			ckpt_cr_attr.creationFlags = CL_CKPT_WR_ACTIVE_REPLICA;
			break;

		default:
			printf("clTcCkptCreate: (warning) invalid checkpoint type\n");
			ckpt_cr_attr.creationFlags = ckpt_type;
	}

	/* Maximum checkpoint size = size of all checkpoints combined
	 */
	ckpt_cr_attr.checkpointSize = num_sections * section_size;

	/* Can make this a configurable parameter when reading from 
	 * a file as opposed to API arguments; for now hardcoded to
	 * forever
	 */
	ckpt_cr_attr.retentionDuration = (ClTimeT)-1;

	ckpt_cr_attr.maxSections = num_sections;

	ckpt_cr_attr.maxSectionSize = section_size;

	ckpt_cr_attr.maxSectionIdSize = (ClSizeT)(strlen(section_id_name)+1);

	/* Initialize the checkpoint open flags
	 */
	ckpt_open_flags = (CL_CKPT_CHECKPOINT_READ  |
					   CL_CKPT_CHECKPOINT_WRITE |
					   CL_CKPT_CHECKPOINT_CREATE);

	/* Can make this a configurable parameter when reading from 
	 * a file as opposed to API arguments; for now hardcoded to
	 * forever
	 */
	timeout = (ClTimeT)-1;

	/* time check 1 start 
	 */
    startTime = clOsalStopWatchTimeGet();

	ret_code = clCkptCheckpointOpen(ckpt_svc_hdl, 
									&ckpt_name_t, 
									&ckpt_cr_attr,
									ckpt_open_flags,
									timeout,
									( ClCkptHdlT *)(&ckpt_data->ckpt_hdl));
	/* time check 1 end
	 */
    endTime = clOsalStopWatchTimeGet();

	time_taken_us = endTime - startTime;

	ckpt_data->time_taken_ms = 0;
	ckpt_data->time_taken_us  = time_taken_us;

	if (ret_code != CL_OK)
	{
		printf("clTcCkptCreate: Failed to create ckpt:0x%x \n", ret_code);
		return ret_code;
	}

	/* Intialize section create arguments 
	 */
	
	section_id.idLen = (ClUint16T)strlen(section_id_name); 
	section_id.id    = (ClUint8T*)section_id_name;

	/* If there is a section name prefix, then set the
	 * prefix and advance a pointer to affix the unique
	 * id of a section within the section create loop
	 */
	if ( section_name_prefix != NULL )
	{
		snprintf((ClCharT*)section_id.id,CL_MAX_NAME_LENGTH, "%s", section_name_prefix);
		/* pointer to the part of the string that the 
	 	 * unique identifier of a section will be placed
	 	 */
		section_name_ptr = section_id.id + strlen(section_name_prefix);
	}
	else
	{
		snprintf((ClCharT*)section_id.id, CL_MAX_NAME_LENGTH,"s");

		section_name_ptr = section_id.id + 1; 
	}


	/* Expiration time for section can also be varied
	 * once parameters are read from a configuration file
	 */
	section_cr_attr.expirationTime = (ClTimeT)CL_TIME_END;

	/* ensure that the section ids need to be named
	 */
	section_cr_attr.sectionId = &section_id;

#ifdef PRE_ALLOCATE_SECTION
	/* create a data buffer, because the size given to
	 * the section at creation remains with it forever
	 * not sure if this is a bug
	 */
	section_data = clHeapAllocate(section_size);
	if (section_data == NULL)
	{
		printf("clTcCkptCreate: Failed to allocate section data\n");
		goto clean_up_code;
	}
#endif
	
	/* Set the local replica to be active 
	 * You cannot do any activity on this checkpoint
	 * including a status get (see Bug 6118) unless you 
	 * call this API
	 * 
	 */
	if (ckpt_type == TC_CKPT_ASYNC_COLLOC)
	{
   		ret_code = clCkptActiveReplicaSet((ClCkptHdlT)ckpt_data->ckpt_hdl);
		if (ret_code != CL_OK)
		{
			printf("clTcCkptCreate: Failed to activate replica :0x%x\n", 
			   	   ret_code);
			goto clean_up_code;
		}
	}

	/* Create the sections within the checkpoint
	 */
	for ( section_num = 1; section_num <= num_sections; section_num++ )
	{
		sprintf((ClCharT*)section_name_ptr, "%05d", section_num);
		section_id.idLen = strlen((ClCharT*)section_id.id);

		/* time check 2 start (cumulative)
	 	 */
        startTime = clOsalStopWatchTimeGet();
		ret_code = clCkptSectionCreate((ClCkptHdlT)ckpt_data->ckpt_hdl,
									   &section_cr_attr,
									   NULL, 0);
		/* time check 2 end (cumulative)
		 */
        endTime = clOsalStopWatchTimeGet();

		/* does not account for overflow
		 */
		time_taken_us = endTime - startTime;
		ckpt_data->time_taken_us  += time_taken_us;

		if (ret_code != CL_OK)
		{
			printf("clTcCkptCreate: Failed to create section #%d :0x%x \n", 
					section_num, ret_code);
			goto clean_up_code;
		}
	}

	/* total time taken excluding any intialization code
	 * time check 1 + time check 2
	 */

	/* free up memory allocated to initialize section
	 */
#ifdef PRE_ALLOCATE_SECTION
	clHeapFree(section_data);
#endif
	return ret_code;

	clean_up_code:
	/* Delete checkpoint (test: check memory profile to ensure all resources
	 * are actually released)
	 */
	if ( clCkptCheckpointDelete( ckpt_svc_hdl, &ckpt_name_t) != CL_OK )
	{
		printf("clTcCkptCreate: Failed to delete checkpoint %s\n", ckpt_name); 
	}

	return ret_code;	
}
ClRcT
clLogMasterCkptGet(void)
{
    ClRcT                                rc              = CL_OK;
    ClCkptCheckpointCreationAttributesT  ckptAttr        = {0};
    ClCkptOpenFlagsT                     openFlags       = 0;
    ClLogSvrCommonEoDataT                *pCommonEoEntry = NULL;
    ClLogMasterEoDataT                   *pMasterEoEntry = NULL;
    ClTimeT                              timeout         = 5000L;
    ClIocNodeAddressT                    localAddr = clIocLocalAddressGet();
    ClInt32T tries = 0;
    static ClTimerTimeOutT delay = {  0,  100 };

    CL_LOG_DEBUG_TRACE(("Enter"));

    rc = clLogMasterEoEntryGet(&pMasterEoEntry, &pCommonEoEntry);
    if( CL_OK != rc )
    {
        return rc;
    }
    ckptAttr.creationFlags     = CL_CKPT_CHECKPOINT_COLLOCATED | CL_CKPT_ALL_OPEN_ARE_REPLICAS;
    ckptAttr.checkpointSize    = pMasterEoEntry->maxFiles * pMasterEoEntry->sectionSize;
    ckptAttr.retentionDuration = CL_LOGMASTER_CKPT_RETENTION_DURATION;
    ckptAttr.maxSections       = pMasterEoEntry->maxFiles;
    ckptAttr.maxSectionSize    = pMasterEoEntry->sectionSize;
    ckptAttr.maxSectionIdSize  = pMasterEoEntry->sectionIdSize;

    //   openFlags = CL_CKPT_CHECKPOINT_WRITE | CL_CKPT_CHECKPOINT_READ;
    //rc = clCkptCheckpointOpen(pCommonEoEntry->hSvrCkpt, &gLogMasterCkptName,
    //                          NULL, openFlags, 0,  &pMasterEoEntry->hCkpt);
    //    if( CL_ERR_NOT_EXIST == CL_GET_ERROR_CODE(rc) )
    //  {
    openFlags = CL_CKPT_CHECKPOINT_CREATE | CL_CKPT_CHECKPOINT_WRITE | CL_CKPT_CHECKPOINT_READ;

reopen:
    rc = clCkptCheckpointOpen(pCommonEoEntry->hSvrCkpt, &gLogMasterCkptName, &ckptAttr,openFlags, timeout, &pMasterEoEntry->hCkpt);
    if( (CL_OK != rc) && (CL_ERR_ALREADY_EXIST != rc) )
    {
        /*
         * No replica found and we are the only master.
         * Delete and try re-opening the checkpoint
         */
        if(CL_GET_ERROR_CODE(rc) == CL_ERR_NO_RESOURCE && pCommonEoEntry->masterAddr == localAddr)
        {
            if(tries++ < 1)
            {
                clLogNotice("CKP", "GET", "No replica for log checkpoint."
                            "Deleting ckpt [%.*s] and retrying the ckpt open",
                            gLogMasterCkptName.length, gLogMasterCkptName.value);
                clCkptCheckpointDelete(pCommonEoEntry->hSvrCkpt, &gLogMasterCkptName);
                clOsalTaskDelay(delay);
                goto reopen;
            }
        }
        CL_LOG_DEBUG_ERROR(("clCkptCheckpointOpen(): rc[0x%x]", rc));
        return rc;
    }
    //     if( CL_ERR_ALREADY_EXIST != CL_GET_ERROR_CODE(rc))
    {   /* Create default section */
    }
    //    return rc;
    //    }

    if(pCommonEoEntry->masterAddr == localAddr)
    {
        rc = clLogMasterStateRecover(pCommonEoEntry, pMasterEoEntry, CL_FALSE);
        if( CL_OK != rc )
        {
            CL_LOG_CLEANUP(clCkptCheckpointClose(pMasterEoEntry->hCkpt),
                           CL_OK);
        }
    } /* else you are standby so just keep the ckpt opened */

    CL_LOG_DEBUG_TRACE(("Exit: rc[0x%x]", rc));
    return rc;
}