Example #1
0
int
main P2C(int, argc, string *, argv)
{
string input_name, full_input_name;
string output_name;
FILE *input_file, *output_file;

   kpse_set_progname (argv[0]);
   switch (argc) {
   case 1: fprintf(stderr, "otp2ocp: No file given\n");
         return EXIT_FAILURE;
   case 2: input_name = argv[1];
         output_name = concat(xbasename(argv[1]), ".ocp");
         break;
   case 3: input_name = argv[1];
         output_name = concat(xbasename(argv[2]), ".ocp");
         break;
   default: fprintf(stderr, "otp2ocp: Too many arguments\n");
         return EXIT_FAILURE;
   }
   full_input_name = kpse_find_file(input_name, kpse_otp_format, true);
   if (!full_input_name) {
     fprintf(stderr, "otp2ocp: %s not found\n", input_name);
     return EXIT_FAILURE;
   }
   input_file = xfopen(full_input_name, FOPEN_R_MODE);
   output_file = xfopen(output_name, FOPEN_WBIN_MODE);
   otp_read(input_file, output_file);

return EXIT_SUCCESS;
}
Example #2
0
int main(int argc, char *argv[])
{
	log_options_t opts = LOG_OPTS_STDERR_ONLY;
	int rc = 0;

	slurm_conf_init(NULL);
	log_init(xbasename(argv[0]), opts, SYSLOG_FACILITY_USER, NULL);
	parse_command_line(argc, argv);
	if (params.verbose) {
		opts.stderr_level += params.verbose;
		log_alter(opts, SYSLOG_FACILITY_USER, NULL);
	}

	while (1) {
		if ((!params.no_header) &&
		    (params.iterate || params.verbose || params.long_output))
			print_date();

		if (!params.clusters) {
			if (_get_info(false))
				rc = 1;
		} else if (_multi_cluster(params.clusters) != 0)
			rc = 1;
		if (params.iterate) {
			printf("\n");
			sleep(params.iterate);
		} else
			break;
	}

	exit(rc);
}
Example #3
0
int
fput_main(const struct cmd_fput_info* info)
{
    struct start_peer_info spi = {
        .cwd = info->cwd,
        .adb = info->adb,
        .transport = info->transport,
        .user = info->user,
    };

    struct cmd_xfer_stub_info xilocal = {
        .mode = "send",
        .filename = info->local,
        .xfer = info->xfer,
    };

    struct cmd_xfer_stub_info xiremote = {
        .mode = "recv",
        .filename = info->remote ?: ".",
        .desired_basename = (strcmp(info->local, "-") == 0
                             ? NULL
                             : xbasename(info->local)),
        .xfer = info->xfer,
    };

    return xfer_handle_command(&spi, &xilocal, &xiremote);
}
Example #4
0
/* Create an shm file and map it. */
void *
shm_create(struct shm *shm, size_t size)
{
	int	 saved_errno;
	char	*path;

        if (size == 0)
                fatalx("zero size");

	if (ppath(
	    shm->name, sizeof shm->name, "%s.XXXXXXXXXX", __progname) != 0)
		return (NULL);
	if ((path = shm_path(shm)) == NULL)
		return (NULL);
	if ((shm->fd = mkstemp(path)) == -1)
		return (NULL);
	strlcpy(shm->name, xbasename(path), sizeof shm->name);

	if (shm_expand(shm, size) != 0)
		goto error;

	shm->data = mmap(NULL, size, SHM_PROT, SHM_FLAGS, shm->fd, 0);
	if (shm->data == MAP_FAILED)
		goto error;
	madvise(shm->data, size, MADV_SEQUENTIAL);

	shm->size = size;
	return (shm->data);

error:
	saved_errno = errno;
	unlink(path);
	errno = saved_errno;
	return (NULL);
}
Example #5
0
File: upsrw.c Project: AlexLov/nut
int main(int argc, char **argv)
{
	int	i, port;
	const char	*prog = xbasename(argv[0]);
	char	*password = NULL, *username = NULL, *setvar = NULL;

	while ((i = getopt(argc, argv, "+hs:p:u:V")) != -1) {
		switch (i)
		{
		case 's':
			setvar = optarg;
			break;
		case 'p':
			password = optarg;
			break;
		case 'u':
			username = optarg;
			break;
		case 'V':
			printf("Network UPS Tools %s %s\n", prog, UPS_VERSION);
			exit(EXIT_SUCCESS);
		case 'h':
		default:
			usage(prog);
			exit(EXIT_SUCCESS);
		}
	}

	argc -= optind;
	argv += optind;

	if (argc < 1) {
		usage(prog);
		exit(EXIT_SUCCESS);
	}

	/* be a good little client that cleans up after itself */
	atexit(clean_exit);

	if (upscli_splitname(argv[0], &upsname, &hostname, &port) != 0) {
		fatalx(EXIT_FAILURE, "Error: invalid UPS definition.  Required format: upsname[@hostname[:port]]");
	}

	ups = xcalloc(1, sizeof(*ups));

	if (upscli_connect(ups, hostname, port, 0) < 0) {
		fatalx(EXIT_FAILURE, "Error: %s", upscli_strerror(ups));
	}

	if (setvar) {
		/* setting a variable */
		do_setvar(setvar, username, password);
	} else {
		/* if not, get the list of supported read/write variables */
		print_rwlist();
	}

	exit(EXIT_SUCCESS);
}
Example #6
0
int main(int argc, char **argv)
{
	log_options_t opts = LOG_OPTS_STDERR_ONLY;
	update_block_msg_t msg;
	ListIterator itr = NULL;
	char *block_name = NULL;
	int rc = SLURM_SUCCESS;

	log_init(xbasename(argv[0]), opts, SYSLOG_FACILITY_DAEMON, NULL);
	parse_command_line(argc, argv);

	memset(&msg, 0, sizeof(update_block_msg_t));
	if (!all_blocks && (!block_list || !list_count(block_list))) {
		error("you need at least one block to remove.");
		exit(1);
	}

	if (all_blocks) {
		int i=0;
		block_info_msg_t *block_ptr = NULL;
		_get_new_info_block(&block_ptr);
		if (!block_ptr) {
			error("there was no block_ptr filled in.");
			return 1;
		}
		if (block_list)
			list_flush(block_list);
		else
			block_list = list_create(slurm_destroy_char);

		for (i=0; i<block_ptr->record_count; i++) {
			list_append(block_list,
				    xstrdup(block_ptr->
					    block_array[i].bg_block_id));
		}
	}

	itr = list_iterator_create(block_list);
	while ((block_name = list_next(itr))) {
		if (remove_blocks)
			msg.state = BG_BLOCK_NAV;
		else
			msg.state = BG_BLOCK_FREE;
		msg.bg_block_id = block_name;
		rc = slurm_update_block(&msg);
		if (rc != SLURM_SUCCESS)
			error("Error trying to free block %s: %s",
			      block_name, slurm_strerror(rc));
	}
	list_iterator_destroy(itr);
	if (wait_full)
		_check_status();

	FREE_NULL_LIST(block_list);
	info("done");
	return 0;
}
Example #7
0
static void rmfiles (char *prefix)
{
#ifdef _WIN32
    /* Win32 doesn't have POSIX dirent functions.  */
    WIN32_FIND_DATA ffd;
    HANDLE hnd;
    int go_on;
    string temp = concat (prefix, "*");
    string directory = xdirname (prefix);

    pushd (directory);
    hnd = FindFirstFile(temp, &ffd);
    go_on = (hnd != INVALID_HANDLE_VALUE);
    while (go_on) {
        /* FIXME: can this remove read-only files also, like rm -f does?  */
        DeleteFile(ffd.cFileName);
        go_on = (FindNextFile(hnd, &ffd) == TRUE);
    }
    FindClose(hnd);
    free(temp);
    popd ();
#else  /* not _WIN32 */
    DIR *dp;
    struct dirent *de;
    int temp_len = strlen (prefix);
    string directory = "./";
    const_string base = xbasename (prefix);

    /* Copy the directory part of PREFIX with the trailing slash, if any.  */
    if (base != prefix)
    {
        directory = (string) xmalloc (base - prefix + 1);
        directory[0] = '\0';
        strncat (directory, prefix, base - prefix);
    }

    /* Find matching files and delete them.  */
    if ((dp = opendir (directory)) != 0) {
        while ((de = readdir (dp)) != 0)
        {
            string found = concat (directory, de->d_name);

            if (FILESTRNCASEEQ (found, prefix, temp_len))
                /* On POSIX-compliant systems, including DJGPP, this will also
                   remove read-only files and empty directories, like rm -f does.  */
                if (remove (found))
                    perror (found);
            free (found);
        }
    }
#endif /* not _WIN32 */
}
Example #8
0
static void
set_default_pdf_filename(void)
{
  const char *dvi_base;

  dvi_base = xbasename(dvi_filename);
  if (mp_mode &&
      strlen(dvi_base) > 4 &&
      FILESTRCASEEQ(".mps", dvi_base + strlen(dvi_base) - 4)) {
    pdf_filename = NEW(strlen(dvi_base)+1, char);
    strncpy(pdf_filename, dvi_base, strlen(dvi_base) - 4);
    pdf_filename[strlen(dvi_base)-4] = '\0';
  } else if (strlen(dvi_base) > 4 &&
Example #9
0
static void
copydir( char *from, char *to, mode_t mode, char *group, char *owner,
         int dotimes, uid_t uid, gid_t gid)
{
  int i;
  DIR *dir;
  struct dirent *ep;
  struct stat sb;
  char *base, *destdir, *direntry, *destentry;

  base = xbasename(from);

  /* create destination directory */
  destdir = xmalloc((unsigned int)(strlen(to) + 1 + strlen(base) + 1));
  sprintf(destdir, "%s%s%s", to, _DIRECTORY_SEPARATOR, base);
  if (mkdirs(destdir, mode) != 0) {
    fail("cannot make directory %s\n", destdir);
    free(destdir);
    return;
  }

  if (!(dir = opendir(from))) {
    fail("cannot open directory %s\n", from);
    free(destdir);
    return;
  }

  direntry = xmalloc((unsigned int)PATH_MAX);
  destentry = xmalloc((unsigned int)PATH_MAX);

  while ((ep = readdir(dir)))
  {
    if (strcmp(ep->d_name, ".") == 0 || strcmp(ep->d_name, "..") == 0)
      continue;

    sprintf(direntry, "%s/%s", from, ep->d_name);
    sprintf(destentry, "%s%s%s", destdir, _DIRECTORY_SEPARATOR, ep->d_name);

    if (stat(direntry, &sb) == 0 && S_ISDIR(sb.st_mode))
      copydir( direntry, destdir, mode, group, owner, dotimes, uid, gid );
    else
      copyfile( direntry, destentry, mode, group, owner, dotimes, uid, gid );
  }

  free(destdir);
  free(direntry);
  free(destentry);
  closedir(dir);
}
Example #10
0
/*
 * Augment a buffer name with a number, if necessary
 *
 * If more than one file of the same basename() is open,
 * the additional buffers are named "file<2>", "file<3>", and
 * so forth.  This function adjusts a buffer name to
 * include the number, if necessary.
 */
int
augbname(char *bn, const char *fn, size_t bs)
{
	int	 count;
	size_t	 remain, len;

	if ((len = xbasename(bn, fn, bs)) >= bs)
		return (FALSE);

	remain = bs - len;
	for (count = 2; bfind(bn, FALSE) != NULL; count++)
		snprintf(bn + len, remain, "<%d>", count);

	return (TRUE);
}
Example #11
0
static void
do_kanji (void) {
    const char **p;

    printf("\nAssuming CP %s 932\n", is_cp932_system ? "is" : "is not");

    for (p = ktab; *p; p++) {
        char *q = to_kanji(*p);
        char *r = xdirname(q);

        printf("%s -> %s + %s\n", *p, from_kanji(r), *p + (xbasename(q)-q));

        free (r);
        free (q);
    }
}
Example #12
0
void
kpathsea_db_insert (kpathsea kpse, const_string passed_fname)
{
  /* We might not have found ls-R, or even had occasion to look for it
     yet, so do nothing if we have no hash table.  */
  if (kpse->db.buckets) {
    const_string dir_part;
    string fname = xstrdup (passed_fname);
    string baseptr = fname + (xbasename (fname) - fname);
    const_string file_part = xstrdup (baseptr);

    *baseptr = '\0';  /* Chop off the filename.  */
    dir_part = fname; /* That leaves the dir, with the trailing /.  */

    /* Note that we do not assuse that these names have been normalized. */
    hash_insert (&(kpse->db), file_part, dir_part);
  }
}
Example #13
0
File: squeue.c Project: VURM/slurm
int
main (int argc, char *argv[])
{
	log_options_t opts = LOG_OPTS_STDERR_ONLY ;
	int error_code = SLURM_SUCCESS;

	log_init(xbasename(argv[0]), opts, SYSLOG_FACILITY_USER, NULL);
	parse_command_line( argc, argv );
	if (params.verbose) {
		opts.stderr_level += params.verbose;
		log_alter(opts, SYSLOG_FACILITY_USER, NULL);
	}
	max_line_size = _get_window_width( );

	if (params.clusters)
		working_cluster_rec = list_peek(params.clusters);

	while (1) {
		if ((!params.no_header) &&
		    (params.iterate || params.verbose || params.long_list))
			_print_date ();

		if (!params.clusters) {
			if (_get_info(false))
				error_code = 1;
		} else if (_multi_cluster(params.clusters) != 0)
			error_code = 1;

		if ( params.iterate ) {
			printf( "\n");
			sleep( params.iterate );
		}
		else
			break;
	}

	if ( error_code != SLURM_SUCCESS )
		exit (error_code);
	else
		exit (0);
}
Example #14
0
int
main (int argc, char *argv[])
{
	log_options_t log_opts = LOG_OPTS_STDERR_ONLY ;
	int rc = 0;

	slurm_conf_init(NULL);
	log_init (xbasename(argv[0]), log_opts, SYSLOG_FACILITY_DAEMON, NULL);
	initialize_and_process_args(argc, argv);
	if (opt.verbose) {
		log_opts.stderr_level += opt.verbose;
		log_alter (log_opts, SYSLOG_FACILITY_DAEMON, NULL);
	}

	if (opt.clusters)
		rc = _multi_cluster(opt.clusters);
	else
		rc = _proc_cluster();

	exit(rc);
}
Example #15
0
int srun(int ac, char **av)
{
	int debug_level;
	log_options_t logopt = LOG_OPTS_STDERR_ONLY;
	bool got_alloc = false;
	List srun_job_list = NULL;

	slurm_conf_init(NULL);
	debug_level = _slurm_debug_env_val();
	logopt.stderr_level += debug_level;
	log_init(xbasename(av[0]), logopt, 0, NULL);
	_set_exit_code();

	if (slurm_select_init(1) != SLURM_SUCCESS )
		fatal( "failed to initialize node selection plugin" );

	if (switch_init(0) != SLURM_SUCCESS )
		fatal("failed to initialize switch plugins");

	_setup_env_working_cluster();

	init_srun(ac, av, &logopt, debug_level, 1);
	if (opt_list) {
		if (!_enable_pack_steps())
			fatal("Job steps that span multiple components of a heterogeneous job are not currently supported");
		create_srun_job((void **) &srun_job_list, &got_alloc, 0, 1);
	} else
		create_srun_job((void **) &job, &got_alloc, 0, 1);

	_setup_job_env(job, srun_job_list, got_alloc);
	_set_node_alias();
	_launch_app(job, srun_job_list, got_alloc);

	if ((global_rc & 0xff) == SIG_OOM)
		global_rc = 1;	/* Exit code 1 */

	return (int)global_rc;
}
Example #16
0
int main(int argc, char **argv)
{
    const char **p;
    kpathsea kpse = kpathsea_new();

    kpathsea_set_program_name (kpse, argv[0], NULL);

    printf("\n%s: name -> xdirname(name) + xbasename(name)\n\n",
           kpse->invocation_short_name);

    for (p = tab; *p; p++) {
        char *q = xdirname(*p);

        printf("%s -> %s + %s\n", *p, q, xbasename(*p));
        free (q);
    }

#if defined (WIN32)
    kanji_test();
#endif

    return 0;
}
Example #17
0
/* handle sending the signal */
static void stop_driver(const ups_t *ups)
{
	char	pidfn[SMALLBUF];
	int	ret;
	struct stat	fs;

	upsdebugx(1, "Stopping UPS: %s", ups->upsname);

	snprintf(pidfn, sizeof(pidfn), "%s/%s-%s.pid", altpidpath(),
		ups->driver, ups->upsname);
	ret = stat(pidfn, &fs);

	if ((ret != 0) && (ups->port != NULL)) {
		snprintf(pidfn, sizeof(pidfn), "%s/%s-%s.pid", altpidpath(),
			ups->driver, xbasename(ups->port));
		ret = stat(pidfn, &fs);
	}

	if (ret != 0) {
		upslog_with_errno(LOG_ERR, "Can't open %s", pidfn);
		exec_error++;
		return;
	}

	upsdebugx(2, "Sending signal to %s", pidfn);

	if (testmode)
		return;

	ret = sendsignalfn(pidfn, SIGTERM);

	if (ret < 0) {
		upslog_with_errno(LOG_ERR, "Stopping %s failed", pidfn);
		exec_error++;
		return;
	}
}
Example #18
0
int main(int argc, char **argv)
{
	const char	*prog = xbasename(argv[0]);

	verbose = 1;		/* TODO: remove when done testing */

	/* normally we don't have stderr, so get this going to syslog early */
	open_syslog(prog);
	syslogbit_set();

	upsname = getenv("UPSNAME");
	notify_type = getenv("NOTIFYTYPE");

	if ((!upsname) || (!notify_type)) {
		printf("Error: UPSNAME and NOTIFYTYPE must be set.\n");
		printf("This program should only be run from upsmon.\n");
		exit(EXIT_FAILURE);
	}

	/* see if this matches anything in the config file */
	checkconf();

	exit(EXIT_SUCCESS);
}
Example #19
0
int main (int argc, char **argv)
{
	log_options_t logopt = LOG_OPTS_STDERR_ONLY;
	slurm_ctl_conf_t *conf = NULL;
	shares_response_msg_t resp;

	log_init(xbasename(argv[0]), logopt, 0, NULL);
	xfree(slurmctld_conf.priority_type);
	//logopt.stderr_level += 5;
	logopt.prefix_level = 1;
	log_alter(logopt, 0, NULL);
	print_fields_have_header = 0;
	print_fields_parsable_print = PRINT_FIELDS_PARSABLE_ENDING;

	conf = slurm_conf_lock();
	/* force priority type to be multifactor */
	xfree(conf->priority_type);
	conf->priority_type = xstrdup("priority/multifactor");
	conf->priority_flags = PRIORITY_FLAGS_FAIR_TREE;
	/* force accounting type to be slurmdbd (It doesn't really talk
	 * to any database, but needs this to work with fairshare
	 * calculation). */
	xfree(conf->accounting_storage_type);
	conf->accounting_storage_type = xstrdup("accounting_storage/slurmdbd");
	/* set up a known environment to test against.  Since we are
	 * only concerned about the fairshare we won't look at the other
	 * factors here. */
	conf->priority_decay_hl = 1;
	conf->priority_favor_small = 0;
	conf->priority_max_age = conf->priority_decay_hl;
	conf->priority_reset_period = 0;
	conf->priority_weight_age = 0;
	conf->priority_weight_fs = 10000;
	conf->priority_weight_js = 0;
	conf->priority_weight_part = 0;
	conf->priority_weight_qos = 0;
	slurm_conf_unlock();

	/* we don't want to do any decay here so make the save state
	 * to /dev/null */
	xfree(slurmctld_conf.state_save_location);
	slurmctld_conf.state_save_location = "/dev/null";
	/* now set up the association tree */
	_setup_assoc_list();
	/* now set up the job list */
	job_list = list_create(_list_delete_job);

	/* now init the priorities of the associations */
	if (slurm_priority_init() != SLURM_SUCCESS)
		fatal("failed to initialize priority plugin");
	/* on some systems that don't have multiple cores we need to
	 * sleep to make sure the thread gets started. */
	sleep(1);
	memset(&resp, 0, sizeof(shares_response_msg_t));
	resp.assoc_shares_list = assoc_mgr_get_shares(NULL, 0, NULL, NULL);
	process(&resp, 0);

	/* free memory */
	if (slurm_priority_fini() != SLURM_SUCCESS)
		fatal("failed to finalize priority plugin");
	if (job_list)
		list_destroy(job_list);
	if (resp.assoc_shares_list)
		list_destroy(resp.assoc_shares_list);
	if (assoc_mgr_assoc_list)
		list_destroy(assoc_mgr_assoc_list);
	if (assoc_mgr_qos_list)
		list_destroy(assoc_mgr_qos_list);
	return 0;
}
Example #20
0
File: salloc.c Project: adk9/slurm
int main(int argc, char *argv[])
{
	log_options_t logopt = LOG_OPTS_STDERR_ONLY;
	job_desc_msg_t desc;
	resource_allocation_response_msg_t *alloc;
	time_t before, after;
	allocation_msg_thread_t *msg_thr;
	char **env = NULL;
	int status = 0;
	int retries = 0;
	pid_t pid  = getpid();
	pid_t tpgid = 0;
	pid_t rc_pid = 0;
	int i, rc = 0;
	static char *msg = "Slurm job queue full, sleeping and retrying.";
	slurm_allocation_callbacks_t callbacks;

	log_init(xbasename(argv[0]), logopt, 0, NULL);
	_set_exit_code();

	if (spank_init_allocator() < 0) {
		error("Failed to initialize plugin stack");
		exit(error_exit);
	}

	/* Be sure to call spank_fini when salloc exits
	 */
	if (atexit((void (*) (void)) spank_fini) < 0)
		error("Failed to register atexit handler for plugins: %m");


	if (initialize_and_process_args(argc, argv) < 0) {
		error("salloc parameter parsing");
		exit(error_exit);
	}
	/* reinit log with new verbosity (if changed by command line) */
	if (opt.verbose || opt.quiet) {
		logopt.stderr_level += opt.verbose;
		logopt.stderr_level -= opt.quiet;
		logopt.prefix_level = 1;
		log_alter(logopt, 0, NULL);
	}

	if (spank_init_post_opt() < 0) {
		error("Plugin stack post-option processing failed");
		exit(error_exit);
	}

	_set_spank_env();
	_set_submit_dir_env();
	if (opt.cwd && chdir(opt.cwd)) {
		error("chdir(%s): %m", opt.cwd);
		exit(error_exit);
	}

	if (opt.get_user_env_time >= 0) {
		char *user = uid_to_string(opt.uid);
		if (strcmp(user, "nobody") == 0) {
			error("Invalid user id %u: %m", (uint32_t)opt.uid);
			exit(error_exit);
		}
		env = env_array_user_default(user,
					     opt.get_user_env_time,
					     opt.get_user_env_mode);
		xfree(user);
		if (env == NULL)
			exit(error_exit);    /* error already logged */
		_set_rlimits(env);
	}

	/*
	 * Job control for interactive salloc sessions: only if ...
	 *
	 * a) input is from a terminal (stdin has valid termios attributes),
	 * b) controlling terminal exists (non-negative tpgid),
	 * c) salloc is not run in allocation-only (--no-shell) mode,
	 * NOTE: d and e below are configuration dependent
	 * d) salloc runs in its own process group (true in interactive
	 *    shells that support job control),
	 * e) salloc has been configured at compile-time to support background
	 *    execution and is not currently in the background process group.
	 */
	if (tcgetattr(STDIN_FILENO, &saved_tty_attributes) < 0) {
		/*
		 * Test existence of controlling terminal (tpgid > 0)
		 * after first making sure stdin is not redirected.
		 */
	} else if ((tpgid = tcgetpgrp(STDIN_FILENO)) < 0) {
		if (!opt.no_shell) {
			error("no controlling terminal: please set --no-shell");
			exit(error_exit);
		}
#ifdef SALLOC_RUN_FOREGROUND
	} else if ((!opt.no_shell) && (pid == getpgrp())) {
		if (tpgid == pid)
			is_interactive = true;
		while (tcgetpgrp(STDIN_FILENO) != pid) {
			if (!is_interactive) {
				error("Waiting for program to be placed in "
				      "the foreground");
				is_interactive = true;
			}
			killpg(pid, SIGTTIN);
		}
	}
#else
	} else if ((!opt.no_shell) && (getpgrp() == tcgetpgrp(STDIN_FILENO))) {
Example #21
0
static int _parse_comp_file(
	char *file, step_update_request_msg_t *step_msg)
{
	int i;
	FILE *fd = fopen(file, "r");
	char line[BUFFER_SIZE];
	char *fptr;
	int version;
	char *update[MAX_RECORD_FIELDS+1];    /* End list with null entry and,
						 possibly, more data than we
						 expected */

	enum {	UPDATE_STEP_VERSION,
		UPDATE_STEP_EXTRA,
		UPDATE_STEP_INBLOCKS,
		UPDATE_STEP_OUTBLOCKS,
		UPDATE_STEP_EXITCODE,
		UPDATE_STEP_CPU_ALLOC,
		UPDATE_STEP_START,
		UPDATE_STEP_END,
		UPDATE_STEP_USER_SEC,
		UPDATE_STEP_SYS_SEC,
		UPDATE_STEP_MAX_RSS,
		UPDATE_STEP_UID,
		UPDATE_STEP_STEPNAME,
		UPDATE_STEP_VER1_LENGTH
	};

	if (fd == NULL) {
		perror(file);
		return SLURM_ERROR;
	}

	if (!fgets(line, BUFFER_SIZE, fd)) {
		fprintf(stderr, "Empty step update completion file\n");
		return SLURM_ERROR;
	}

	fptr = line;	/* break the record into NULL-terminated strings */
	for (i = 0; i < MAX_RECORD_FIELDS; i++) {
		update[i] = fptr;
		fptr = strstr(fptr, " ");
		if (fptr == NULL) {
			fptr = strstr(update[i], "\n");
			if (fptr)
				*fptr = 0;
			break;
		} else
			*fptr++ = 0;
	}

	if (i < MAX_RECORD_FIELDS)
		i++;
	update[i] = 0;

	version = atoi(update[UPDATE_STEP_VERSION]);
	switch (version) {
	case 1:
		if (i != UPDATE_STEP_VER1_LENGTH) {
			fprintf(stderr,
				"Bad step update completion file length\n");
			return SLURM_ERROR;
		}
		step_msg->jobacct = jobacctinfo_create(NULL);
		step_msg->exit_code = atoi(update[UPDATE_STEP_EXITCODE]);
		step_msg->start_time = atoi(update[UPDATE_STEP_START]);
		step_msg->end_time = atoi(update[UPDATE_STEP_END]);
		step_msg->jobacct->user_cpu_sec =
			atoi(update[UPDATE_STEP_USER_SEC]);
		step_msg->jobacct->sys_cpu_sec =
			atoi(update[UPDATE_STEP_SYS_SEC]);
		step_msg->jobacct->min_cpu =
			step_msg->jobacct->user_cpu_sec
			+ step_msg->jobacct->sys_cpu_sec;
		step_msg->jobacct->max_rss = atoi(update[UPDATE_STEP_MAX_RSS]);
		step_msg->name =
			xstrdup(xbasename(update[UPDATE_STEP_STEPNAME]));
		break;
	default:
		fprintf(stderr, "Unsupported step update "
			"completion file version: %d\n",
			version);
		return SLURM_ERROR;
		break;
	}


	return SLURM_SUCCESS;
}
Example #22
0
int main(int argc, char **argv)
{
  program_name = argv[0];
  static char stderr_buf[BUFSIZ];
  setbuf(stderr, stderr_buf);
  assert(NCOMMANDS <= MAX_COMMANDS);
  string Pargs, Largs, Fargs;
  int vflag = 0;
  int Vflag = 0;
  int zflag = 0;
  int iflag = 0;
  int Xflag = 0;
  int oflag = 0;
  int safer_flag = 1;
  int opt;
  const char *command_prefix = getenv("GROFF_COMMAND_PREFIX");
  if (!command_prefix)
    command_prefix = PROG_PREFIX;
  commands[TROFF_INDEX].set_name(command_prefix, "troff");
  static const struct option long_options[] = {
    { "help", no_argument, 0, 'h' },
    { "version", no_argument, 0, 'v' },
    { NULL, 0, 0, 0 }
  };
  while ((opt = getopt_long(argc, argv,
			    "abcCd:eEf:F:gGhiI:lL:m:M:n:No:pP:r:RsStT:UvVw:W:XzZ",
			    long_options, NULL))
	 != EOF) {
    char buf[3];
    buf[0] = '-';
    buf[1] = opt;
    buf[2] = '\0';
    switch (opt) {
    case 'i':
      iflag = 1;
      break;
    case 'I':
      commands[SOELIM_INDEX].set_name(command_prefix, "soelim");
      commands[SOELIM_INDEX].append_arg(buf, optarg);
      // .psbb may need to search for files
      commands[TROFF_INDEX].append_arg(buf, optarg);
      // \X'ps:import' may need to search for files
      Pargs += buf;
      Pargs += optarg;
      Pargs += '\0';
      break;
    case 't':
      commands[TBL_INDEX].set_name(command_prefix, "tbl");
      break;
    case 'p':
      commands[PIC_INDEX].set_name(command_prefix, "pic");
      break;
    case 'g':
      commands[GRN_INDEX].set_name(command_prefix, "grn");
      break;
    case 'G':
      commands[GRAP_INDEX].set_name(command_prefix, "grap");
      break;
    case 'e':
      commands[EQN_INDEX].set_name(command_prefix, "eqn");
      break;
    case 's':
      commands[SOELIM_INDEX].set_name(command_prefix, "soelim");
      break;
    case 'R':
      commands[REFER_INDEX].set_name(command_prefix, "refer");
      break;
    case 'z':
    case 'a':
      commands[TROFF_INDEX].append_arg(buf);
      // fall through
    case 'Z':
      zflag++;
      break;
    case 'l':
      lflag++;
      break;
    case 'V':
      Vflag++;
      break;
    case 'v':
      vflag = 1;
      {
	printf("GNU groff version %s\n", Version_string);
	printf("Copyright (C) 2004 Free Software Foundation, Inc.\n"
	       "GNU groff comes with ABSOLUTELY NO WARRANTY.\n"
	       "You may redistribute copies of groff and its subprograms\n"
	       "under the terms of the GNU General Public License.\n"
	       "For more information about these matters, see the file named COPYING.\n");
	printf("\ncalled subprograms:\n\n");
        fflush(stdout);
      }
      commands[POST_INDEX].append_arg(buf);
      // fall through
    case 'C':
      commands[SOELIM_INDEX].append_arg(buf);
      commands[REFER_INDEX].append_arg(buf);
      commands[PIC_INDEX].append_arg(buf);
      commands[GRAP_INDEX].append_arg(buf);
      commands[TBL_INDEX].append_arg(buf);
      commands[GRN_INDEX].append_arg(buf);
      commands[EQN_INDEX].append_arg(buf);
      commands[TROFF_INDEX].append_arg(buf);
      break;
    case 'N':
      commands[EQN_INDEX].append_arg(buf);
      break;
    case 'h':
      help();
      break;
    case 'E':
    case 'b':
      commands[TROFF_INDEX].append_arg(buf);
      break;
    case 'c':
      commands[TROFF_INDEX].append_arg(buf);
      break;
    case 'S':
      safer_flag = 1;
      break;
    case 'U':
      safer_flag = 0;
      break;
    case 'T':
      if (strcmp(optarg, "html") == 0) {
	// force soelim to aid the html preprocessor
	commands[SOELIM_INDEX].set_name(command_prefix, "soelim");
      }
      if (strcmp(optarg, "Xps") == 0) {
	warning("-TXps option is obsolete: use -X -Tps instead");
	device = "ps";
	Xflag++;
      }
      else
	device = optarg;
      break;
    case 'F':
      font::command_line_font_dir(optarg);
      if (Fargs.length() > 0) {
	Fargs += PATH_SEP_CHAR;
	Fargs += optarg;
      }
      else
	Fargs = optarg;
      break;
    case 'o':
      oflag = 1;
    case 'f':
    case 'm':
    case 'r':
    case 'd':
    case 'n':
    case 'w':
    case 'W':
      commands[TROFF_INDEX].append_arg(buf, optarg);
      break;
    case 'M':
      commands[EQN_INDEX].append_arg(buf, optarg);
      commands[GRAP_INDEX].append_arg(buf, optarg);
      commands[GRN_INDEX].append_arg(buf, optarg);
      commands[TROFF_INDEX].append_arg(buf, optarg);
      break;
    case 'P':
      Pargs += optarg;
      Pargs += '\0';
      break;
    case 'L':
      append_arg_to_string(optarg, Largs);
      break;
    case 'X':
      Xflag++;
      break;
    case '?':
      usage(stderr);
      exit(1);
      break;
    default:
      assert(0);
      break;
    }
  }
  if (safer_flag)
    commands[PIC_INDEX].append_arg("-S");
  else
    commands[TROFF_INDEX].insert_arg("-U");
  font::set_unknown_desc_command_handler(handle_unknown_desc_command);
  if (!font::load_desc())
    fatal("invalid device `%1'", device);
  if (!postdriver)
    fatal("no `postpro' command in DESC file for device `%1'", device);
  if (predriver && !zflag) {
    commands[TROFF_INDEX].insert_arg(commands[TROFF_INDEX].get_name());
    commands[TROFF_INDEX].set_name(predriver);
    // pass the device arguments to the predrivers as well
    commands[TROFF_INDEX].insert_args(Pargs);
    if (vflag)
      commands[TROFF_INDEX].insert_arg("-v");
  }
  const char *real_driver = 0;
  if (Xflag) {
    real_driver = postdriver;
    postdriver = (char *)GXDITVIEW;
    commands[TROFF_INDEX].append_arg("-r" XREG "=", "1");
  }
  if (postdriver)
    commands[POST_INDEX].set_name(postdriver);
  int gxditview_flag = postdriver && strcmp(xbasename(postdriver), GXDITVIEW) == 0;
  if (gxditview_flag && argc - optind == 1) {
    commands[POST_INDEX].append_arg("-title");
    commands[POST_INDEX].append_arg(argv[optind]);
    commands[POST_INDEX].append_arg("-xrm");
    commands[POST_INDEX].append_arg("*iconName:", argv[optind]);
    string filename_string("|");
    append_arg_to_string(argv[0], filename_string);
    append_arg_to_string("-Z", filename_string);
    for (int i = 1; i < argc; i++)
      append_arg_to_string(argv[i], filename_string);
    filename_string += '\0';
    commands[POST_INDEX].append_arg("-filename");
    commands[POST_INDEX].append_arg(filename_string.contents());
  }
  if (gxditview_flag && Xflag) {
    string print_string(real_driver);
    if (spooler) {
      print_string += " | ";
      print_string += spooler;
      print_string += Largs;
    }
    print_string += '\0';
    commands[POST_INDEX].append_arg("-printCommand");
    commands[POST_INDEX].append_arg(print_string.contents());
  }
  const char *p = Pargs.contents();
  const char *end = p + Pargs.length();
  while (p < end) {
    commands[POST_INDEX].append_arg(p);
    p = strchr(p, '\0') + 1;
  }
  if (gxditview_flag)
    commands[POST_INDEX].append_arg("-");
  if (lflag && !vflag && !Xflag && spooler) {
    commands[SPOOL_INDEX].set_name(BSHELL);
    commands[SPOOL_INDEX].append_arg(BSHELL_DASH_C);
    Largs += '\0';
    Largs = spooler + Largs;
    commands[SPOOL_INDEX].append_arg(Largs.contents());
  }
  if (zflag) {
    commands[POST_INDEX].set_name(0);
    commands[SPOOL_INDEX].set_name(0);
  }
  commands[TROFF_INDEX].append_arg("-T", device);
  // html renders equations as images via ps
  if (strcmp(device, "html") == 0) {
    if (oflag)
      fatal("`-o' option is invalid with device `html'");
    commands[EQN_INDEX].append_arg("-Tps:html");
  }
  else
    commands[EQN_INDEX].append_arg("-T", device);

  commands[GRN_INDEX].append_arg("-T", device);

  int first_index;
  for (first_index = 0; first_index < TROFF_INDEX; first_index++)
    if (commands[first_index].get_name() != 0)
      break;
  if (optind < argc) {
    if (argv[optind][0] == '-' && argv[optind][1] != '\0')
      commands[first_index].append_arg("--");
    for (int i = optind; i < argc; i++)
      commands[first_index].append_arg(argv[i]);
    if (iflag)
      commands[first_index].append_arg("-");
  }
  if (Fargs.length() > 0) {
    string e = "GROFF_FONT_PATH";
    e += '=';
    e += Fargs;
    char *fontpath = getenv("GROFF_FONT_PATH");
    if (fontpath && *fontpath) {
      e += PATH_SEP_CHAR;
      e += fontpath;
    }
    e += '\0';
    if (putenv(strsave(e.contents())))
      fatal("putenv failed");
  }
  {
    // we save the original path in GROFF_PATH__ and put it into the
    // environment -- troff will pick it up later.
    char *path = getenv("PATH");
    string e = "GROFF_PATH__";
    e += '=';
    if (path && *path)
      e += path;
    e += '\0';
    if (putenv(strsave(e.contents())))
      fatal("putenv failed");
    char *binpath = getenv("GROFF_BIN_PATH");
    string f = "PATH";
    f += '=';
    if (binpath && *binpath)
      f += binpath;
    else
      f += BINPATH;
    if (path && *path) {
      f += PATH_SEP_CHAR;
      f += path;
    }
    f += '\0';
    if (putenv(strsave(f.contents())))
      fatal("putenv failed");
  }
  if (Vflag)
    print_commands(Vflag == 1 ? stdout : stderr);
  if (Vflag == 1)
    exit(0);
  return run_commands(vflag);
}
Example #23
0
/*
 * Initialize log with
 * prog = program name to tag error messages with
 * opt  = log_options_t specifying max log levels for syslog, stderr, and file
 * fac  = log facility for syslog (unused if syslog level == LOG_QUIET)
 * logfile =
 *        logfile name if logfile level > LOG_QUIET
 */
static int
_log_init(char *prog, log_options_t opt, log_facility_t fac, char *logfile )
{
	int rc = 0;

	if (!log)  {
		log = (log_t *)xmalloc(sizeof(log_t));
		log->logfp = NULL;
		log->argv0 = NULL;
		log->buf   = NULL;
		log->fbuf  = NULL;
		log->fpfx  = NULL;
		atfork_install_handlers();
	}

	if (prog) {
		if (log->argv0)
			xfree(log->argv0);
		log->argv0 = xstrdup(xbasename(prog));
	} else if (!log->argv0) {
		const char *short_name = strrchr(default_name, '/');
		if (short_name)
			short_name++;
		else
			short_name = default_name;
		log->argv0 = xstrdup(short_name);
	}

	if (!log->fpfx)
		log->fpfx = xstrdup("");

	log->opt = opt;

	if (log->buf) {
		cbuf_destroy(log->buf);
		log->buf = NULL;
	}
	if (log->fbuf) {
		cbuf_destroy(log->fbuf);
		log->fbuf = NULL;
	}

	if (log->opt.buffered) {
		log->buf  = cbuf_create(128, 8192);
		log->fbuf = cbuf_create(128, 8192);
	}

	if (log->opt.syslog_level > LOG_LEVEL_QUIET)
		log->facility = fac;

	if (logfile && (log->opt.logfile_level > LOG_LEVEL_QUIET)) {
		FILE *fp;

		fp = safeopen(logfile, "a", SAFEOPEN_LINK_OK);

		if (!fp) {
			char *errmsg = NULL;
			xslurm_strerrorcat(errmsg);
			fprintf(stderr,
				"%s: log_init(): Unable to open logfile"
			        "`%s': %s\n", prog, logfile, errmsg);
			xfree(errmsg);
			rc = errno;
			goto out;
		}

		if (log->logfp)
			fclose(log->logfp); /* Ignore errors */

		log->logfp = fp;
	}

	if (log->logfp) {
		int fd;
		if ((fd = fileno(log->logfp)) < 0)
			log->logfp = NULL;
		else
			fd_set_close_on_exec(fd);
	}

	log->initialized = 1;
 out:
	return rc;
}
Example #24
0
int
main(int argc, char **argv)
{
	int debug_level, sig, srun_fd;
	struct sigaction sa;
	log_options_t logopt = LOG_OPTS_STDERR_ONLY;
	struct sockaddr_un ca;
	unsigned int ca_len = sizeof(ca);

	atexit(remove_listen_socket);

	/* copied from srun */
	debug_level = _slurm_debug_env_val();
	logopt.stderr_level += debug_level;
	log_init(xbasename(argv[0]), logopt, 0, NULL);

	if (init_srun_argv(argc, argv)) {
		fatal("failed to initialize arguments for running srun");
	}

	if ((cr_id = cr_init()) < 0) {
		fatal("failed to initialize libcr: %s", cr_strerror(errno));
	}
	(void)cr_register_callback(cr_callback, NULL, CR_THREAD_CONTEXT);

	/* forward signals. copied from cr_restart */
	sa.sa_sigaction = signal_child;
	sa.sa_flags = SA_RESTART | SA_NODEFER | SA_SIGINFO;
	sigemptyset(&sa.sa_mask);
	for (sig = 0;  sig < _NSIG; sig ++) {
		if (sig == SIGSTOP ||
		    sig == SIGKILL ||
		    sig == SIGCHLD)
			continue;
		sigaction(sig, &sa, NULL);
	}
	sa.sa_sigaction = on_child_exit;
	sa.sa_flags = SA_RESTART | SA_SIGINFO | SA_NOCLDSTOP;
	sigaction(SIGCHLD, &sa, NULL);

	cr_enter_cs(cr_id); /* BEGIN CS: avoid race condition of whether srun is forked */
	if ( fork_exec_srun() ) {
		fatal("failed fork/exec/wait srun");
	}
	cr_leave_cs(cr_id); /* END CS */

	while (1) {
		pthread_mutex_lock(&step_launch_mutex);
		while (step_launched) {
			/* just avoid busy waiting */
			pthread_cond_wait(&step_launch_cond,
					  &step_launch_mutex);
		}
		pthread_mutex_unlock(&step_launch_mutex);

		if (_wait_for_srun_connect() < 0)
			continue;

		cr_enter_cs(cr_id); /* BEGIN CS: checkpoint(callback) will be delayed */

		srun_fd = accept(listen_fd, (struct sockaddr*)&ca, &ca_len);
		if (srun_fd < 0) {
			/* restarted before enter CS. socket will not be restored */
			if (errno == EBADF) {
				cr_leave_cs(cr_id);
				continue;
			} else {
				fatal("failed to accept socket: %m");
			}
		}

		_read_info_from_srun(srun_fd);
		close(srun_fd);

		step_launched = 1;
		debug2("step launched");

		cr_leave_cs(cr_id); /* END CS */
	}

	return 0;
}
Example #25
0
int main(int argc, char *argv[])
{
    opt_t opt;
    int retval = 0;
    const char *m;


    /*
     * Initialize.
     */
    err_init(xbasename(argv[0]));       /* init err package */

    /*
     *  If running setuid, fork a child to handle 
     *   all privileged operations and drop privs in this process.
     */
    privsep_init();

    /*
     * Seed options with default values:
     */
    opt_default(&opt, argv[0]);

    /*
     * Override defaults with environment
     */
    opt_env(&opt);

    /*
     * Process any options that need to be handled early:
     */
    opt_args_early(&opt, argc, argv);

    /*
     *  Load static or dynamic pdsh modules
     */
    mod_init();
    /*
     *  Allow module directory to be overridden, but not when
     *   running as root or setuid. (This is mainly for testing...)
     */
    if (!(m = getenv ("PDSH_MODULE_DIR")) ||
          getuid() == 0 ||
          getuid() != geteuid())
        m = pdsh_module_dir;
    if (mod_load_modules(m, &opt) < 0)
        errx("%p: Couldn't load any pdsh modules\n");

    /*
     * Handle options.
     */
    opt_args(&opt, argc, argv); /* override with command line           */

    if (opt_verify(&opt)) {     /* verify options, print errors         */
        /*
         * Do the work.
         */
        if (opt.info_only)      /* display info only */
            opt_list(&opt);
        else if (pdsh_personality() == PCP && opt.pcp_server) 
            retval = (_pcp_remote_server (&opt) < 0);
        else if (pdsh_personality() == PCP && opt.pcp_client)
            retval = (_pcp_remote_client (&opt) < 0);
        else if (pdsh_personality() == PCP || opt.cmd != NULL)
            retval = dsh(&opt); /* single dsh/pcp command */
        else                    /* prompt loop */
            _interactive_dsh(&opt);
    } else {
        retval = 1;
    }

    mod_exit(); 

    /*
     * Clean up.
     */
    privsep_fini();
    opt_free(&opt);             /* free heap storage in opt struct */
    err_cleanup();

    return retval;
}
Example #26
0
int main(int argc, char **argv)
{
	log_options_t opts = LOG_OPTS_STDERR_ONLY;
	node_info_msg_t *node_info_ptr = NULL;
	node_info_msg_t *new_node_ptr = NULL;
	int error_code;
	int height = 40;
	int width = 100;
	int startx = 0;
	int starty = 0;
	int end = 0;
	int i;
	int rc;

	slurm_conf_init(NULL);
	log_init(xbasename(argv[0]), opts, SYSLOG_FACILITY_DAEMON, NULL);
	parse_command_line(argc, argv);
	if (params.verbose) {
		opts.stderr_level += params.verbose;
		log_alter(opts, SYSLOG_FACILITY_USER, NULL);
	}

	if (params.cluster_dims == 4) {
		min_screen_width = 92;
	} else if (params.cluster_dims == 3)
		min_screen_width = 92;

	/* no need for this if you are resolving */
	while (slurm_load_node((time_t) NULL,
			       &new_node_ptr, SHOW_ALL)) {
		if (params.resolve || (params.display == COMMANDS)) {
			new_node_ptr = NULL;
			break;		/* just continue */
		}
		error_code = slurm_get_errno();
		printf("slurm_load_node: %s\n",
		       slurm_strerror(error_code));
		if (params.iterate == 0)
			exit(1);
		sleep(10);	/* keep trying to reconnect */
	}

	select_g_ba_init(new_node_ptr, 0);

	if (dim_size == NULL) {
		dim_size = get_cluster_dims(new_node_ptr);
		if ((dim_size == NULL) || (dim_size[0] < 1))
			fatal("Invalid system dimensions");
	}
	_init_colors();

	if (params.resolve) {
		char *ret_str = resolve_mp(params.resolve, new_node_ptr);
		if (ret_str) {
			printf("%s", ret_str);
			xfree(ret_str);
		}
		_smap_exit(0);	/* Calls exit(), no return */
	}
	if (!params.commandline) {
		int check_width = min_screen_width;

		initscr();
		init_grid(new_node_ptr, COLS);
		signal(SIGWINCH, (void (*)(int))_resize_handler);

		if (params.cluster_dims == 4) {
			height = dim_size[2] * dim_size[3] + dim_size[2] + 3;
			width = (dim_size[1] + dim_size[3] + 1) * dim_size[0]
				 + 2;
			check_width += width;
		} else if (params.cluster_dims == 3) {
			height = dim_size[1] * dim_size[2] + dim_size[1] + 3;
			width = dim_size[0] + dim_size[2] + 3;
			check_width += width;
		} else {
			height = 10;
			width = COLS;
		}

	        if ((COLS < check_width) || (LINES < height)) {
			endwin();
			error("Screen is too small make sure the screen "
			      "is at least %dx%d\n"
			      "Right now it is %dx%d\n",
			      check_width,
			      height,
			      COLS,
			      LINES);
			_smap_exit(1);	/* Calls exit(), no return */
		}

		raw();
		keypad(stdscr, true);
		noecho();
		cbreak();
		curs_set(0);
		nodelay(stdscr, true);
		start_color();
		_set_pairs();

		grid_win = newwin(height, width, starty, startx);
		max_display = (getmaxy(grid_win) - 1) * (getmaxx(grid_win) - 1);

		if (params.cluster_dims == 4) {
			startx = width;
			width = COLS - width - 2;
			height = LINES;
		} else if (params.cluster_dims == 3) {
			startx = width;
			width = COLS - width - 2;
			height = LINES;
		} else {
			startx = 0;
			starty = height;
			height = LINES - height;
		}

		text_win = newwin(height, width, starty, startx);
        }
	while (!end) {
		if (!params.commandline) {
			_get_option();
redraw:
			clear_window(text_win);
			clear_window(grid_win);
			move(0, 0);

			update_grid(new_node_ptr);
			main_xcord = 1;
			main_ycord = 1;
		}

		if (!params.no_header)
			print_date();

		clear_grid();
		switch (params.display) {
		case JOBS:
			get_job();
			break;
		case RESERVATIONS:
			get_reservation();
			break;
		case SLURMPART:
			get_slurm_part();
			break;
		case COMMANDS:
#ifdef HAVE_BG
			wclear(text_win);
			get_command();
#else
			error("Must be on a real BG SYSTEM to "
			      "run this command");
			if (!params.commandline)
				endwin();
			_smap_exit(1);	/* Calls exit(), no return */
#endif
			break;
		case BGPART:
			if (params.cluster_flags & CLUSTER_FLAG_BG)
				get_bg_part();
			else {
				error("Must be on a BG SYSTEM to "
				      "run this command");
				if (!params.commandline)
					endwin();
				_smap_exit(1);	/* Calls exit(), no return */
			}
			break;
		}

		if (!params.commandline) {
			box(text_win, 0, 0);
			wnoutrefresh(text_win);

			print_grid();
			box(grid_win, 0, 0);
			wnoutrefresh(grid_win);

			doupdate();

			node_info_ptr = new_node_ptr;
			if (node_info_ptr) {
				error_code = slurm_load_node(
					node_info_ptr->last_update,
					&new_node_ptr, SHOW_ALL);
				if (error_code == SLURM_SUCCESS)
					slurm_free_node_info_msg(
						node_info_ptr);
				else if (slurm_get_errno()
					 == SLURM_NO_CHANGE_IN_DATA) {
					error_code = SLURM_SUCCESS;
					new_node_ptr = node_info_ptr;
				}
			} else {
				error_code = slurm_load_node(
					(time_t) NULL,
					&new_node_ptr, SHOW_ALL);
			}
			if (error_code && (quiet_flag != 1)) {
				if (!params.commandline) {
					mvwprintw(
						text_win,
						main_ycord,
						1,
						"slurm_load_node: %s",
						slurm_strerror(
							slurm_get_errno()));
					main_ycord++;
				} else {
					printf("slurm_load_node: %s",
					       slurm_strerror(
						       slurm_get_errno()));
				}
			}
		}

		if (params.iterate) {
			for (i = 0; i < params.iterate; i++) {
				sleep(1);
				if (!params.commandline) {
					if ((rc = _get_option()) == 1)
						goto redraw;
					else if (resize_screen) {
						resize_screen = 0;
						goto redraw;
					}
				}
			}
		} else
			break;

	}

	if (!params.commandline) {
		nodelay(stdscr, false);
		getch();
		endwin();
	}

	_smap_exit(0);	/* Calls exit(), no return */
	exit(0);	/* Redundant, but eliminates compiler warning */
}
Example #27
0
File: sprio.c Project: A1ve5/slurm
int main (int argc, char *argv[])
{
	char *prio_type = NULL;
	int error_code = SLURM_SUCCESS;
	priority_factors_request_msg_t req_msg;
	priority_factors_response_msg_t *resp_msg = NULL;
	log_options_t opts = LOG_OPTS_STDERR_ONLY ;

	slurm_conf_init(NULL);
	log_init(xbasename(argv[0]), opts, SYSLOG_FACILITY_USER, NULL);

	parse_command_line( argc, argv );
	if (params.verbose) {
		opts.stderr_level += params.verbose;
		log_alter(opts, SYSLOG_FACILITY_USER, NULL);
	}

	if (working_cluster_rec) {
		slurm_ctl_conf_info_msg_t  *slurm_ctl_conf_ptr;

		error_code = slurm_load_ctl_conf((time_t) NULL,
						  &slurm_ctl_conf_ptr);
		if (error_code) {
			slurm_perror ("slurm_load_ctl_conf error");
			exit(error_code);
		}
		weight_age  = slurm_ctl_conf_ptr->priority_weight_age;
		weight_fs   = slurm_ctl_conf_ptr->priority_weight_fs;
		weight_js   = slurm_ctl_conf_ptr->priority_weight_js;
		weight_part = slurm_ctl_conf_ptr->priority_weight_part;
		weight_qos  = slurm_ctl_conf_ptr->priority_weight_qos;
		weight_tres = slurm_ctl_conf_ptr->priority_weight_tres;
		prio_type   = xstrdup(slurm_ctl_conf_ptr->priority_type);
		slurm_free_ctl_conf(slurm_ctl_conf_ptr);
	} else {
		weight_age  = slurm_get_priority_weight_age();
		weight_fs   = slurm_get_priority_weight_fairshare();
		weight_js   = slurm_get_priority_weight_job_size();
		weight_part = slurm_get_priority_weight_partition();
		weight_qos  = slurm_get_priority_weight_qos();
		weight_tres = slurm_get_priority_weight_tres();
		prio_type   = slurm_get_priority_type();
	}

	/* Check to see if we are running a supported accounting plugin */
	if (xstrcasecmp(prio_type, "priority/basic") == 0) {
		fprintf (stderr, "You are not running a supported "
			 "priority plugin\n(%s).\n"
			 "Only 'priority/multifactor' is supported.\n",
			 prio_type);
		exit(1);
	}
	xfree(prio_type);


	memset(&req_msg, 0, sizeof(priority_factors_request_msg_t));

	if (params.jobs)
		req_msg.job_id_list = params.job_list;
	else
		req_msg.job_id_list = NULL;

	if (params.users)
		req_msg.uid_list = params.user_list;
	else
		req_msg.uid_list = NULL;

	error_code = _get_info(&req_msg, &resp_msg);

	if (error_code) {
		slurm_perror("Couldn't get priority factors from controller");
		exit(error_code);
	}

	if (params.format == NULL) {
		if (params.normalized) {
			if (params.long_list)
				params.format = "%.15i %.8u %10y %10a %10f "
					"%10j %10p %10q %20t";
			else{
				params.format = xstrdup("%.15i");
				if (params.users)
					xstrcat(params.format, " %.8u");
				xstrcat(params.format, " %10y");
				if (weight_age)
					xstrcat(params.format, " %10a");
				if (weight_fs)
					xstrcat(params.format, " %10f");
				if (weight_js)
					xstrcat(params.format, " %10j");
				if (weight_part)
					xstrcat(params.format, " %10p");
				if (weight_qos)
					xstrcat(params.format, " %10q");
				if (weight_tres)
					xstrcat(params.format, " %20t");
			}
		} else {
			if (params.long_list)
				params.format = "%.15i %.8u %.10Y %.10A %.10F "
					"%.10J %.10P %.10Q %.6N %.20T";
			else{
				params.format = xstrdup("%.15i");
				if (params.users)
					xstrcat(params.format, " %.8u");
				xstrcat(params.format, " %.10Y");
				if (weight_age)
					xstrcat(params.format, " %.10A");
				if (weight_fs)
					xstrcat(params.format, " %.10F");
				if (weight_js)
					xstrcat(params.format, " %.10J");
				if (weight_part)
					xstrcat(params.format, " %.10P");
				if (weight_qos)
					xstrcat(params.format, " %.10Q");
				if (weight_tres)
					xstrcat(params.format, " %.20T");
			}
		}
	}

	/* create the format list from the format */
	parse_format(params.format);

	if (params.jobs && (!resp_msg || !resp_msg->priority_factors_list ||
			    !list_count(resp_msg->priority_factors_list))) {
		printf("Unable to find jobs matching user/id(s) specified\n");
	} else if (resp_msg) {
		print_jobs_array(resp_msg->priority_factors_list,
				 params.format_list);
	}
#if 0
	/* Free storage here if we want to verify that logic.
	 * Since we exit next, this is not important */
	FREE_NULL_LIST(params.format_list);
	slurm_free_priority_factors_response_msg(resp_msg);
#endif

	exit (error_code);
}
int
main(int argc, char **argv)
{
    int onlydir, dodir, dolink, dorelsymlink, dotimes, opt, len, lplen, tdlen, bnlen, exists, fromfd, tofd, cc, wc;
    mode_t mode = 0755;
    char *linkprefix, *owner, *group, *cp, *cwd, *todir, *toname, *name, *base, *linkname, *bp, buf[BUFSIZ];
    uid_t uid;
    gid_t gid;
    struct stat sb, tosb;
    struct utimbuf utb;

    program = argv[0];
    cwd = linkname = linkprefix = owner = group = 0;
    onlydir = dodir = dolink = dorelsymlink = dotimes = lplen = 0;

    while ((opt = getopt(argc, argv, "C:DdlL:Rm:o:g:t")) != EOF) {
	switch (opt) {
	  case 'C':
	    cwd = optarg;
	    break;
	  case 'D':
	    onlydir = 1;
	    break;
	  case 'd':
	    dodir = 1;
	    break;
	  case 'l':
	    dolink = 1;
	    break;
	  case 'L':
	    linkprefix = optarg;
	    lplen = strlen(linkprefix);
	    dolink = 1;
	    break;
	  case 'R':
	    dolink = dorelsymlink = 1;
	    break;
	  case 'm':
	    mode = strtoul(optarg, &cp, 8);
	    if (mode == 0 && cp == optarg)
		usage();
	    break;
	  case 'o':
	    owner = optarg;
	    break;
	  case 'g':
	    group = optarg;
	    break;
	  case 't':
	    dotimes = 1;
	    break;
	  default:
	    usage();
	}
    }

    argc -= optind;
    argv += optind;
    if (argc < 2 - onlydir)
	usage();

    todir = argv[argc-1];
    if ((stat(todir, &sb) < 0 || !S_ISDIR(sb.st_mode)) &&
	mkdirs(todir, 0777) < 0) {
	fail("cannot make directory %s", todir);
    }
    if (onlydir)
	return 0;

    if (!cwd) {
#ifdef GETCWD_CAN_MALLOC
	cwd = getcwd(0, PATH_MAX);
#else
	cwd = malloc(PATH_MAX + 1);
	cwd = getcwd(cwd, PATH_MAX);
#endif
    }
    xchdir(todir);
#ifdef GETCWD_CAN_MALLOC
    todir = getcwd(0, PATH_MAX);
#else
    todir = malloc(PATH_MAX + 1);
    todir = getcwd(todir, PATH_MAX);
#endif
    tdlen = strlen(todir);
    xchdir(cwd);
    tdlen = strlen(todir);

    uid = owner ? touid(owner) : -1;
    gid = group ? togid(group) : -1;

    while (--argc > 0) {
	name = *argv++;
	len = strlen(name);
	base = xbasename(name);
	bnlen = strlen(base);
	toname = (char*)xmalloc(tdlen + 1 + bnlen + 1);
	sprintf(toname, "%s/%s", todir, base);
	exists = (lstat(toname, &tosb) == 0);

	if (dodir) {
	    /* -d means create a directory, always */
	    if (exists && !S_ISDIR(tosb.st_mode)) {
		(void) unlink(toname);
		exists = 0;
	    }
	    if (!exists && mkdir(toname, mode) < 0)
		fail("cannot make directory %s", toname);
	    if ((owner || group) && chown(toname, uid, gid) < 0)
		fail("cannot change owner of %s", toname);
	} else if (dolink) {
	    if (*name == '/') {
		/* source is absolute pathname, link to it directly */
		linkname = 0;
	    } else {
		if (linkprefix) {
		    /* -L implies -l and prefixes names with a $cwd arg. */
		    len += lplen + 1;
		    linkname = (char*)xmalloc(len + 1);
		    sprintf(linkname, "%s/%s", linkprefix, name);
		} else if (dorelsymlink) {
		    /* Symlink the relative path from todir to source name. */
		    linkname = (char*)xmalloc(PATH_MAX);

		    if (*todir == '/') {
			/* todir is absolute: skip over common prefix. */
			lplen = relatepaths(todir, cwd, linkname);
			strcpy(linkname + lplen, name);
		    } else {
			/* todir is named by a relative path: reverse it. */
			reversepath(todir, name, len, linkname);
			xchdir(cwd);
		    }

		    len = strlen(linkname);
		}
		name = linkname;
	    }

	    /* Check for a pre-existing symlink with identical content. */
	    if (exists &&
		(!S_ISLNK(tosb.st_mode) ||
		 readlink(toname, buf, sizeof buf) != len ||
		 strncmp(buf, name, len) != 0)) {
		(void) (S_ISDIR(tosb.st_mode) ? rmdir : unlink)(toname);
		exists = 0;
	    }
	    if (!exists && symlink(name, toname) < 0)
		fail("cannot make symbolic link %s", toname);
#ifdef HAVE_LCHOWN
	    if ((owner || group) && lchown(toname, uid, gid) < 0)
		fail("cannot change owner of %s", toname);
#endif

	    if (linkname) {
		free(linkname);
		linkname = 0;
	    }
	} else {
	    /* Copy from name to toname, which might be the same file. */
	    fromfd = open(name, O_RDONLY);
	    if (fromfd < 0 || fstat(fromfd, &sb) < 0)
		fail("cannot access %s", name);
	    if (exists && (!S_ISREG(tosb.st_mode) || access(toname, W_OK) < 0))
		(void) (S_ISDIR(tosb.st_mode) ? rmdir : unlink)(toname);
	    tofd = open(toname, O_CREAT | O_WRONLY, 0666);
	    if (tofd < 0)
		fail("cannot create %s", toname);

	    bp = buf;
	    while ((cc = read(fromfd, bp, sizeof buf)) > 0) {
		while ((wc = write(tofd, bp, cc)) > 0) {
		    if ((cc -= wc) == 0)
			break;
		    bp += wc;
		}
		if (wc < 0)
		    fail("cannot write to %s", toname);
	    }
	    if (cc < 0)
		fail("cannot read from %s", name);

	    if (ftruncate(tofd, sb.st_size) < 0)
		fail("cannot truncate %s", toname);
	    if (dotimes) {
		utb.actime = sb.st_atime;
		utb.modtime = sb.st_mtime;
		if (utime(toname, &utb) < 0)
		    fail("cannot set times of %s", toname);
	    }
#ifdef HAVE_FCHMOD
	    if (fchmod(tofd, mode) < 0)
#else
	    if (chmod(toname, mode) < 0)
#endif
		fail("cannot change mode of %s", toname);
	    if ((owner || group) && fchown(tofd, uid, gid) < 0)
		fail("cannot change owner of %s", toname);

	    /* Must check for delayed (NFS) write errors on close. */
	    if (close(tofd) < 0)
		fail("cannot write to %s", toname);
	    close(fromfd);
	}

	free(toname);
    }

    free(cwd);
    free(todir);
    return 0;
}
Example #29
0
/*
 * Initialize scheduler log with
 * prog = program name to tag error messages with
 * opt  = log_options_t specifying max log levels for syslog, stderr, and file
 * fac  = log facility for syslog (unused if syslog level == LOG_QUIET)
 * logfile = logfile name if logfile level > LOG_QUIET
 */
static int
_sched_log_init(char *prog, log_options_t opt, log_facility_t fac, 
		char *logfile)
{
	int rc = 0;

	if (!sched_log) {
		sched_log = (log_t *)xmalloc(sizeof(log_t));
		atfork_install_handlers();
	}

	if (prog) {
		xfree(sched_log->argv0);
		sched_log->argv0 = xstrdup(xbasename(prog));
	} else if (!sched_log->argv0) {
		const char *short_name;
		short_name = strrchr((const char *) default_name, '/');
		if (short_name) 
			short_name++;
		else
			short_name = default_name;
		sched_log->argv0 = xstrdup(short_name);
	}

	if (!sched_log->fpfx)
		sched_log->fpfx = xstrdup("");

	sched_log->opt = opt;

	if (sched_log->buf) {
		cbuf_destroy(sched_log->buf);
		sched_log->buf = NULL;
	}
	if (sched_log->fbuf) {
		cbuf_destroy(sched_log->fbuf);
		sched_log->fbuf = NULL;
	}

	if (sched_log->opt.buffered) {
		sched_log->buf  = cbuf_create(128, 8192);
		sched_log->fbuf = cbuf_create(128, 8192);
	}

	if (sched_log->opt.syslog_level > LOG_LEVEL_QUIET)
		sched_log->facility = fac;

	if (logfile) {
		FILE *fp;

		fp = safeopen(logfile, "a", SAFEOPEN_LINK_OK);

		if (!fp) {
			rc = errno;
			goto out;
		}

		if (sched_log->logfp)
			fclose(sched_log->logfp); /* Ignore errors */

		sched_log->logfp = fp;
	}

	if (sched_log->logfp) {
		int fd;
		if ((fd = fileno(sched_log->logfp)) < 0)
			sched_log->logfp = NULL;
		else
			fd_set_close_on_exec(fd);
	}

	sched_log->initialized = 1;
 out:
	return rc;
}
Example #30
0
File: upslog.c Project: alezz/nut
int main(int argc, char **argv)
{
	int	interval = 30, i;
	const char	*prog = xbasename(argv[0]);
	time_t	now, nextpoll = 0;
	const char	*user = NULL;
	struct passwd	*new_uid = NULL;
	const char	*pidfilebase = prog;

	logformat = DEFAULT_LOGFORMAT;
	user = RUN_AS_USER;

	printf("Network UPS Tools %s %s\n", prog, UPS_VERSION);

	 while ((i = getopt(argc, argv, "+hs:l:i:f:u:Vp:")) != -1) {
		switch(i) {
			case 'h':
				help(prog);
				break;

			case 's':
				monhost = optarg;
				break;

			case 'l':
				logfn = optarg;
				break;

			case 'i':
				interval = atoi(optarg);
				break;

			case 'f':
				logformat = optarg;
				break;

			case 'u':
				user = optarg;
				break;

			case 'V':
				exit(EXIT_SUCCESS);

			case 'p':
				pidfilebase = optarg;
				break;
		}
	}

	argc -= optind;
	argv += optind;

	/* not enough args for the old way? */
	if ((argc == 1) || (argc == 2))
		help(prog);

	/* see if it's being called in the old style - 3 or 4 args */

	/* <system> <logfn> <interval> [<format>] */

	if (argc >= 3) {
		monhost = argv[0];
		logfn = argv[1];
		interval = atoi(argv[2]);
	}

	if (argc >= 4) {
		/* read out the remaining argv entries to the format string */

		logformat = xmalloc(LARGEBUF);
		memset(logformat, '\0', LARGEBUF);

		for (i = 3; i < argc; i++)
			snprintfcat(logformat, LARGEBUF, "%s ", argv[i]);
	}

	if (!monhost)
		fatalx(EXIT_FAILURE, "No UPS defined for monitoring - use -s <system>");

	if (!logfn)
		fatalx(EXIT_FAILURE, "No filename defined for logging - use -l <file>");

	/* shouldn't happen */
	if (!logformat)
		fatalx(EXIT_FAILURE, "No format defined - but this should be impossible");

	printf("logging status of %s to %s (%is intervals)\n", 
		monhost, logfn, interval);

	if (upscli_splitname(monhost, &upsname, &hostname, &port) != 0) {
		fatalx(EXIT_FAILURE, "Error: invalid UPS definition.  Required format: upsname[@hostname[:port]]\n");
	}

	if (upscli_connect(&ups, hostname, port, UPSCLI_CONN_TRYSSL) < 0)
		fprintf(stderr, "Warning: initial connect failed: %s\n", 
			upscli_strerror(&ups));

	if (strcmp(logfn, "-") == 0)
		logfile = stdout;
	else
		logfile = fopen(logfn, "a");

	if (logfile == NULL)
		fatal_with_errno(EXIT_FAILURE, "could not open logfile %s", logfn);

	/* now drop root if we have it */
	new_uid = get_user_pwent(user);

	open_syslog(prog); 

	if (logfile != stdout)
		background();

	setup_signals();

	writepid(pidfilebase);

	become_user(new_uid);

	compile_format();

	while (exit_flag == 0) {
		time(&now);

		if (nextpoll > now) {
			/* there is still time left, so sleep it off */
			sleep(difftime(nextpoll, now));
			nextpoll += interval;
		} else {
			/* we spent more time in polling than the interval allows */
			nextpoll = now + interval;
		}

		if (reopen_flag) {
			upslogx(LOG_INFO, "Signal %d: reopening log file", 
				reopen_flag);
			reopen_log();
			reopen_flag = 0;
		}

		/* reconnect if necessary */
		if (upscli_fd(&ups) < 0) {
			upscli_connect(&ups, hostname, port, 0);
		}

		run_flist();

		/* don't keep connection open if we don't intend to use it shortly */
		if (interval > 30) {
			upscli_disconnect(&ups);
		}
	}

	upslogx(LOG_INFO, "Signal %d: exiting", exit_flag);

	if (logfile != stdout)
		fclose(logfile);

	upscli_disconnect(&ups);
	
	exit(EXIT_SUCCESS);
}