/*
 *========================================================================
 * $Id: get_proc_loadavg.c 163 2005-09-14 22:54:20Z rgb $
 *
 * See copyright in copyright.h and the accompanying file COPYING
 *========================================================================
 */

#include "xmlsysd.h"

/*
 * This routine parses /proc/stat and packs its values into doc.
 */

void get_proc_loadavg(xmlNodePtr proc)
{

 int i,numfields;
 struct timeval tv;
 xmlNodePtr loadavg,loadvalue;

 if(verbose==102){
   fprintf(stderr,"Starting get_proc_meminfo().\n");
 }

 /* 
  * Create a timestamped child of meminfo node.  Everything below
  * will belong to this
  */
 loadavg = xmlNewChild(proc,NULL,(xmlChar*) "loadavg",NULL);
 gettimeofday(&tv,0);
 sprintf(outbuf,"%d",tv.tv_sec);
 xmlSetProp(loadavg,(xmlChar*) "tv_sec",(xmlChar*) outbuf);
 sprintf(outbuf,"%d",tv.tv_usec);
 xmlSetProp(loadavg,(xmlChar*) "tv_usec",(xmlChar*) outbuf);


 /* 
  * Don't ask me why, but /proc/loadavg cannot be rewound.  So we just
  * close and reopen the damn thing.
  */

 /* PROC_LOADAVG */
 if(verbose == 102){
   fprintf(stderr,"Closing and reopening %s.\n",procpaths[PROC_LOADAVG]);
 }
 fclose(stat_fd[PROC_LOADAVG]);
 if(verbose == 102){
   fprintf(stderr,"Closed %s.\n",procpaths[PROC_LOADAVG]);
 }
 stat_fd[PROC_LOADAVG] = fopen(procpaths[PROC_LOADAVG],"r");
 if(verbose == 102){
   fprintf(stderr,"Reopened %s.\n",procpaths[PROC_LOADAVG]);
 }

 while(TRUE){

   /* Normal EOF causes break from while loop */
   if((fgets(statbuf,K,stat_fd[PROC_LOADAVG]) == NULL)) break;

   if(verbose == 102){
     fprintf(stderr,"Parsing %s\n",statbuf);
   }

   /* parse the line into fields */
   numfields = parse(statbuf,fields,MAXFIELDNUMBER,K);

   /*
    * Now we go down a simple lookup table to assemble each statistic
    * by name.  fields[] now contains the parsed fields from a line of
    * /proc/meminfo.  We identify the line by its first entry (the name
    * of the /proc/meminfo entity) and use the following values to build 
    * one or more statistics.
    */

   /* There is only one line and we want the first three values */
   loadvalue = xmlNewChild(loadavg,NULL,(xmlChar*) "load1",(xmlChar*) fields[0]);
   loadvalue = xmlNewChild(loadavg,NULL,(xmlChar*) "load5",(xmlChar*) fields[1]);
   loadvalue = xmlNewChild(loadavg,NULL,(xmlChar*) "load15",(xmlChar*) fields[2]);

 }

}

