/*
 * nqsd/nqs_load.c
 * 
 * DESCRIPTION:
 *
 *	NQS load module.
 *
 *	Original Author:
 *	-------
 *	John Roman, Monsanto Company.
 *	September 21, 1992.
 */

#include <libnqs/license.h>
#include <libnqs/proto.h>

#include <libnqs/nqsxvars.h>
#include <libnqs/transactcc.h>		/* Transaction completion codes */
#include <malloc.h>

#include <libsal/license.h>
#include <libsal/proto.h>
#include <libsal/defines.h>

#include <time.h>

/*** nqs_load
 *
 *	Store the load information for this Mid in an internal data
 *	structure.
 *
 *	Returns:
 *		TCML_COMPLETE:	if successful;
 */
long nqs_load (
	Mid_t mid,
	int version,
	int nqs_jobs,
	char *string)
{
    struct loadinfo *loadinfo_ptr;
    float load1,  load5,  load15;   
    struct pipeto *dest;	/* Pipe queue destination */
    time_t timenow;	/* Current time */
    
    sal_dprintf(SAL_DEBUG_INFO, SAL_DEBUG_MSG_DEBUGMEDIUM, "Nqs_load: Entering with mid %u jobs %d \n", mid,  nqs_jobs);
  
    sscanf(string,  "%f %f %f",  &load1,  &load5,  &load15);
    /*
     * Look through the queue of loadinfos for this mid.  If it is
     * there,  replace the contents with the new information.  If it is
     * not,  create a new structure.
     */
    loadinfo_ptr = Loadinfo_head.next;
    while (loadinfo_ptr != (struct loadinfo *) 0) {
	if (loadinfo_ptr->mid == mid) {
	    time (&loadinfo_ptr->time);
	    loadinfo_ptr->no_jobs = nqs_jobs;
	    loadinfo_ptr->load1 = load1;
	    loadinfo_ptr->load5 = load5;
	    loadinfo_ptr->load15 = load15;
	    break;
	} else {
	    loadinfo_ptr = loadinfo_ptr->next;
	}
    }
    if (loadinfo_ptr == (struct loadinfo *) 0) {
	loadinfo_ptr = (struct loadinfo *) malloc (sizeof (Loadinfo_head) );
	loadinfo_ptr->mid = mid;
	loadinfo_ptr->rap = 1;		/* set to default value */
	time (&loadinfo_ptr->time);
	loadinfo_ptr->no_jobs = nqs_jobs;
	loadinfo_ptr->load1 = load1;
	loadinfo_ptr->load5 = load5;
	loadinfo_ptr->load15 = load15;
	loadinfo_ptr->next = Loadinfo_head.next; 
	Loadinfo_head.next = loadinfo_ptr;
    }
    /*
     *  If this machine is not enabled, set it to retry in 30 seconds.
     */
    dest = Pipetoset;
    while (dest != (struct pipeto *) 0) {
	if (dest->rhost_mid == mid) {
	    /*
	     *  Perform update on this destination.
	     */
	    if ( !(dest->status & DEST_ENABLED) ) {
		timenow = time ((time_t *) 0);
		dest->status = DEST_RETRY;
		dest->retry_at = timenow + 30;
		/*
		 *  Set timer to re-enable the destination.
		 */
		nqs_vtimer (&dest->retry_at, nqs_wakdes);
		udb_destination (dest);	/* Update NQS database image */
	    }
	}
	dest = dest->next;		/* Next destination */
    }	 
    return (TCML_COMPLETE);
}
