/*
  File:  proxy_util.c

  Description:  miscellaneous utility functions.
*/

#include <stdio.h>
#include <sys/time.h>
#include <stdarg.h>
#include <time.h>
#include "proxy_protos.h"


/*
  log a message to the log file (or stderr)
*/

void
log_msg ( struct mdata *md, char *fmt, ... )
{
  va_list   ap;
  char      bt[256];
  char      buf[BUFSIZ];
  time_t    t;
  struct tm tm;

  t = time(NULL);
  localtime_r(&t,&tm);
  strftime(bt,sizeof(bt)-1,"%Y-%m-%d %T",&tm);
  bt[sizeof(bt)-1] = 0;
  va_start(ap, fmt);
  vsnprintf(buf,sizeof(buf)-1,fmt,ap);
  buf[sizeof(buf)-1] = 0;
  va_end(ap);
  fprintf(md->log_fp,"[%s] %s\n",bt,buf);
}


/* 
   print out some information from the global data structure 
*/

void
print_stats ( struct mdata *md )
{
  log_msg(md,"Available file descriptors:    %d",
	  md->nofile);
  log_msg(md,"Main event loop iterations:    %d",
	  md->iterations);
  log_msg(md,"Events received in main loop:  %d",
	  md->events);
  log_msg(md,"Event errors recorded:         %d",
	  md->kevent_errors);
  log_msg(md,"Client connections accepted:   %d",
	  md->accepts);
  log_msg(md,"Bytes read from clients:       %d",
	  md->bytes_read[CLIENT]);
  log_msg(md,"Bytes written to clients:      %d",
	  md->bytes_written[CLIENT]);
  log_msg(md,"Bytes read from server:        %d",
	  md->bytes_read[SERVER]);
  log_msg(md,"Bytes written to server:       %d",
	  md->bytes_written[SERVER]);
  log_msg(md,"Maximum concurrent clients:    %d",
	  md->max_clients);
  log_msg(md,"Time reading from clients:     %.3f",
	  md->time_reading[CLIENT]);
  log_msg(md,"Time reading from server:      %.3f",
	  md->time_reading[SERVER]);
  log_msg(md,"Time writing to clients:       %.3f",
	  md->time_writing[CLIENT]);
  log_msg(md,"Time writing to server:        %.3f",
	  md->time_writing[SERVER]);
  if ( md->time_reading[SERVER] > 0.0 ) {
    log_msg(md,"Acceleration factor:           %.3f",
	    md->time_writing[CLIENT]/md->time_reading[SERVER]);
  }
}


/* difference between two struct timevals */

float
diff_timeval ( struct timeval *t_start, struct timeval *t_finish )
{
  float f;

  f = (t_finish->tv_sec - t_start->tv_sec) + 
    (t_finish->tv_usec - t_start->tv_usec) / 1000000.0;

  return f;
}


syntax highlighted by Code2HTML, v. 0.9.1