Ejemplo n.º 1
0
void read_init_vars(struct mlx5_context *ctx)
{
	pthread_mutex_lock(&ctx->env_mtx);
	if (!ctx->env_initialized) {
		mlx5_single_threaded = single_threaded_app(&ctx->ibv_ctx);
		mlx5_use_mutex = get_use_mutex(&ctx->ibv_ctx);
		open_debug_file(ctx);
		set_debug_mask(&ctx->ibv_ctx);
		set_freeze_on_error(&ctx->ibv_ctx);
		ctx->prefer_bf = get_always_bf(&ctx->ibv_ctx);
		ctx->shut_up_bf = get_shut_up_bf(&ctx->ibv_ctx);
		mlx5_read_env(ctx);
		ctx->env_initialized = 1;
	}
	pthread_mutex_unlock(&ctx->env_mtx);
}
Ejemplo n.º 2
0
Archivo: debug.c Proyecto: abbra/sssd
int rotate_debug_files(void)
{
    int ret;
    errno_t error;

    if (!debug_to_file) return EOK;

    do {
        error = 0;
        ret = fclose(debug_file);
        if (ret != 0) {
            error = errno;
        }

        /* Check for EINTR, which means we should retry
         * because the system call was interrupted by a
         * signal
         */
    } while (error == EINTR);

    if (error != 0) {
        /* Even if we were unable to close the debug log, we need to make
         * sure that we open up a new one. Log rotation will remove the
         * current file, so all debug messages will be disappearing.
         *
         * We should write an error to the syslog warning of the resource
         * leak and then proceed with opening the new file.
         */
        sss_log(SSS_LOG_ALERT, "Could not close debug file [%s]. [%d][%s]\n",
                               debug_log_file, error, strerror(error));
        sss_log(SSS_LOG_ALERT, "Attempting to open new file anyway. "
                               "Be aware that this is a resource leak\n");
    }

    debug_file = NULL;

    return open_debug_file();
}
Ejemplo n.º 3
0
void 
process_requests()
{
  
  float	temp_rate;
  
  if (debug)    open_debug_file();


  while (1) {
    recv_request();

    switch (netperf_request.content.request_type) {
      
    case DEBUG_ON:
      netperf_response.content.response_type = DEBUG_OK;
      /*  dump_request already present in recv_request; redundant? */
      if (!debug) {
	debug++;
	open_debug_file();
	dump_request();
      }
      send_response();
      break;
      
    case DEBUG_OFF:
      if (debug)
	debug--;
      netperf_response.content.response_type = DEBUG_OK;
      send_response();
      /* +SAF why??? */
      if (!debug) 
      {
	fclose(where);
#if !defined(WIN32) && !defined(MPE) && !defined(__VMS)
	/* For Unix: reopen the debug write file descriptor to "/dev/null" */
	/* and redirect stdout to it.					   */
	fflush (stdout);
	where = fopen ("/dev/null", "w");
	if (where == NULL)
	{
	  perror ("netserver: reopening debug fp for writing: /dev/null");
	  exit   (1);
	}
	if (close (STDOUT_FILENO) == -1)
	{
	  perror ("netserver: closing stdout file descriptor");
	  exit   (1);
	}
	if (dup (fileno (where))  == -1)
	{
	  perror ("netserver: duplicate /dev/null write file descr. to stdout");
	  exit   (1);
	}
#endif /* !WIN32 !MPE !__VMS */
      }
      break;
      
    case CPU_CALIBRATE:
      netperf_response.content.response_type = CPU_CALIBRATE;
      temp_rate = calibrate_local_cpu(0.0);
      bcopy((char *)&temp_rate,
	    (char *)netperf_response.content.test_specific_data,
	    sizeof(temp_rate));
      bcopy((char *)&lib_num_loc_cpus,
	    (char *)netperf_response.content.test_specific_data + sizeof(temp_rate),
	    sizeof(lib_num_loc_cpus));
      if (debug) {
	fprintf(where,"netserver: sending CPU information:");
	fprintf(where,"rate is %g num cpu %d\n",temp_rate,lib_num_loc_cpus);
	fflush(where);
      }
      
      /* we need the cpu_start, cpu_stop in the looper case to kill the */
      /* child proceses raj 7/95 */
      
#ifdef USE_LOOPER
      cpu_start(1);
      cpu_stop(1,&temp_rate);
#endif /* USE_LOOPER */
      
      send_response();
      break;
      
    case DO_TCP_STREAM:
      recv_tcp_stream();
      break;
      
    case DO_TCP_MAERTS:
      recv_tcp_maerts();
      break;
      
    case DO_TCP_RR:
      recv_tcp_rr();
      break;
      
    case DO_TCP_CRR:
      recv_tcp_conn_rr();
      break;
      
    case DO_TCP_CC:
      recv_tcp_cc();
      break;
      
#ifdef DO_1644
    case DO_TCP_TRR:
      recv_tcp_tran_rr();
      break;
#endif /* DO_1644 */
      
#ifdef DO_NBRR
    case DO_TCP_NBRR:
      recv_tcp_nbrr();
      break;
#endif /* DO_NBRR */
      
    case DO_UDP_STREAM:
      recv_udp_stream();
      break;
      
    case DO_UDP_RR:
      recv_udp_rr();
      break;
      
#ifdef WANT_DLPI

    case DO_DLPI_CO_RR:
      recv_dlpi_co_rr();
      break;
      
    case DO_DLPI_CL_RR:
      recv_dlpi_cl_rr();
      break;

    case DO_DLPI_CO_STREAM:
      recv_dlpi_co_stream();
      break;

    case DO_DLPI_CL_STREAM:
      recv_dlpi_cl_stream();
      break;

#endif /* WANT_DLPI */

#ifdef WANT_UNIX

    case DO_STREAM_STREAM:
      recv_stream_stream();
      break;
      
    case DO_STREAM_RR:
      recv_stream_rr();
      break;
      
    case DO_DG_STREAM:
      recv_dg_stream();
      break;
      
    case DO_DG_RR:
      recv_dg_rr();
      break;
      
#endif /* WANT_UNIX */

#ifdef WANT_XTI
    case DO_XTI_TCP_STREAM:
      recv_xti_tcp_stream();
      break;
      
    case DO_XTI_TCP_RR:
      recv_xti_tcp_rr();
      break;
      
    case DO_XTI_UDP_STREAM:
      recv_xti_udp_stream();
      break;
      
    case DO_XTI_UDP_RR:
      recv_xti_udp_rr();
      break;

#endif /* WANT_XTI */

#ifdef WANT_SCTP
    case DO_SCTP_STREAM:
      recv_sctp_stream();
      break;
      
    case DO_SCTP_STREAM_MANY:
      recv_sctp_stream_1toMany();
      break;

    case DO_SCTP_RR:
      recv_sctp_rr();
      break;

    case DO_SCTP_RR_MANY:
      recv_sctp_rr_1toMany();
      break;
#endif

#ifdef WANT_SDP
    case DO_SDP_STREAM:
      recv_sdp_stream();
      break;

    case DO_SDP_MAERTS:
      recv_sdp_maerts();
      break;

    case DO_SDP_RR:
      recv_sdp_rr();
      break;
#endif 

    default:
      fprintf(where,"unknown test number %d\n",
	      netperf_request.content.request_type);
      fflush(where);
      netperf_response.content.serv_errno=998;
      send_response();
      break;
      
    }
  }
}
Ejemplo n.º 4
0
extern "C" void
preserve_log_file()
{
	char		old[MAXPATHLEN + 4];
	int			still_in_old_file = FALSE;
	int			failed_to_rotate = FALSE;
	int			save_errno;
	int         rename_failed = 0;
	time_t clock_now;
	struct tm *tm; 

	(void)sprintf( old, "%s.old", debug_fn );
	(void)time( &clock_now );
	tm = localtime( &clock_now );
	fprintf(debug_fp, "%s: ", formatTimeHeader(tm));
	fprintf( debug_fp, "Saving log file to \"%s\"\n", old );
	(void)fflush( debug_fp );

	fclose(debug_fp);
	debug_fp = NULL;

#if defined(WIN32)

	(void)unlink(old);

	/* use rename on WIN32, since link isn't available */
	if (rename(debug_fn, old) < 0) {
		/* the rename failed, perhaps one of the log files
		 * is currently open.  Sleep a half second and try again. */		 
		Sleep(500);
		(void)unlink(old);
		if ( rename(debug_fn,old) < 0) {
			/* Feh.  Some bonehead must be keeping one of the files
			 * open for an extended period.  Win32 will not permit an
			 * open file to be unlinked or renamed.  So, here we copy
			 * the file over (instead of renaming it) and then truncate
			 * our original. */

			if ( CopyFile(debug_fn,old,FALSE) == 0 ) {
				/* Even our attempt to copy failed.  We're screwed. */
				failed_to_rotate = TRUE;
			}

			/* now truncate the original by reopening _not_ with append */
			debug_fp = open_debug_file("w");
			if ( debug_fp ==  NULL ) {
				still_in_old_file = TRUE;
			}
		}
	}

#else

	errno = 0;
	if( rename(debug_fn, old) < 0 ) {
		save_errno = errno;
		if( save_errno == ENOENT ) {
				/* This can happen if we are not using debug file locking,
				   and two processes try to rotate this log file at the
				   same time.  The other process must have already done
				   the rename but not created the new log file yet.
				*/
			rename_failed = 1;
		}
		else {
			fprintf( stderr, "Can't rename(%s,%s)\n",
					  debug_fn, old );
			return;
		}
	}

#endif

	if (debug_fp == NULL) {
		debug_fp = open_debug_file( "a");
	}

	if( debug_fp == NULL ) {
		save_errno = errno;
		fprintf(stderr, "Can't open file %s\n",
				 debug_fn ); 
		return;
	}

	if ( !still_in_old_file ) {
		(void)time( &clock_now );
		tm = localtime( &clock_now );
		fprintf(debug_fp, "%s: ", formatTimeHeader(tm));
		fprintf (debug_fp, "Now in new log file %s\n", debug_fn);
	}

	if ( failed_to_rotate || rename_failed ) {
		fprintf(debug_fp,"WARNING: Failed to rotate log into file %s!\n",old);
		if( rename_failed ) {
			fprintf(debug_fp,"Likely cause is that another Condor process rotated the file at the same time.\n");
		}
		else {
			fprintf(debug_fp,"       Perhaps someone is keeping log files open???");
		}
	}
}
/* the routine we call when we are going to spawn/fork/whatnot a child
   process from the parent netserver daemon. raj 2011-07-08 */
void
spawn_child() {

#if defined(HAVE_FORK)

  if (debug) {
    fprintf(where,
	    "%s: enter\n",
	    __FUNCTION__);
    fflush(where);
  }


  /* flush the usual suspects */
  fflush(stdin);
  fflush(stdout);
  fflush(stderr);
  fflush(where);

  signal(SIGCLD,SIG_IGN);

  switch (fork()) {
  case -1:
    fprintf(where,
	    "%s: fork() error %s (errno %d)\n",
	    __FUNCTION__,
	    strerror(errno),
	    errno);
    fflush(where);
    exit(1);

  case 0:
    /* we are the child, but not of inetd.  we don't know if we are
       the child of a daemonized parent or not, so we still need to
       worry about the standard file descriptors. raj 2011-07-11 */

    close_listens(listen_list);
    open_debug_file();

    child = 1;
    netperf_daemon = 0;
    process_requests();
    exit(0);
    break;

  default:
    /* we are the parent, not a great deal to do here, but we may
       want to reap some children */
#if !defined(HAVE_SETSID)
    /* Only call "waitpid()" if "setsid()" is not used. */
    while(waitpid(-1, NULL, WNOHANG) > 0) {
      if (debug) {
	fprintf(where,
		"%s: reaped a child process\n",
		__FUNCTION__);
      }
    }
#endif
    break;
  }

#elif defined(WIN32)

  BOOL b;
  char *cmdline;
  int cmdline_length;
  int cmd_index;
  PROCESS_INFORMATION pi;
  STARTUPINFO si;
  int i;

  if (debug) {
    fprintf(where,
	    "%s: enter\n",
	    __FUNCTION__);
    fflush(where);
  }


  /* create the cmdline array based on strlen(program) + 80 chars */
  cmdline_length = strlen(program) + 80;
  cmdline = malloc(cmdline_length + 1);  // +1 for trailing null

  memset(&si, 0 , sizeof(STARTUPINFO));
  si.cb = sizeof(STARTUPINFO);

  /* Pass the server_sock as stdin for the new process.  Hopefully
     this will continue to be created with the OBJ_INHERIT
     attribute. */
  si.hStdInput = (HANDLE)server_sock;
  si.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
  si.hStdError = GetStdHandle(STD_ERROR_HANDLE);
  si.dwFlags = STARTF_USESTDHANDLES;

  /* Build cmdline for child process */
  strcpy(cmdline, program);
  cmd_index = strlen(cmdline);
  if (verbosity > 1) {
    cmd_index += snprintf(&cmdline[cmd_index],
			  cmdline_length - cmd_index,
			  " -v %d",
			  verbosity);
  }
  for (i=0; i < debug; i++) {
    cmd_index += snprintf(&cmdline[cmd_index],
			  cmdline_length - cmd_index,
			  " -d");
  }
  cmd_index += snprintf(&cmdline[cmd_index],
			cmdline_length - cmd_index,
			" -I %x",
			(int)(UINT_PTR)server_sock);

  /* are these -i settings even necessary? the command line scanning
     does not seem to do anything with them */
  cmd_index += snprintf(&cmdline[cmd_index],
			cmdline_length - cmd_index,
			" -i %x",
			(int)(UINT_PTR)server_control);
  cmd_index += snprintf(&cmdline[cmd_index],
			cmdline_length - cmd_index,
			" -i %x",
			(int)(UINT_PTR)where);

  b = CreateProcess(NULL,    /* Application Name */
		    cmdline,
		    NULL,    /* Process security attributes */
		    NULL,    /* Thread security attributes */
		    TRUE,    /* Inherit handles */
		    0,       /* Creation flags
				PROCESS_QUERY_INFORMATION,  */
		    NULL,    /* Enviornment */
		    NULL,    /* Current directory */
		    &si,     /* StartupInfo */
		    &pi);
  if (!b)
    {
      perror("CreateProcessfailure: ");
      free(cmdline); /* even though we exit :) */
      exit(1);
    }

  /* We don't need the thread or process handles any more;
     let them go away on their own timeframe. */

  CloseHandle(pi.hThread);
  CloseHandle(pi.hProcess);

  /* the caller/parent will close server_sock */

  free(cmdline);

#else

  fprintf(where,
	  "%s called on platform which cannot spawn children\n",
	  __FUNCTION__);
  fflush(where);
  exit(1);

#endif /* HAVE_FORK */
}
int _cdecl
main(int argc, char *argv[]) {

#ifdef WIN32
  WSADATA	wsa_data ;

  /* Initialize the winsock lib do we still want version 2.2? */
  if ( WSAStartup(MAKEWORD(2,2), &wsa_data) == SOCKET_ERROR ){
    printf("WSAStartup() failed : %lu\n", GetLastError()) ;
    return -1 ;
  }
#endif /* WIN32 */

  /* Save away the program name */
  program = (char *)malloc(strlen(argv[0]) + 1);
  if (program == NULL) {
    printf("malloc for program name failed!\n");
    return -1 ;
  }
  strcpy(program, argv[0]);

  init_netserver_globals();

  netlib_init();

  strncpy(local_host_name,"",sizeof(local_host_name));
  local_address_family = AF_UNSPEC;
  strncpy(listen_port,TEST_PORT,sizeof(listen_port));

  scan_netserver_args(argc, argv);

  check_if_inetd();

  if (child) {
    /* we are the child of either an inetd or parent netserver via
       spawning (Windows) rather than fork()ing. if we were fork()ed
       we would not be coming through this way. set_server_sock() must
       be called before open_debug_file() or there is a chance that
       we'll toast the descriptor when we do not wish it. */
    set_server_sock();
    open_debug_file();
    process_requests();
  }
  else if (daemon_parent) {
    /* we are the parent daemonized netserver
       process. accept_connections() will decide if we want to spawn a
       child process */
    accept_connections();
  }
  else {
    /* we are the top netserver process, so we have to create the
       listen endpoint(s) and decide if we want to daemonize */
    setup_listens(local_host_name,listen_port,local_address_family);
    if (want_daemonize) {
      daemonize();
    }
    accept_connections();
  }

  unlink_empty_debug_file();

#ifdef WIN32
  WSACleanup();
#endif

  return 0;

}
void
daemonize() {
#if defined(HAVE_FORK)

  if (debug) {
    fprintf(where,
	    "%s: enter\n",
	    __FUNCTION__);
    fflush(where);
  }

  /* flush the usual suspects */
  fflush(stdin);
  fflush(stdout);
  fflush(stderr);

  switch (fork()) {
  case -1:
    fprintf(stderr,
	    "%s: fork() error %s (errno %d)\n",
	    __FUNCTION__,
	    strerror(errno),
	    errno);
    fflush(stderr);
    exit(1);
  case 0:

    /* perhaps belt and suspenders, but if we dump core, perhaps
       better to do so here. we won't worry about the call being
       successful though. raj 2011-07-08 */
    chdir(DEBUG_LOG_FILE_DIR);

    /* we are the child. we should get a new "where" to match our new
       pid */

    open_debug_file();

#ifdef HAVE_SETSID
      setsid();
#else
      setpgrp();
#endif /* HAVE_SETSID */

      signal(SIGCLD, SIG_IGN);

      /* ok, we can start accepting control connections now */
      accept_connections();

  default:
    /* we are the parent, nothing to do but exit? */
    exit(0);
  }

#else
  fprintf(where,
	  "%s called on platform which cannot daemonize\n",
	  __FUNCTION__);
  fflush(where);
  exit(1);
#endif /* HAVE_FORK */
}
Ejemplo n.º 8
0
/**
 * FUNCTION: main
 * --------------
 * the entry point of the application
 *
 * @param argc the number of command line arguments
 * @param argv the command line arguments, kept as a pointer to a string
 *
 * @return 0 on successful completion, -1 on failure
 */
int
main(int argc, char** argv){
    int i;
    int err;
    int lineNum = 0;
    char * logLine;
    char * fileName = "../../access.log";
    FILE * logfile;
    FILE * errorFile;

     open_debug_file();

    // Set/Compile regex
    regex_t regex;
    char * regexString;
    regexString = "^[A-Za-z0-9_:.'?#()/&-]* [A-Za-z0-9_-]* [A-Za-z0-9.@_ -]* [\\[][0-3][0-9][/][JFMASOND][aepuco][nbrylgpvtc][/]....[:][0-2][0-9][:][0-5][0-9][:][0-5][0-9] [-+]....[]] [\\\"].*[\\\"] [0-9][0-9]* [0-9-][0-9-]*"; 
    err = regcomp(&regex, regexString, 0);    
    if(err)
    {
        fprintf(stderr, "Regular expression failed to compile\n");
        debug_write("Regular expression failed to compile\n");
        close_debug_file();
        exit(1);
    }

    // parse command line arguments
    if(parse_opt(argc, argv, &fileName)  != TRUE)
    {
        fprintf(stderr, "Non-execution option selected\n");
        close_debug_file();
        exit(0);
    }
    fprintf(stderr, "Analyzing file: %s\n", fileName);

    // Switch MASTER_SWITCH to TRUE
    MASTER_SWITCH = TRUE;

    //Delete output files
    if(delete_output_files() != 0)
    {
        fprintf(stderr, "Error while deleting output files\n");
        debug_write("Error while deleting output files\n");
        close_debug_file();
        exit(1);
    }

    // Initialize totalStats
    totalStats.total200        = 0;
    totalStats.total404        = 0;
    totalStats.totalInjections = 0;
    totalStats.totalVisits     = 0;

    for(i = 0; i < 24; i++)
    {
        totalStats.hourlyAccess[i] = 0;
    }

    for(i = 0; i < 12; i++)
    {
        totalStats.monthlyAccess[i] = 0;
    }

    debug_write("Opening error file\n");
    if((errorFile = fopen("errors.txt", "w")) == NULL)
    {
        debug_write("Unable to create errors.txt\n");
        fprintf(stderr, "Unable to create errors.txt\n");
        return -1;
    }

    debug_write("Opening access log file\n");
    if ((logfile = fopen(fileName, "r")) == NULL)
    {
        debug_write("access log not found, aborting!\n");
        fprintf(errorFile, "access log not found\n");
        printf("%s not found, aborting!\n", fileName);
        return -1;
    }

    // Initialize buffers
    debug_write("Allocating memory for buffer1\n");
    err = buffer_init(&buffer1);
    if (err)
    {
        debug_write("buffer1 allocation failure, aborting!\n");
        return -1;
    }

    debug_write("Allocating memory for buffer2\n");
    err = buffer_init(&buffer2);
    if (err)
    {
        debug_write("buffer2 allocation failure, aborting!\n");
        return -1;
    }

    // initialize uniqueRequests
    uniqueRequests.urls = (URL *)malloc(sizeof(URL)*MAX_UNIQUE_URLS);
    uniqueRequests.currentSize = 0;

    // initialize buffer values
    buffer1.id = 1;
    buffer1.readyRead = FALSE;
    buffer1.readyWrite = TRUE;

    buffer2.id = 2;
    buffer2.readyRead = FALSE;
    buffer2.readyWrite = TRUE;

    // Create analysis thread
    pthread_t analysisThread;
    pthread_create(&analysisThread, NULL, manage_data, NULL);


    while (!feof(logfile))
    {
        if(buffer1.readyWrite)
        {
            buffer1.currentSize = 0;
            for (i = 0; i < BUFFER_SIZE; i++)
            {
                //insure that the structure is empty
                req_null(&buffer1.requests[i]);

                //read a line
                logLine = malloc((MAX_LINE_LENGTH) * sizeof(char));
                err = log_readline(logfile, logLine, &regex);
                lineNum++;
                if (feof(logfile))
                {
                    break;
                }
                else if(err == 1)
                {
                    fprintf(stderr, "Error: invalid entry on line %d in log file\n", lineNum);
                    fprintf(errorFile, "Error: invalid entry on line %d : %s\n", lineNum, logLine);
                    --i;
                    continue;
                }
                else if(err == 2)
                {
                    fprintf(stderr, "Error: reader error: %d in log file\n", lineNum);
                    fprintf(errorFile, "Error: reader error %d\n", lineNum);
                    fclose(logfile);
                    fclose(errorFile);
                    close_debug_file();
                    exit(1);
                }
                
                //parse line and add it to the buffer
                err = parse_line(logLine, &buffer1.requests[i]);
                if (err)
                {
                    printf("parse error on line %d\n%s\n", lineNum, logLine);
                    fprintf(errorFile, "Error: parsing line %d : %s\n", lineNum, logLine);
                    --i;
                    continue;
                }
                buffer1.currentSize++;
                free(logLine);

                /*#if DEBUG==1
                    printf("%s\n", buffer1.requests[i].host);
                    printf("%s\n", buffer1.requests[i].clientId);
                    printf("%s\n", buffer1.requests[i].userId);
                    printf("%s\n", buffer1.requests[i].time);
                    printf("%s\n", buffer1.requests[i].req);
                    printf("%d\n", buffer1.requests[i].retCode);
                    printf("%d\n", buffer1.requests[i].dataSize);
                    printf("%s\n", buffer1.requests[i].referer);
                    printf("%s\n", buffer1.requests[i].userAgent);
                #endif*/

            }

            buffer1.readyWrite = FALSE;
            buffer1.readyRead = TRUE;
        }

        if(buffer2.readyWrite)
        {
            buffer2.currentSize = 0;
            for (i = 0; i < BUFFER_SIZE; i++)
            {
                //insure that the structure is empty
                req_null(&buffer2.requests[i]);

                //read a line
                logLine = malloc((MAX_LINE_LENGTH) * sizeof(char));
                err = log_readline(logfile, logLine, &regex);
                lineNum++;
                if (feof(logfile))
                {
                    break;
                }
                else if(err == 1)
                {
                    fprintf(stderr, "Error: invalid entry on line %d in log file\n", lineNum);
                    fprintf(errorFile, "Error: invalid entry on line %d : %s\n", lineNum, logLine);
                    --i;
                    continue;
                }
                else if(err == 2)
                {
                    fprintf(stderr, "Error: unknown reader error: %d in log file\n", lineNum);
                    fprintf(errorFile, "Error: unknown reader error %d\n", lineNum);
                    fclose(logfile);
                    fclose(errorFile);
                    close_debug_file();
                    exit(1);
                }
                
                //parse line and add it to the buffer
                err = parse_line(logLine, &buffer2.requests[i]);
                if (err)
                {
                    printf("parse error on line %d\n%s\n", lineNum, logLine);
                    fprintf(errorFile, "Error: parsing line %d : %s\n", lineNum, logLine);
                    --i;
                    continue;
                }
                buffer2.currentSize++;
                free(logLine);

                /*#if DEBUG==1
                    printf("%s\n", buffer2.requests[i].host);
                    printf("%s\n", buffer2.requests[i].clientId);
                    printf("%s\n", buffer2.requests[i].userId);
                    printf("%s\n", buffer2.requests[i].time);
                    printf("%s\n", buffer2.requests[i].req);
                    printf("%d\n", buffer2.requests[i].retCode);
                    printf("%d\n", buffer2.requests[i].dataSize);
                    printf("%s\n", buffer2.requests[i].referer);
                    printf("%s\n", buffer2.requests[i].userAgent);
                #endif*/

            }

            buffer2.readyWrite = FALSE;
            buffer2.readyRead = TRUE;
        }
   
    }

    MASTER_SWITCH = FALSE;
    // wait for any remaining analysis to finish
    pthread_join(analysisThread, NULL);

    #if DEBUG==1
        printf("\nTotal Statistics\n");
        printf("Total 200s: %d\n", totalStats.total200);
        printf("Total 404s: %d\n", totalStats.total404);
        printf("Total injections: %d\n", totalStats.totalInjections);
        printf("Total visits: %d\n", totalStats.totalVisits);
    #endif

    //Write Statistics to file
    if(write_general_stats() != 0)
    {
        fprintf(errorFile, "Error: Unable to write statistics\n");
        fclose(logfile);
        fclose(errorFile);
        close_debug_file();
        exit(1);
    }
    
    UniqueRequests topRequests;
    if(get_top_unique_requests(10, &topRequests) != 0)
    {
        fprintf(stderr, "Error: unable to get top requests\n");
        fprintf(errorFile, "Error: unable to get top requests\n");
        fclose(logfile);
        fclose(errorFile);
        close_debug_file();
        exit(1);
    }
    if(write_top_requests(&topRequests) != 0)
    {
        fprintf(stderr, "Error: unable to write top requests\n");
        fprintf(errorFile, "Error: unable to write top requests\n");
        fclose(logfile);
        fclose(errorFile);
        close_debug_file();
        exit(1);
    }

    fprintf(stderr, "Total number of unique requests: %d\n", uniqueRequests.currentSize);

    //cleanup
    buffer_free(&buffer1);
    buffer_free(&buffer2);
    debug_write("Freeing memory for line buffer\n");
    fclose(logfile);
    regfree(&regex);
    fclose(errorFile);
    debug_write("Closing access.log file...\n");
    close_debug_file();
    for(i = 0;i <topRequests.currentSize; i++)
    {
        free(topRequests.urls[i].url);
    }
    free(topRequests.urls);
    for(i = 0; i < uniqueRequests.currentSize; i++)
    {
        free(uniqueRequests.urls[i].url);
    }
    free(uniqueRequests.urls);

    printf("\nFinished Analysis\n\n");
    return 0;
}
Ejemplo n.º 9
0
static int mlx5_alloc_context(struct verbs_device *vdev,
			      struct ibv_context *ctx, int cmd_fd)
{
	struct mlx5_context	       *context;
	struct mlx5_alloc_ucontext	req;
	struct mlx5_alloc_ucontext_resp resp;
	struct ibv_device		*ibdev = &vdev->device;
	struct verbs_context *verbs_ctx = verbs_get_ctx(ctx);
	int	i;
	int	page_size = to_mdev(ibdev)->page_size;
	int	tot_uuars;
	int	low_lat_uuars;
	int 	gross_uuars;
	int	j;
	off_t	offset;

	mlx5_single_threaded = single_threaded_app();

	context = to_mctx(ctx);
	context->ibv_ctx.cmd_fd = cmd_fd;

	memset(&resp, 0, sizeof(resp));
	open_debug_file(context);
	set_debug_mask();
	set_freeze_on_error();
	if (gethostname(context->hostname, sizeof(context->hostname)))
		strcpy(context->hostname, "host_unknown");

	tot_uuars = get_total_uuars();
	if (tot_uuars <= 0) {
		if (tot_uuars == 0)
			errno = EINVAL;
		else
			errno = -tot_uuars;
		goto err_free;
	}

	gross_uuars = tot_uuars / MLX5_NUM_UUARS_PER_PAGE * 4;
	context->bfs = calloc(gross_uuars, sizeof *context->bfs);
	if (!context->bfs) {
		errno = ENOMEM;
		goto err_free;
	}

	low_lat_uuars = get_num_low_lat_uuars();
	if (low_lat_uuars < 0) {
		errno = ENOMEM;
		goto err_free_bf;
	}

	if (low_lat_uuars > tot_uuars - 1) {
		errno = ENOMEM;
		goto err_free_bf;
	}

	memset(&req, 0, sizeof(req));
	req.total_num_uuars = tot_uuars;
	req.num_low_latency_uuars = low_lat_uuars;
	if (ibv_cmd_get_context(&context->ibv_ctx, &req.ibv_req, sizeof req,
				&resp.ibv_resp, sizeof resp))
		goto err_free_bf;

	context->max_num_qps		= resp.qp_tab_size;
	context->bf_reg_size		= resp.bf_reg_size;
	context->tot_uuars		= resp.tot_uuars;
	context->low_lat_uuars		= low_lat_uuars;
	context->cache_line_size	= resp.cache_line_size;
	context->max_sq_desc_sz = resp.max_sq_desc_sz;
	context->max_rq_desc_sz = resp.max_rq_desc_sz;
	context->max_send_wqebb	= resp.max_send_wqebb;
	context->num_ports	= resp.num_ports;
	context->max_recv_wr	= resp.max_recv_wr;
	context->max_srq_recv_wr = resp.max_srq_recv_wr;
	context->max_desc_sz_sq_dc = resp.max_desc_sz_sq_dc;
	context->atomic_sizes_dc = resp.atomic_sizes_dc;
	pthread_mutex_init(&context->rsc_table_mutex, NULL);
	pthread_mutex_init(&context->srq_table_mutex, NULL);
	for (i = 0; i < MLX5_QP_TABLE_SIZE; ++i)
		context->rsc_table[i].refcnt = 0;

	context->db_list = NULL;

	pthread_mutex_init(&context->db_list_mutex, NULL);


	for (i = 0; i < resp.tot_uuars / MLX5_NUM_UUARS_PER_PAGE; ++i) {
		offset = 0;
		set_command(MLX5_MMAP_GET_REGULAR_PAGES_CMD, &offset);
		set_index(i, &offset);
		context->uar[i] = mmap(NULL, to_mdev(ibdev)->page_size, PROT_WRITE,
				       MAP_SHARED, cmd_fd,
				       page_size * offset);
		if (context->uar[i] == MAP_FAILED) {
			context->uar[i] = NULL;
			goto err_free_bf;
		}
	}

	for (j = 0; j < gross_uuars; ++j) {
		context->bfs[j].reg = context->uar[j / 4] +
			MLX5_BF_OFFSET + (j % 4) * context->bf_reg_size;
		context->bfs[j].need_lock = need_uuar_lock(context, j);
		mlx5_spinlock_init(&context->bfs[j].lock);
		context->bfs[j].offset = 0;
		if (j)
			context->bfs[j].buf_size = context->bf_reg_size / 2;

		context->bfs[j].uuarn = j;
	}

	mlx5_spinlock_init(&context->lock32);

	context->prefer_bf = get_always_bf();
	context->shut_up_bf = get_shut_up_bf();
	mlx5_read_env(ibdev, context);

	mlx5_spinlock_init(&context->hugetlb_lock);
	INIT_LIST_HEAD(&context->hugetlb_list);

	pthread_mutex_init(&context->task_mutex, NULL);

	ctx->ops = mlx5_ctx_ops;
	set_extended(verbs_ctx);
	set_experimental(ctx);

	return 0;

err_free_bf:
	free(context->bfs);

err_free:
	for (i = 0; i < MLX5_MAX_UAR_PAGES; ++i) {
		if (context->uar[i])
			munmap(context->uar[i], page_size);
	}
	close_debug_file(context);
	return errno;
}