Exemplo n.º 1
0
void mlog_load(char *fname)
{
  char *group_index, *group_level;
  char *name, *value, *logname;
  int n, default_level;
  inip_file_t *fd;
  inip_group_t *g;
  inip_element_t *ele;


  if (_log_lock == NULL) _log_init();

  group_index = "log_index";
  group_level = "log_level";

  //** Open the file
  fd = inip_read(fname);
  if (fd == NULL) {
     log_printf(0, "Error loading module definitions!  fname=%s\n", fname);
     return;
  }

  default_level = inip_get_integer(fd, group_level, "default", 0);
//printf("mlog_load: inital ll=%d\n", _log_level);
  _log_level = inip_get_integer(fd, group_level, "start_level", _log_level);
//printf("mlog_load: new ll=%d\n", _log_level);
  for (n=0; n<_mlog_size; n++) _mlog_table[n] = default_level;
  logname = inip_get_string(fd, group_level, "output", "stdout");
  open_log(logname);
  _log_maxsize = inip_get_integer(fd, group_level, "size", 100*1024*1024);

  //** Load the mappings
  g = inip_find_group(fd, group_index);
  if (g == NULL) {
     log_printf(1, "Missing %s group!\n", group_index);
     inip_destroy(fd);
     return;
  }

  ele = inip_first_element(g);
  while (ele != NULL) {
     name = inip_get_element_key(ele);
     value = inip_get_element_value(ele);

     n = (value != NULL) ? atoi(value) : -1;

     if ((n>=0) && (n<_mlog_size)) {
        _mlog_file_table[n] = strdup(name);
        _mlog_table[n] = inip_get_integer(fd, group_level, name, _mlog_table[n]);
//printf("mlog_load: mi=%d key=%s val=%d\n", n, name, _mlog_table[n]);
     } else {
       log_printf(0, "Invalid index: %s=%d  should be between 0..%d!  Skipping option\n", name, n, _mlog_size);
     }

     //** Move to the next segmnet to load
     ele = inip_next_element(ele);
  }

  inip_destroy(fd);
}
Exemplo n.º 2
0
int mlog_printf(int suppress_header, int module_index, int level, const char *fn, const char *fname, int line, const char *fmt, ...)
{
  va_list args;
//  int err;
  int n = 0;

  if (level > _mlog_table[module_index]) return(0);
  if (level > _log_level) return(0);

  if (_log_lock == NULL) _log_init();

  _lock_log();
  if (_log_fd == NULL) {_log_fd = stdout; _log_special=1; }

  if (suppress_header == 0) n = fprintf(_log_fd, "[mi=%d tid=%d file=%s:%d fn=%s] ", module_index, atomic_thread_id, fname, line, fn);
  va_start(args, fmt);
  n += vfprintf(_log_fd, fmt, args);
  va_end(args);

  _log_currsize += n;
  if (_log_currsize > _log_maxsize) {
//     if (_log_special==0) ftruncate(fileno(_log_fd), 0L);
     if (_log_special==0) { fclose(_log_fd); _open_log(NULL, 0); }
     _log_currsize = 0;
  }
  _unlock_log();

  return(n);
}
Exemplo n.º 3
0
int main(int argc, char *argv[])
{
 	_802_3_init();
	_nat_init();
	_arp_init();
	_arpreply_init();
	_ip_init();
	_standard_init();
	_log_init();
	_redirect_init();
	_vlan_init();
	_mark_m_init();
	_mark_init();
	_pkttype_init();
	_stp_init();
	_among_init();
	_limit_init();
	_ulog_init();
	_t_filter_init();
	_t_nat_init();
	_t_broute_init();

	pseudomain(argc, argv);
	return 0;
}
Exemplo n.º 4
0
void _open_log(char *fname, int dolock) {
  if (dolock == 1) {
     if (_log_lock == NULL) _log_init();

     _lock_log();
  }

  _log_currsize = 0;

  if (fname != NULL) {    //** If NULL we'll just use the old name
     strncpy(_log_fname, fname, sizeof(_log_fname)-1);
     _log_fname[sizeof(_log_fname)-1]= '\0';
  }

  _log_special = 0;
  if (strcmp(_log_fname, "stdout") == 0) {
     _log_special = 1;
     _log_fd = stdout;
  } else if (strcmp(_log_fname, "stderr") == 0) {
     _log_special = 2;
     _log_fd = stderr;
  } else if ((_log_fd = fopen(_log_fname, "w")) == NULL) {
     fprintf(stderr, "OPEN_LOG failed! Attempted to us log file %s\n", _log_fname);
     perror("OPEN_LOG: ");
  }

  if (dolock == 1) _unlock_log();
}
Exemplo n.º 5
0
/* reinitialize log data structures. Like log_init, but do not init
 * the log mutex
 */
int log_alter(log_options_t opt, log_facility_t fac, char *logfile)
{
	int rc = 0;
	slurm_mutex_lock(&log_lock);
	rc = _log_init(NULL, opt, fac, logfile);
	slurm_mutex_unlock(&log_lock);
	return rc;
}
Exemplo n.º 6
0
void flush_log()
{
  if (_log_lock == NULL) _log_init();

  _lock_log();
  fflush(_log_fd);
  _unlock_log();
}
Exemplo n.º 7
0
SOL_API struct sol_pwm *
sol_pwm_open(int device, int channel, const struct sol_pwm_config *config)
{
    struct sol_pwm *pwm;

    _log_init();

    pwm = sol_pwm_open_raw(device, channel, config);
#ifdef USE_PIN_MUX
    if (pwm && sol_pin_mux_setup_pwm(device, channel)) {
        SOL_WRN("Pin Multiplexer Recipe for pwm device=%d channel=%d found, \
            but couldn't be applied.", device, channel);
        sol_pwm_close(pwm);
        pwm = NULL;
    }
Exemplo n.º 8
0
/* reinitialize log data structures. Like log_init, but do not init
 * the log mutex
 */
int log_alter_with_fp(log_options_t opt, log_facility_t fac, FILE *fp_in)
{
	int rc = 0;
	slurm_mutex_lock(&log_lock);
	rc = _log_init(NULL, opt, fac, NULL);
	if (log->logfp)
		fclose(log->logfp); /* Ignore errors */
	log->logfp = fp_in;
	if (log->logfp) {
		int fd;
		if ((fd = fileno(log->logfp)) < 0)
			log->logfp = NULL;
		/* don't close fd on out since this fd was made
		 * outside of the logger */
	}
	slurm_mutex_unlock(&log_lock);
	return rc;
}
Exemplo n.º 9
0
SOL_API struct sol_gpio *
sol_gpio_open_by_label(const char *label, const struct sol_gpio_config *config)
{
    uint32_t pin;

    _log_init();

#ifdef USE_PIN_MUX
    if (!sol_pin_mux_map(label, SOL_IO_GPIO, &pin))
        return sol_gpio_open(pin, config);

    SOL_WRN("Label '%s' couldn't be mapped or can't be used as GPIO", label);
#else
    SOL_INF("Pin Multiplexer support is necessary to open a 'board pin'.");
    (void)pin;
#endif

    return NULL;
}
Exemplo n.º 10
0
SOL_API struct sol_aio *
sol_aio_open(int device, int pin, unsigned int precision)
{
    struct sol_aio *aio;

    _log_init();

    aio = sol_aio_open_raw(device, pin, precision);
#ifdef USE_PIN_MUX
    if (aio && sol_pin_mux_setup_aio(device, pin)) {
        SOL_WRN("Pin Multiplexer Recipe for aio device=%d pin=%d found, "
            "but couldn't be applied.", device, pin);
        sol_aio_close(aio);
        aio = NULL;
    }
#endif

    return aio;
}
Exemplo n.º 11
0
SOL_API struct sol_aio *
sol_aio_open_by_label(const char *label, unsigned int precision)
{
#ifdef USE_PIN_MUX
    int device, pin;
#endif

    _log_init();

#ifdef USE_PIN_MUX
    if (!sol_pin_mux_map(label, SOL_IO_AIO, &device, &pin))
        return sol_aio_open(device, pin, precision);

    SOL_WRN("Label '%s' couldn't be mapped or can't be used as Analog I/O", label);
#else
    SOL_INF("Pin Multiplexer support is necessary to open a 'board pin'.");
#endif

    return NULL;
}
Exemplo n.º 12
0
SOL_API struct sol_pwm *
sol_pwm_open_by_label(const char *label, const struct sol_pwm_config *config)
{
    int device, channel;

    _log_init();

#ifdef USE_PIN_MUX
    if (!sol_pin_mux_map(label, SOL_IO_PWM, &device, &channel))
        return sol_pwm_open(device, channel, config);

    SOL_WRN("Label '%s' couldn't be mapped or can't be used as PWM", label);
#else
    SOL_INF("Pin Multiplexer support is necessary to open a 'board pin'.");
    (void)device;
    (void)channel;
#endif

    return NULL;
}
Exemplo n.º 13
0
SOL_API struct sol_gpio *
sol_gpio_open(uint32_t pin, const struct sol_gpio_config *config)
{
    struct sol_gpio *gpio;

    _log_init();

    SOL_NULL_CHECK(config, NULL);

    gpio = sol_gpio_open_raw(pin, config);
#ifdef USE_PIN_MUX
    if (gpio && sol_pin_mux_setup_gpio(pin, config)) {
        SOL_ERR("Pin Multiplexer Recipe for gpio=%d found, but couldn't be applied.", pin);
        sol_gpio_close(gpio);
        gpio = NULL;
    }
#endif

    return gpio;
}
Exemplo n.º 14
0
Arquivo: log.c Projeto: cread/slurm
/*
 * log a message at the specified level to facilities that have been
 * configured to receive messages at that level
 */
static void log_msg(log_level_t level, const char *fmt, va_list args)
{
	char *pfx = "";
	char *buf = NULL;
	char *msgbuf = NULL;
	int priority = LOG_INFO;

	slurm_mutex_lock(&log_lock);

	if (!LOG_INITIALIZED) {
		log_options_t opts = LOG_OPTS_STDERR_ONLY;
		_log_init(NULL, opts, 0, NULL);
	}

	if (SCHED_LOG_INITIALIZED &&
	    (sched_log->opt.logfile_level > LOG_LEVEL_QUIET) &&
	    (xstrncmp(fmt, "sched: ", 7) == 0)) {
		buf = vxstrfmt(fmt, args);
		xlogfmtcat(&msgbuf, "[%M] %s%s%s", sched_log->fpfx, pfx, buf);
		_log_printf(sched_log, sched_log->fbuf, sched_log->logfp,
			    "%s\n", msgbuf);
		fflush(sched_log->logfp);
		xfree(msgbuf);
	}
	if ((level > log->opt.syslog_level)  &&
	    (level > log->opt.logfile_level) &&
	    (level > log->opt.stderr_level)) {
		slurm_mutex_unlock(&log_lock);
		xfree(buf);
		return;
	}

	if (log->opt.prefix_level || (log->opt.syslog_level > level)) {
		switch (level) {
		case LOG_LEVEL_FATAL:
			priority = LOG_CRIT;
			pfx = "fatal: ";
			break;

		case LOG_LEVEL_ERROR:
			priority = LOG_ERR;
			pfx = "error: ";
			break;

		case LOG_LEVEL_SCHED:
		case LOG_LEVEL_INFO:
		case LOG_LEVEL_VERBOSE:
			priority = LOG_INFO;
			break;

		case LOG_LEVEL_DEBUG:
			priority = LOG_DEBUG;
			pfx = "debug:  ";
			break;

		case LOG_LEVEL_DEBUG2:
			priority = LOG_DEBUG;
			pfx = "debug2: ";
			break;

		case LOG_LEVEL_DEBUG3:
			priority = LOG_DEBUG;
			pfx = "debug3: ";
			break;

		case LOG_LEVEL_DEBUG4:
			priority = LOG_DEBUG;
			pfx = "debug4: ";
			break;

		case LOG_LEVEL_DEBUG5:
			priority = LOG_DEBUG;
			pfx = "debug5: ";
			break;

		default:
			priority = LOG_ERR;
			pfx = "internal error: ";
			break;
		}

	}

	if (!buf) {
		/* format the basic message,
		 * if not already done for scheduling log */
		buf = vxstrfmt(fmt, args);
	}

	if (level <= log->opt.stderr_level) {

		fflush(stdout);
		if (log->fmt == LOG_FMT_THREAD_ID) {
			char tmp[64];
			set_idbuf(tmp);
			_log_printf(log, log->buf, stderr, "%s: %s%s\n",
			            tmp, pfx, buf);
		} else {
			_log_printf(log, log->buf, stderr, "%s: %s%s\n",
			            log->argv0, pfx, buf);
		}
		fflush(stderr);
	}

	if ((level <= log->opt.logfile_level) && (log->logfp != NULL)) {

		xlogfmtcat(&msgbuf, "[%M] %s%s%s", log->fpfx, pfx, buf);
		_log_printf(log, log->fbuf, log->logfp, "%s\n", msgbuf);
		fflush(log->logfp);

		xfree(msgbuf);
	}

	if (level <=  log->opt.syslog_level) {

		/* Avoid changing errno if syslog fails */
		int orig_errno = slurm_get_errno();
		xlogfmtcat(&msgbuf, "%s%s", pfx, buf);
		openlog(log->argv0, LOG_PID, log->facility);
		syslog(priority, "%.500s", msgbuf);
		closelog();
		slurm_seterrno(orig_errno);

		xfree(msgbuf);
	}

	slurm_mutex_unlock(&log_lock);

	xfree(buf);
}
Exemplo n.º 15
0
int main(int argc, char *argv[]) {
	int status = 0;

	_log_init();

	_config_default_init();

	_cmdline_process(argc, argv);

	if (setregid(config.gid, config.gid) < 0)
		_failure("setregid");

	if (setreuid(config.uid, config.uid) < 0)
		_failure("setreuid");

	if (_signal_init() < 0)
		_failure("_signal_init");

	if (_daemonize() < 0)
		_failure("_daemonize");

	for (;;) {
		if (config.flags & CONFIG_FL_PIDF_CREATE)
			_file_pid_create(config.pidf_name);

		/* Make sure that we receive a valid status value... otherwise jump out of here. */
		if ((status = _bexec(config.binary, config.args)) == -1) {
			log_warn("main(): _bexec(): Unable to execute binary '%s': %s.\n", config.binary, strerror(errno));
			break;
		}

		/* Log process termination */
		log_info("main(): _bexec(): Execution of '%s' terminated (Exit status: %d).\n", config.binary, WEXITSTATUS(status));

		/* Log any signals that caused the termination */
		if (WIFSIGNALED(status))
			log_info("main(): Child process \'%s\' was terminated due to unhandled signal %d.\n", config.binary, WTERMSIG(status));

		/* Check if the exit status refers to a bad runtime state */
		if (WEXITSTATUS(status) == PROCESS_EXIT_STATUS_CUSTOM_BAD_RUNTIME_OR_CONFIG) {
			log_info("main(): Child process \'%s\' won't be restarted due to runtime or configuration errors.\n", config.binary);

			/* If so, do not attempt to restart the process, even if explicitly requested
			 * by command line options.
			 */
			break;
		}

		if (config.flags & CONFIG_FL_PROC_RSTIGN) {
			log_info("main(): Restarting child \'%s\' regardless of exit status code.\n", config.binary);

			/* Restart child regardless of signals and exit codes */
			_main_loop_restart_prepare();

			continue;
		} else if ((config.flags & CONFIG_FL_PROC_RSTUSIG) && WIFSIGNALED(status) && (WTERMSIG(status) != SIGKILL) && (WTERMSIG(status) != SIGQUIT)) {
			log_info("main(): Restarting child \'%s\' since its termination was caused by an unhandled signal other than SIGKILL and SIGQUIT. (Termination signal was %d)\n", config.binary, WTERMSIG(status));

			/* Restart child if any unhandled signal other than KILL and QUIT caused its
			 * termination
			 */
			_main_loop_restart_prepare();

			continue;
		} else if ((config.flags & CONFIG_FL_PROC_RESTART) && WEXITSTATUS(status)) {
			log_info("main(): Restarting child \'%s\' due to a non-zero exit status code.", config.binary);

			/* Restart child is exit status code isn't zero */
			_main_loop_restart_prepare();

			continue;
		}

		break;
	}

	if (status < 0)
		_failure("_bexec");

	if (config.flags & CONFIG_FL_PIDF_CREATE) {
		if (unlink(config.pidf_name) < 0)
			_failure("unlink");
	}

	_config_destroy();

	_log_destroy();

	return 0;
}
Exemplo n.º 16
0
int main(int argc, char *argv[])
{
   int c;
   char config_file_path[256];
   word usage = false;
   while ((c = getopt (argc, argv, ":c:")) != -1)
   {
      switch (c)
      {
      case 'c':
         strcpy(config_file_path, optarg);
         break;
      case ':':
         break;
      case '?':
      default:
         usage = true;
         break;
      }
   }

   char * config_fail;
   if((config_fail = load_config(config_file_path)))
   {
      printf("Failed to read config file \"%s\":  %s\n", config_file_path, config_fail);
      usage = true;
   }

   debug = *conf[conf_debug];

   if(usage)
   {
      printf("\tUsage: %s [-c /path/to/config/file.conf]\n\n", argv[0] );
      exit(1);
   }

   int lfp = 0;

   // Set up log
   _log_init(debug?"/tmp/vstpdb.log":"/var/log/garner/vstpdb.log", debug?1:0);

   // Enable core dumps
   struct rlimit limit;
   if(!getrlimit(RLIMIT_CORE, &limit))
   {
      limit.rlim_cur = RLIM_INFINITY;
      setrlimit(RLIMIT_CORE, &limit);
   }

   start_time = time(NULL);

   // DAEMONISE
   if(!debug)
   {
      int i=fork();
      if (i<0)
      {
         /* fork error */
         _log(CRITICAL, "fork() error.  Aborting.");
         exit(1);
      }
      if (i>0) exit(0); /* parent exits */
      /* child (daemon) continues */
        
      pid_t sid = setsid(); /* obtain a new process group */   
      if(sid < 0)
      {
         /* setsid error */
         _log(CRITICAL, "setsid() error.  Aborting.");
         exit(1);
      }

      for (i=getdtablesize(); i>=0; --i) close(i); /* close all descriptors */

      umask(022); // Created files will be rw for root, r for all others

      i = chdir("/var/run/");  
      if(i < 0)
      {
         /* chdir error */
         _log(CRITICAL, "chdir() error.  Aborting.");
         exit(1);
      }
        
      if((lfp = open("/var/run/vstpdb.pid", O_RDWR|O_CREAT, 0640)) < 0)
      {
         _log(CRITICAL, "Unable to open pid file \"/var/run/vstpdb.pid\".  Aborting.");
         exit(1); /* can not open */
      }
           
      if (lockf(lfp,F_TLOCK,0)<0)
      {
         _log(CRITICAL, "Failed to obtain lock.  Aborting.");
         exit(1); /* can not lock */
      }
        
      char str[128];
      sprintf(str, "%d\n", getpid());
      i = write(lfp, str, strlen(str)); /* record pid to lockfile */
      
      _log(GENERAL, "");
      _log(GENERAL, "%s %s", NAME, BUILD);
      _log(GENERAL, "Running as daemon.");
   }
   else
   {
      _log(GENERAL, "");
      _log(GENERAL, "%s %s", NAME, BUILD);
      _log(GENERAL, "Running in local mode.");
   }
     
   // Check core dumps
   if(prctl(PR_GET_DUMPABLE, 0, 0, 0, 0) != 1)
   {
      _log(MAJOR, "PR_GET_DUMPABLE not 1.");
   }
   else
   {
      _log(DEBUG, "PR_GET_DUMPABLE is 1.");
   }
   if(!getrlimit(RLIMIT_CORE, &limit))
   {
      if(limit.rlim_cur != RLIM_INFINITY)
      {
         _log(MAJOR, "RLIMIT_CORE not RLIM_INFINITY.");
      }
      else
      {
         _log(DEBUG, "RLIMIT_CORE is RLIM_INFINITY.");
      }
   }
   else
   {
      _log(MAJOR, "Unable to determine RLIMIT_CORE.");
   }

   run = true;
   interrupt = false;

   {
      // Sort out the signal handlers
      struct sigaction act;
      sigset_t block_mask;
     
      sigemptyset(&block_mask);
      act.sa_handler = termination_handler;
      act.sa_mask = block_mask;
      act.sa_flags = 0;
      if(sigaction(SIGTERM, &act, NULL) || sigaction(SIGINT, &act, NULL))
      {
         _log(CRITICAL, "Failed to set up signal handler.");
         exit(1);
      }
   }

   if(!debug) signal(SIGCHLD,SIG_IGN); /* ignore child */
   if(!debug) signal(SIGTSTP,SIG_IGN); /* ignore tty signals */
   if(!debug) signal(SIGTTOU,SIG_IGN);
   if(!debug) signal(SIGTTIN,SIG_IGN);

   // Zero the stats
   {
      word i;
      for(i=0; i < MAXstats; i++) 
      {
         stats[i] = 0;
         grand_stats[i] = 0;
      }
   }

   // Startup delay
   {
      struct sysinfo info;
      word logged = false;
      word i;
      while(run && !debug && (sysinfo(&info) || info.uptime < (512 + 128)))
      {
         if(!logged) _log(GENERAL, "Startup delay...");
         logged = true;
         for(i = 0; i < 8 && run; i++) sleep(1);
      }
   }

   if(run) perform();

   if(lfp) close(lfp);

   return 0;
}
Exemplo n.º 17
0
int main(int argc, char **argv)
{
   char config_file_path[256];
   opt_filename = NULL;
   opt_url = NULL;
   fetch_all = false;
   test_mode = false;
   verbose = false;
   opt_insecure = false;
   used_insecure = false;

   strcpy(config_file_path, "/etc/openrail.conf");
   word usage = false;
   int c;
   while ((c = getopt (argc, argv, ":c:u:f:tpih")) != -1)
      switch (c)
      {
      case 'c':
         strcpy(config_file_path, optarg);
         break;
      case 'u':
         if(!opt_filename) opt_url = optarg;
         break;
      case 'f':
         if(!opt_url) opt_filename = optarg;
         break;
      case 'a':
         fetch_all = true;
         break;
      case 't':
         test_mode = true;
         break;
      case 'p':
         verbose = true;
         break;
      case 'i':
         opt_insecure = true;
         break;
      case 'h':
         usage = true;
         break;
      case ':':
         break;
      case '?':
      default:
         usage = true;
      break;
      }

   char * config_fail;
   if((config_fail = load_config(config_file_path)))
   {
      printf("Failed to read config file \"%s\":  %s\n", config_file_path, config_fail);
      usage = true;
   }

   if(usage) 
   {
      printf("%s %s  Usage: %s [-c /path/to/config/file.conf] [-u <url> | -f <path> | -a] [-t | -r] [-p][-i]\n", NAME, BUILD, argv[0]);
      printf(
             "-c <file>  Path to config file.\n"
             "Data source:\n"
             "default    Fetch latest update.\n"
             "-u <url>   Fetch from specified URL.\n"
             "-f <file>  Use specified file.  (Must already be decompressed.)\n"
             "Actions:\n"
             "default    Apply data to database.\n"
             "-t         Report datestamp on download or file, do not apply to database.\n"
             "Options:\n"
             "-i         Insecure.  Circumvent certificate checks if necessary.\n"
             "-p         Print activity as well as logging.\n"
             );
      exit(1);
   }

   char zs[1024];

   start_time = time(NULL);

   debug = *conf[conf_debug];
  
   _log_init(debug?"/tmp/tscdb.log":"/var/log/garner/tscdb.log", (debug?1:(verbose?4:0)));
   
   _log(GENERAL, "");
   _log(GENERAL, "%s %s", NAME, BUILD);
   
   // Enable core dumps
   struct rlimit limit;
   if(!getrlimit(RLIMIT_CORE, &limit))
   {
      limit.rlim_cur = RLIM_INFINITY;
      setrlimit(RLIMIT_CORE, &limit);
   }
   
   int i;
   for(i = 0; i < MATCHES; i++)
   {
      if(regcomp(&match[i], match_strings[i], REG_ICASE + REG_EXTENDED))
      {
         sprintf(zs, "Failed to compile regex match %d", i);
         _log(MAJOR, zs);
      }
   }
   
   // Initialise database
   if(db_init(conf[conf_db_server], conf[conf_db_user], conf[conf_db_password], conf[conf_db_name])) exit(1);

   {
      word e;
      if((e=database_upgrade(cifdb)))
      {
         _log(CRITICAL, "Error %d in upgrade_database().  Aborting.", e);
         exit(1);
      }
   }

   run = 1;
   tiploc_ignored = false;

   // Zero the stats
   {
      word i;
      for(i = 0; i < MAXStats; i++) { stats[i] = 0; }
   }

   if(fetch_file())
   {
      if(opt_url || opt_filename)
      {
         _log(GENERAL, "Failed to find data.");
         exit(1);
      }
      {
         char report[256];
         _log(GENERAL, "Failed to fetch file.");
         
         sprintf(report, "Failed to collect timetable update after %lld attempts.", stats[Fetches]);
         email_alert(NAME, BUILD, "Timetable Update Failure Report", report);
      }
      exit(1);
   }

   char in_q = 0;
   char b_depth = 0;

   size_t ibuf = 0;
   size_t iobj = 0;
   size_t buf_end;

   // Determine applicable update
   {
      MYSQL_RES * result0;
      MYSQL_ROW row0;
      last_update_id[0] = '\0';
      if(!db_query("SELECT MAX(id) FROM updates_processed"))
      {
         result0 = db_store_result();
         if((row0 = mysql_fetch_row(result0)))
         {
            strcpy(last_update_id, row0[0]);
         }
         mysql_free_result(result0);
      }
   }

   if(last_update_id[0] == '\0')
   {
      _log(CRITICAL, "Failed to determine last update id from database.");
      exit(1);
   }


   if(test_mode)
   {
   }
   else
   {
      char c, pc;
      pc = 0;
      // Run through the file splitting off each JSON object and passing it on for processing.

      // DB may have dropped out due to long delay
      (void) db_connect();
      if(db_start_transaction()) _log(CRITICAL, "Failed to initiate database transaction.");
      while((buf_end = fread(buffer, 1, MAX_BUF, fp_result)) && run && !db_errored)
      {
         for(ibuf = 0; ibuf < buf_end && run && !db_errored; ibuf++)
         {
            c = buffer[ibuf];
            if(c != '\r' && c != '\n') 
            {
               obj[iobj++] = c;
               if(iobj >= MAX_OBJ)
               {
                  _log(CRITICAL, "Object buffer overflow!");
                  exit(1);
               }
               if(c == '"' && pc != '\\') in_q = ! in_q;
               if(!in_q && c == '{') b_depth++;
               if(!in_q && c == '}' && b_depth-- && !b_depth)
               {
                  obj[iobj] = '\0';
                  process_object(obj);
                  iobj = 0;
               }
            }
            pc = c;
         }
      }
      fclose(fp_result);
      if(db_errored)
      {
         _log(CRITICAL, "Update rolled back due to database error.");
         (void) db_rollback_transaction();
      }
      else
      {
         _log(GENERAL, "Committing database updates...");
         if(db_commit_transaction())
         {
            _log(CRITICAL, "Database commit failed.");
         }
         else
         {
            _log(GENERAL, "Committed.");
         }
      }
   }

#define REPORT_SIZE 16384
   char report[REPORT_SIZE];
   report[0] = '\0';

   _log(GENERAL, "");
   _log(GENERAL, "End of run:");

   if(used_insecure)
   {
      strcat(report, "*** Warning: Insecure download used.\n");
      _log(GENERAL, "*** Warning: Insecure download used.");
   }

   sprintf(zs, "             Elapsed time: %ld minutes", (time(NULL) - start_time + 30) / 60);
   _log(GENERAL, zs);
   strcat(report, zs); strcat(report, "\n");
   if(test_mode)
   {
      sprintf(zs, "Test mode.  No database changes made.");
      _log(GENERAL, zs);
      strcat(report, zs); strcat(report, "\n");
      exit(0);
   }

   for(i=0; i<MAXStats; i++)
   {
      sprintf(zs, "%25s: %s", stats_category[i], commas_q(stats[i]));
      if(i == DBError && stats[i]) strcat(zs, " ****************");
      _log(GENERAL, zs);
      strcat(report, zs);
      strcat(report, "\n");
   }

   db_disconnect();

   email_alert(NAME, BUILD, "Timetable Update Report", report);

   exit(0);
}
Exemplo n.º 18
0
/* Parse arguments, etc then get my socket address/port information. Attempt to
 * adopt this process into a job in the following order:
 * 	1) If the user has only one job on the node, pick that one
 * 	2) Send RPC to source IP of socket. If there is a slurmd at the IP
 * 		address, ask it which job I belong to. On success, pick that one
 *	3) Pick a job semi-randomly (default) or skip the adoption (if
 *		configured)
 */
PAM_EXTERN int pam_sm_acct_mgmt(pam_handle_t *pamh, int flags
				__attribute__((unused)), int argc, const char **argv)
{
	int retval = PAM_IGNORE, rc, slurmrc, bufsize, user_jobs;
	char *user_name;
	List steps = NULL;
	step_loc_t *stepd = NULL;
	struct passwd pwd, *pwd_result;
	char *buf = NULL;

	_init_opts();
	_parse_opts(pamh, argc, argv);
	_log_init(opts.log_level);

	switch (opts.action_generic_failure) {
	case CALLERID_ACTION_DENY:
		rc = PAM_PERM_DENIED;
		break;
	case CALLERID_ACTION_ALLOW:
		rc = PAM_SUCCESS;
		break;
	case CALLERID_ACTION_IGNORE:
		rc = PAM_IGNORE;
		break;
		/* Newer gcc versions warn if enum cases are missing */
	default:
		error("The code is broken!!!!");
	}

	retval = pam_get_item(pamh, PAM_USER, (void *) &user_name);
	if (user_name == NULL || retval != PAM_SUCCESS)  {
		pam_syslog(pamh, LOG_ERR, "No username in PAM_USER? Fail!");
		return PAM_SESSION_ERR;
	}

	/* Check for an unsafe config that might lock out root. This is a very
	 * basic check that shouldn't be 100% relied on */
	if (!opts.ignore_root &&
	    (opts.action_unknown == CALLERID_ACTION_DENY ||
	     opts.action_no_jobs != CALLERID_ACTION_ALLOW ||
	     opts.action_adopt_failure != CALLERID_ACTION_ALLOW ||
	     opts.action_generic_failure != CALLERID_ACTION_ALLOW
		    )) {
		/* Let's get verbose */
		info("===============================");
		info("Danger!!!");
		info("A crazy admin set ignore_root=0 and some unsafe actions");
		info("You might lock out root!");
		info("If this is desirable, modify the source code");
		info("Setting ignore_root=1 and continuing");
		opts.ignore_root = 1;
	}

	/* Ignoring root is probably best but the admin can allow it */
	if (!strcmp(user_name, "root")) {
		if (opts.ignore_root) {
			info("Ignoring root user");
			return PAM_IGNORE;
		} else {
			/* This administrator is crazy */
			info("Danger!!! This is a connection attempt by root and ignore_root=0 is set! Hope for the best!");
		}
	}

	/* Calculate buffer size for getpwnam_r */
	bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
	if (bufsize == -1)
		bufsize = 16384; /* take a large guess */

	buf = xmalloc(bufsize);
	retval = getpwnam_r(user_name, &pwd, buf, bufsize, &pwd_result);
	if (pwd_result == NULL) {
		if (retval == 0) {
			error("getpwnam_r could not locate %s", user_name);
		} else {
			errno = retval;
			error("getpwnam_r: %m");
		}

		xfree(buf);
		return PAM_SESSION_ERR;
	}

	if (_load_cgroup_config() != SLURM_SUCCESS)
		return rc;

	/* Check if there are any steps on the node from any user. A failure here
	 * likely means failures everywhere so exit on failure or if no local jobs
	 * exist. */
	steps = stepd_available(NULL, opts.node_name);
	if (!steps) {
		error("Error obtaining local step information.");
		goto cleanup;
	}

	/* Check to see if this user has only one job on the node. If so, choose
	 * that job and adopt this process into it (unless configured not to) */
	user_jobs = _user_job_count(steps, pwd.pw_uid, &stepd);
	if (user_jobs == 0) {
		if (opts.action_no_jobs == CALLERID_ACTION_DENY) {
			send_user_msg(pamh,
				      "Access denied by "
				      PAM_MODULE_NAME
				      ": you have no active jobs on this node");
			rc = PAM_PERM_DENIED;
		} else {
			debug("uid %u owns no jobs but action_no_jobs=ignore",
			      pwd.pw_uid);
			rc = PAM_IGNORE;
		}
		goto cleanup;
	} else if (user_jobs == 1) {
		if (opts.single_job_skip_rpc) {
			info("Connection by user %s: user has only one job %u",
			     user_name,
			     stepd->jobid);
			slurmrc = _adopt_process(getpid(), stepd);
			/* If adoption into the only job fails, it is time to
			 * exit. Return code is based on the
			 * action_adopt_failure setting */
			if (slurmrc == SLURM_SUCCESS ||
			    (opts.action_adopt_failure ==
			     CALLERID_ACTION_ALLOW))
				rc = PAM_SUCCESS;
			else
				rc = PAM_PERM_DENIED;
			goto cleanup;
		}
	} else {
		debug("uid %u has %d jobs", pwd.pw_uid, user_jobs);
	}

	/* Single job check turned up nothing (or we skipped it). Make RPC call
	 * to slurmd at source IP. If it can tell us the job, the function calls
	 * _adopt_process */
	rc = _try_rpc(&pwd);
	if (rc == PAM_SUCCESS)
		goto cleanup;

	/* The source of the connection either didn't reply or couldn't
	 * determine the job ID at the source. Proceed to action_unknown */
	rc = _action_unknown(pamh, &pwd, steps);

cleanup:
	FREE_NULL_LIST(steps);
	xfree(buf);
	xfree(slurm_cgroup_conf);
	xfree(opts.node_name);
	return rc;
}
Exemplo n.º 19
0
int main(int argc, char *argv[])
{

   char config_buffer[1025];

   if ( argc != 2 ) /* argc should be two to ensure we have a filename */
   { 
     /* print the usage and exit */
     printf("No config file passed.\n\n\tUsage: %s /path/to/config/file.conf\n\n", argv[0] );
   }
   else
   {
   FILE *cfg = fopen(argv[1], "r");
   fread(config_buffer, 1024, 1, cfg);
   fclose(cfg);

   parse_config(config_buffer);
   int lfp = 0;

     /* Determine debug mode
     
     We don't always want to run in production mode, so we
     read the content of the debug config variable and act 
     on it accordingly.
     
     If we do not have a variable set, we assume production 
     mode */
     if ( strcmp(conf.debug,"true") == 0  )
     {
       debug = 1;
     }
     else
     {
       debug = 0;
     }

   // Set up log
   _log_init(debug?"/tmp/trustdb.log":"/var/log/garner/trustdb.log", debug?1:0);

   // Enable core dumps
   struct rlimit limit;
   if(!getrlimit(RLIMIT_CORE, &limit))
   {
      limit.rlim_cur = RLIM_INFINITY;
      setrlimit(RLIMIT_CORE, &limit);
   }

   start_time  = time(NULL);

   // DAEMONISE
   if(debug != 1)
   {
      int i=fork();
      if (i<0)
      {
         /* fork error */
         _log(CRITICAL, "fork() error.  Aborting.");
         exit(1);
      }
      if (i>0) exit(0); /* parent exits */
      /* child (daemon) continues */
      
      pid_t sid = setsid(); /* obtain a new process group */   
      if(sid < 0)
      {
         /* setsid error */
         _log(CRITICAL, "setsid() error.  Aborting.");
         exit(1);
      }

      for (i=getdtablesize(); i>=0; --i) close(i); /* close all descriptors */

      umask(022); // Created files will be rw for root, r for all others

      i = chdir("/var/run/");  
      if(i < 0)
      {
         /* chdir error */
         _log(CRITICAL, "chdir() error.  Aborting.");
         exit(1);
      }
      
      if((lfp = open("/var/run/trustdb.pid", O_RDWR|O_CREAT, 0640)) < 0)
      {
         _log(CRITICAL, "Unable to open pid file \"/var/run/trustdb.pid\".  Aborting.");
         exit(1); /* can not open */
      }
         
      if (lockf(lfp,F_TLOCK,0)<0)
      {
         _log(CRITICAL, "Failed to obtain lock.  Aborting.");
         exit(1); /* can not lock */
      }
      
      char str[128];
      sprintf(str, "%d\n", getpid());
      i = write(lfp, str, strlen(str)); /* record pid to lockfile */
      
      _log(GENERAL, "");
      sprintf(zs, "%s %s", NAME, BUILD);
      _log(GENERAL, zs);
      _log(GENERAL, "Running as daemon.");
   }
   else
   {
      _log(GENERAL, "");
      sprintf(zs, "%s %s", NAME, BUILD);
      _log(GENERAL, zs);
      _log(GENERAL, "Running in local mode.");
   }
   
   // Check core dumps
   if(prctl(PR_GET_DUMPABLE, 0, 0, 0, 0) != 1)
   {
      _log(MAJOR, "PR_GET_DUMPABLE not 1.");
   }
   else
   {
      _log(DEBUG, "PR_GET_DUMPABLE is 1.");
   }
   if(!getrlimit(RLIMIT_CORE, &limit))
   {
      if(limit.rlim_cur != RLIM_INFINITY)
      {
         _log(MAJOR, "RLIMIT_CORE not RLIM_INFINITY.");
      }
      else
      {
         _log(DEBUG, "RLIMIT_CORE is RLIM_INFINITY.");
      }
   }
   else
   {
      _log(MAJOR, "Unable to determine RLIMIT_CORE.");
   }

   run = true;
   interrupt = false;
   high_load = true;
   last_idle = 0;

   if(signal(SIGTERM, termination_handler) == SIG_IGN) signal(SIGTERM, SIG_IGN);
   if(signal(SIGINT,  termination_handler) == SIG_IGN) signal(SIGINT,  SIG_IGN);
   if(signal(SIGHUP,  termination_handler) == SIG_IGN) signal(SIGHUP,  SIG_IGN);
   if(!debug) signal(SIGCHLD,SIG_IGN); /* ignore child */
   if(!debug) signal(SIGTSTP,SIG_IGN); /* ignore tty signals */
   if(!debug) signal(SIGTTOU,SIG_IGN);
   if(!debug) signal(SIGTTIN,SIG_IGN);

   // Zero the stats
   {
      word i;
      for(i=0; i < MAXstats; i++) stats[i] = 0;
   }

   // Startup delay
   if(!debug)
   {
      struct sysinfo info;
      // If uptime query fails OR uptime is small, wait for system to stabilise.
      if(sysinfo(&info) || info.uptime < 64)
      {
         _log(GENERAL, "Startup delay ...");
         word i;
         for(i = 0; i < 64 && run; i++) sleep(1);
      }
   }

   perform();

   if(lfp) close(lfp);

   return 0;
   }
}