/*******************************************************************************
Utility API: clTcActivateReplica

Descrition :

This API is utility related, used to set the local checkpoint as the active
replica.  The checkpoint data is retrieved and replica activate called only if
the checkpoint creation flag is ASYNC and COLLOCATED

*******************************************************************************/
static int
clTcActivateReplica ( ClTcCkptDataT *ckpt_data )
{
	ClRcT ret_code = CL_OK;
	ClCkptCheckpointDescriptorT ckpt_desc;

	ret_code = clCkptCheckpointStatusGet((ClCkptHdlT)ckpt_data->ckpt_hdl,
										 &ckpt_desc);

	if (ret_code != CL_OK)
	{
		printf("clTcActivateReplica: could not retrieve ckpt info: 0x%x\n",
			   ret_code);
		return ret_code;
	}

	/* If the check point type is async collocated
	 * then we need to set the active replica to this
	 * node
	 */
	if (ckpt_desc.checkpointCreationAttributes.creationFlags &
		CL_CKPT_CHECKPOINT_COLLOCATED)
	{
    	ret_code = clCkptActiveReplicaSet((ClCkptHdlT)ckpt_data->ckpt_hdl);
		if ( ret_code != CL_OK )
		{
			printf("clTcActivateReplica: Failed to activate replica :0x%x\n", 
				   ret_code);
		}
	}
	return ret_code;
}
SaAisErrorT saCkptActiveReplicaSet(SaCkptCheckpointHandleT checkpointHandle)
{
    ClRcT          rc     = CL_OK;
    SaAisErrorT    safRc  = SA_AIS_OK;

    /*
     * Call the corresponding ckpt client library function.
     */
    rc = clCkptActiveReplicaSet((ClCkptHdlT) checkpointHandle);

    /*
     * Translate the clovis error type to SAF error type.
     */
    clErrorTxlate(rc, &safRc);
    
    return safRc;
}
ClRcT alarmClockCkptActivate(ClCkptHdlT ckptHdl, ClUint32T numSections)
{
    ClRcT rc = CL_OK;
    ClCkptSectionIdT id;
    ClCharT section_name[CL_MAX_NAME_LENGTH];

    snprintf(section_name, sizeof(section_name), "s%05d", numSections);
    id.idLen = strlen(section_name);
    id.id = (ClUint8T*)section_name;

    rc = clCkptActiveReplicaSet(ckptHdl);
    if(rc != CL_OK)
    {
        alarmClockLogWrite(CL_LOG_SEV_ERROR, "alarmClockReplicaSet: returned [%#x]", rc);
        return rc;
    }
    
    rc = clCkptSectionCheck(ckptHdl, &id);
    if(CL_GET_ERROR_CODE(rc) == CL_ERR_NOT_EXIST)
    {
        ClCkptSectionCreationAttributesT attr;
        attr.sectionId = &id;
        attr.expirationTime = (ClTimeT)CL_TIME_END;
        rc = clCkptSectionCreate(ckptHdl, &attr, NULL, 0);
        if(rc == CL_OK)
        {
            alarmClockLogWrite(CL_LOG_SEV_INFO, "alarmClockActivate: Section [%s] created successfully",
                               section_name);
        }
    }
    
    if(rc != CL_OK)
    {
        alarmClockLogWrite(CL_LOG_SEV_INFO, "alarmClockActivate: Section operation on [%s] "
                           "failed with [%#x]", section_name, rc);
    }
    
    return rc;
}
/*******************************************************************************
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
clLogMasterStateRecover(ClLogSvrCommonEoDataT  *pCommonEoEntry,
                        ClLogMasterEoDataT    *pMasterEoEntry,
                        ClBoolT switchover)
{
    ClRcT                             rc             = CL_OK;
    ClHandleT                         hSecIter       = CL_HANDLE_INVALID_VALUE;
    ClCkptSectionDescriptorT          secDescriptor  = {{0}};
    ClCkptIOVectorElementT            ioVector       = {{0}};
    ClUint32T                         errIndex       = 0;
    ClCkptSectionCreationAttributesT  secAttr        = {0};
    ClBoolT                           logReadFlag    = CL_FALSE;

    CL_LOG_DEBUG_TRACE(("Enter"));

    rc = clLogMasterEoEntrySet(pMasterEoEntry);
    if( CL_OK != rc )
    {
        CL_LOG_DEBUG_ERROR(("clLogMasterEoEntrySet(): rc[0x %x]", rc));
        return rc;
    }

    if(switchover)
    {
        rc = clCkptActiveReplicaSetSwitchOver(pMasterEoEntry->hCkpt);
    }
    else
    {
        rc = clCkptActiveReplicaSet(pMasterEoEntry->hCkpt);
    }
    if (CL_OK != rc)
    {
        CL_LOG_DEBUG_ERROR(("clCkptActiveReplicaSet(): rc[%#x],switchover flag [%d]", rc, switchover));
        return rc;
    }

    rc = clCkptSectionIterationInitialize(pMasterEoEntry->hCkpt,
                                          CL_CKPT_SECTIONS_ANY,
                                          CL_TIME_END, &hSecIter);
    if( CL_OK != rc )
    {
        CL_LOG_DEBUG_ERROR(("clCkptSectionIterationInitialize(): rc[0x %x]",
                            rc));
        return rc;
    }

    do
    {
        rc = clCkptSectionIterationNext(hSecIter, &secDescriptor);
        if( CL_OK != rc)
        {
            break;
        }

        logReadFlag         = CL_TRUE;
        if( pCommonEoEntry->masterAddr == clIocLocalAddressGet() )
        {
            ioVector.sectionId  = secDescriptor.sectionId;
            ioVector.dataBuffer = NULL;
            ioVector.dataSize   = 0;
            ioVector.readSize   = 0;
            ioVector.dataOffset = 0;
            clLogNotice(CL_LOG_AREA_MASTER, CL_LOG_CTX_CKPT_READ,
                        "Got section [%.*s] to be read",
                        secDescriptor.sectionId.idLen, secDescriptor.sectionId.id);
            if( 0 != strncmp((ClCharT *) ioVector.sectionId.id,
                             (ClCharT *) gLogMasterCompDataSectionId.id,
                             gLogMasterCompDataSectionId.idLen) )
            {
                rc = clCkptCheckpointRead(pMasterEoEntry->hCkpt, &ioVector, 1,
                                          &errIndex);
                if( CL_OK == rc ) /* create whatever we can */
                {
                    if( 0 == strncmp((ClCharT *) ioVector.sectionId.id,
                                     (ClCharT *) gLogMasterDefaultSectionId.id,
                                     gLogMasterDefaultSectionId.idLen) )
                    {
                        rc = clLogMasterEoEntryRecover(pMasterEoEntry, &ioVector,
                                                       &errIndex);
                        if( CL_OK != rc )
                        {
                            clHeapFree(ioVector.dataBuffer);
                            clHeapFree(ioVector.sectionId.id);
                            break; /* break out of the loop, can't continue */
                        }
                        clHeapFree(ioVector.dataBuffer);
                    }
                    else
                    {
                        /* create whatever we can */
                        clLogMasterFileEntryRecover(pMasterEoEntry, &ioVector,
                                                    &errIndex);
                        clHeapFree(ioVector.dataBuffer);
                    }
                }
            }
            clHeapFree(secDescriptor.sectionId.id);
        }
        else
        {
            return rc;
        }
    } while( (rc == CL_OK) );

    CL_LOG_CLEANUP(clCkptSectionIterationFinalize(hSecIter), CL_OK);

    if( CL_TRUE == logReadFlag )
    {
        ioVector.sectionId  = gLogMasterCompDataSectionId;
        ioVector.dataBuffer = NULL;
        ioVector.dataSize   = 0;
        ioVector.readSize   = 0;
        ioVector.dataOffset = 0;
        rc = clCkptCheckpointRead(pMasterEoEntry->hCkpt, &ioVector, 1, &errIndex);
        if( CL_OK != rc )
        {
            CL_LOG_DEBUG_ERROR(("clCkptCheckpointRead():rc[0x %x]", rc));
            return rc;
        }
        rc = clLogMasterCompTableStateRecover(pMasterEoEntry, (ClUint8T*) ioVector.dataBuffer,
                                              ioVector.readSize);
        if( CL_OK != rc )
        {
            CL_LOG_DEBUG_ERROR(("Unable to recreate the state of compTable"));
        }
        clHeapFree(ioVector.dataBuffer);
    }
    else
    {
        secAttr.sectionId      = &gLogMasterDefaultSectionId;
        secAttr.expirationTime = CL_TIME_END;
        rc = clCkptSectionCreate(pMasterEoEntry->hCkpt, &secAttr, NULL, 0);
        if( CL_OK != rc )
        {
            CL_LOG_DEBUG_ERROR(("clCkptSectionCreate(): rc[0x %x]", rc));
            return rc;
        }
        secAttr.sectionId      = &gLogMasterCompDataSectionId;
        secAttr.expirationTime = CL_TIME_END;
        rc = clCkptSectionCreate(pMasterEoEntry->hCkpt, &secAttr, NULL,
                                 0);
        if( CL_OK != rc )
        {
            CL_LOG_DEBUG_ERROR(("clCkptSectionCreate(): rc[0x %x]", rc));
            CL_LOG_CLEANUP(clCkptSectionDelete(pMasterEoEntry->hCkpt,
                                               &gLogMasterDefaultSectionId),
                           CL_OK);
        }
    }

    CL_LOG_DEBUG_TRACE(("Exit"));
    return CL_OK;
}
/*
 * Function - clLogSOCkptRead()
 *  Walk thru the list of sections.
 *  Read the checkpoint data.
 *  Recreate the entry 
 */
ClRcT
clLogStreamOwnerGlobalStateRecover(ClIocNodeAddressT  masterAddr, ClBoolT switchover)
{
    ClRcT                     rc            = CL_OK;
    ClHandleT                 hSecIter      = CL_HANDLE_INVALID_VALUE;
    ClCkptSectionDescriptorT  secDescriptor = {{0}};
    ClLogSOEoDataT            *pSoEoEntry   = NULL;
    ClIocNodeAddressT         localAddr     = 0;

    CL_LOG_DEBUG_TRACE(("Enter"));

    localAddr = clIocLocalAddressGet();
    rc = clLogStreamOwnerEoEntryGet(&pSoEoEntry, NULL);
    if( CL_OK != rc )
    {
        return rc;
    }
    if(switchover)
    {
        rc = clCkptActiveReplicaSetSwitchOver(pSoEoEntry->hCkpt);
    }
    else
    {
        rc = clCkptActiveReplicaSet(pSoEoEntry->hCkpt);
    }

    if (CL_OK != rc)
    {
        CL_LOG_DEBUG_ERROR(("clCkptActiveReplicaSet(): rc[%#x], switchover flag [%d]", rc, switchover));
        return rc;
    }
    rc = clCkptSectionIterationInitialize(pSoEoEntry->hCkpt,
                                          CL_CKPT_SECTIONS_ANY, 
                                          CL_TIME_END, &hSecIter);
    if( CL_OK != rc )
    {
        CL_LOG_DEBUG_ERROR(("clCkptSectionIterationInitialize(): rc[0x %x]",
                            rc));
        return rc;
    }    
    do
    {    
        rc = clCkptSectionIterationNext(hSecIter, &secDescriptor);
        if( (rc != CL_OK))
        {
            if( CL_ERR_NOT_EXIST == CL_GET_ERROR_CODE(rc)
                ||
                CL_CKPT_ERR_NO_SECTIONS == CL_GET_ERROR_CODE(rc))
            {
                rc = CL_OK;
            }
            break;
        }
        /* 
         * Create the entries as many as we can, so explicitly
         * not checking the rc.
         */
        if( localAddr == masterAddr )
        {
            clLogStreamOwnerGlobalEntryRecover(pSoEoEntry, &secDescriptor);
        }
        clHeapFree(secDescriptor.sectionId.id);
    }while((rc == CL_OK));

    CL_LOG_CLEANUP(clCkptSectionIterationFinalize(hSecIter), CL_OK);

    CL_LOG_DEBUG_TRACE(("Exit"));
    return rc;
}