示例#1
0
文件: pmdbg.c 项目: aeppert/pcp
int
main(int argc, char **argv)
{
    int		i;
    int		c;

    while ((c = pmgetopt_r(argc, argv, &opts)) != EOF) {
	switch (c) {

	case 'l':	/* list all flags */
	    printf("Performance Co-Pilot Debug Flags\n");
	    printf("#define                 Value  Meaning\n");
	    for (i = 0; i < nfoo; i++)
		printf(fmt, foo[i].name, foo[i].flag, foo[i].text);
	    exit(0);

	case '?':
	default:
	    opts.errors++;
	    break;
	}
    }

    if (opts.errors || opts.optind >= argc) {
	pmUsageMessage(&opts);
	exit(1);
    }

    /* non-flag args are argv[opts.optind] ... argv[argc-1] */
    while (opts.optind < argc) {
	char	*p = argv[opts.optind];
	for (p = argv[opts.optind]; *p && isdigit((int)*p); p++)
	    ;
	if (*p == '\0')
	    sscanf(argv[opts.optind], "%d", &c);
	else {
	    char	*q;
	    p = argv[opts.optind];
	    if (*p == '0' && (p[1] == 'x' || p[1] == 'X'))
		p = &p[2];
	    for (q = p; isxdigit((int)*q); q++)
		;
	    if (*q != '\0' || sscanf(p, "%x", &c) != 1) {
		printf("Cannot decode \"%s\" - neither decimal nor hexadecimal\n", argv[opts.optind]);
		goto next;
	    }
	}
	printf("Performance Co-Pilot -- pmDebug value = %d (0x%x)\n", c, c);
	printf("#define                 Value  Meaning\n");
	for (i = 0; i < nfoo; i++) {
	    if (c & foo[i].flag)
		printf(fmt, foo[i].name, foo[i].flag, foo[i].text);
	}

next:
	opts.optind++;
    }

    return 0;
}
示例#2
0
文件: pmhostname.c 项目: Aconex/pcp
int
main(int argc, char **argv)
{
    char	*name, *hename;
    char       	host[MAXHOSTNAMELEN];
    __pmHostEnt	*hep;

    while (pmGetOptions(argc, argv, &opts) != EOF)
	opts.errors++;

    if (opts.errors || argc > opts.optind + 1) {
	pmUsageMessage(&opts);
	exit(1);
    }

    if (argc == opts.optind) {
	if (gethostname(host, MAXHOSTNAMELEN) < 0) {
	    fprintf(stderr, "%s: gethostname failure\n", pmProgname);
	    exit(1);
	}
	name = host;
    }
    else
	name = argv[opts.optind];

    hep = __pmGetAddrInfo(name);
    if (hep == NULL) {
        printf("%s\n", name);
    }
    else {
	hename = __pmHostEntGetName(hep);
        printf("%s\n", hename ? hename : name);
    }

    exit(0);
}
示例#3
0
文件: collectl2pcp.c 项目: Aconex/pcp
int
main(int argc, char *argv[])
{
    int         sts;
    int         ctx;
    int         c;
    char	*infile;
    int		nfilelist;
    int		filenum;
    char	*archive = NULL;
    int		j;
    char	*buf;
    fields_t	*f;
    char	*s;
    int		gzipped;
    FILE	*fp;
    metric_t	*m;
    handler_t	*h;
    int		unhandled_metric_cnt = 0;

    while ((c = pmGetOptions(argc, argv, &opts)) != EOF) {
        switch (c) {
	case 'F':
	    Fflag = 1;
	    break;
	case 'v':
	    vflag++;
	    break;
        }
    }

    nfilelist = argc - opts.optind - 1;
    if (nfilelist < 1)
    	opts.errors++;
    else
	archive = argv[argc - 1];

    if (opts.errors) {
	pmUsageMessage(&opts);
	exit(1);
    }

    if ((buf = malloc(BUFSIZE)) == NULL) {
    	perror("Error: out of memory:");
	exit(1);
    }

    if (Fflag) {
    	snprintf(buf, BUFSIZE, "%s.meta", archive); unlink(buf);
    	snprintf(buf, BUFSIZE, "%s.index", archive); unlink(buf);
	for (j=0;; j++) {
	    snprintf(buf, BUFSIZE, "%s.%d", archive, j);
	    if (unlink(buf) < 0)
	    	break;
	}
    }

    ctx = pmiStart(archive, 0);
    if ((sts = pmiUseContext(ctx)) < 0) {
	fprintf(stderr, "Error: pmiUseContext failed: %s\n", pmiErrStr(sts));
	exit(1);
    }

    /*
     * Define the metrics name space, see metrics.c (generated by pmdesc)
     */
    for (m = metrics; m->name; m++) {
	pmDesc *d = &m->desc;

	sts = pmiAddMetric(m->name, d->pmid, d->type, d->indom, d->sem, d->units);
	if (sts < 0) {
	    fprintf(stderr, "Error: failed to add metric %s: %s\n", m->name, pmiErrStr(sts));
	    exit(1);
	}
    }

    /*
     * Populate special case instance domains
     */
    pmiAddInstance(pmInDom_build(LINUX_DOMAIN, LOADAVG_INDOM), "1 minute", 1);
    pmiAddInstance(pmInDom_build(LINUX_DOMAIN, LOADAVG_INDOM), "5 minute", 5);
    pmiAddInstance(pmInDom_build(LINUX_DOMAIN, LOADAVG_INDOM), "15 minute", 15);
    indom_cnt[LOADAVG_INDOM] = 3;

    for (filenum=0; filenum < nfilelist; filenum++) {
	infile = argv[opts.optind + filenum];
	gzipped = strstr(infile, ".gz") != NULL;
	if (gzipped) {
	    snprintf(buf, BUFSIZE, "gzip -c -d %s", infile);
	    if ((fp = popen(buf, "r")) == NULL)
		perror(buf);
	}
	else
	if ((fp = fopen(infile, "r")) == NULL)
	    perror(infile);

	if (fp == NULL) {
	    pmUsageMessage(&opts);
	    exit(1);
	}

	/*
	 * parse the header
	 */
	sts = header_handler(fp, infile, buf, BUFSIZE);

	/*
	 * Parse remaining data stream for this input file
	 */
	while(fgets(buf, BUFSIZE, fp)) {
	    if ((s = strrchr(buf, '\n')) != NULL)
		*s = '\0';
	    if (!buf[0])
	    	continue;
	    f = fields_new(buf, strlen(buf)+1);
	    if (f->nfields > 0) {
		if ((h = find_handler(f->fields[0])) == NULL) {
		    unhandled_metric_cnt++;
		    if (vflag > 1)
			printf("Unhandled tag: \"%s\"\n", f->fields[0]);
		}
		else {
		    sts = h->handler(h, f);
		    if (sts < 0 && h->handler == timestamp_handler) {
			fprintf(stderr, "Error: %s\n", pmiErrStr(sts));
			exit(1);
		    }
		}
	    }
	    fields_free(f);
	}

	/* final flush for this file */
	if ((sts = timestamp_flush()) < 0) {
	    fprintf(stderr, "Error: failed to write final timestamp: %s\n", pmiErrStr(sts));
	    exit(1);
	}

	if (gzipped)
	    pclose(fp);
	else
	    fclose(fp);
    }

    sts = pmiEnd();
    if (unhandled_metric_cnt && vflag)
    	fprintf(stderr, "Warning: %d unhandled metric/values\n", unhandled_metric_cnt);

    exit(0);
}
示例#4
0
int main(int argc, char **argv)
{
    int		autoport = 0;

    QApplication a(argc, argv);
    setupEnvironment();

    /* -a/-h ignored, back-compat for time control from libpcp_gui */
    opts.short_options = "ahD:p:V?";
    opts.long_options = longopts;
    (void)pmGetOptions(argc, argv, &opts);
    if (opts.errors || opts.optind != argc) {
	pmUsageMessage(&opts);
	exit(1);
    }

    if (!opts.guiport) {
	char	*endnum, *envstr;

	autoport = 1;
	if ((envstr = getenv("PMTIME_PORT")) == NULL) {
	    opts.guiport = PmTime::BasePort;
	} else {
	    opts.guiport = strtol(envstr, &endnum, 0);
	    if (*endnum != '\0' || opts.guiport < 0) {
		pmprintf(
		    "%s: PMTIME_PORT must be a numeric port number (not %s)\n",
			pmProgname, envstr);
		pmflush();
		exit(1);
	    }
	}
    }

    console = new Console;
    TimeLord tl(&a);
    do {
	if (tl.listen(QHostAddress::LocalHost, opts.guiport))
	    break;
	opts.guiport++;
    } while (autoport && (opts.guiport >= 0));

    if (!opts.guiport || tl.isListening() == false) {
	if (!autoport)
	    pmprintf("%s: cannot find an available port\n", pmProgname);
	else
	    pmprintf("%s: cannot connect to requested port (%d)\n",
		    pmProgname, opts.guiport);
	pmflush();
	exit(1);
    } else if (autoport) {	/* write to stdout for client */
	char	name[32];
	int	c = snprintf(name, sizeof(name), "port=%u\n", opts.guiport);
	if (write(fileno(stdout), name, c + 1) < 0) {
	    if (errno != EPIPE) {
		pmprintf("%s: cannot write port for client: %s\n",
		    pmProgname, strerror(errno));
		pmflush();
	    }
	    exit(1);
	}
    }

    PmTimeLive hc;
    PmTimeArch ac;
    tl.setContext(&hc, &ac);

    hc.init();
    if (!pmDebug) hc.disableConsole();
    else hc.popup(1);

    ac.init();
    if (!pmDebug) ac.disableConsole();
    else ac.popup(1);

    a.exec();
    return 0;
}
示例#5
0
int
main(int argc, char **argv)
{
    int			c;
    int			sts;
    int			sep = __pmPathSeparator();
    int			use_localtime = 0;
    int			isdaemon = 0;
    char		*pmnsfile = PM_NS_DEFAULT;
    char		*username;
    char		*logfile = "pmlogger.log";
				    /* default log (not archive) file name */
    char		*endnum;
    int			i;
    task_t		*tp;
    optcost_t		ocp;
    __pmFdSet		readyfds;
    char		*p;
    char		*runtime = NULL;
    int	    		ctx;		/* handle corresponding to ctxp below */
    __pmContext  	*ctxp;		/* pmlogger has just this one context */
    int			niter;
    pid_t               target_pid = 0;

    __pmGetUsername(&username);

    /*
     * Warning:
     *		If any of the pmlogger options change, make sure the
     *		corresponding changes are made to pmnewlog when pmlogger
     *		options are passed through from the control file
     */
    while ((c = pmgetopt_r(argc, argv, &opts)) != EOF) {
	switch (c) {

	case 'c':		/* config file */
	    if (access(opts.optarg, F_OK) == 0)
		configfile = opts.optarg;
	    else {
		/* does not exist as given, try the standard place */
		char *sysconf = pmGetConfig("PCP_VAR_DIR");
		int sz = strlen(sysconf)+strlen("/config/pmlogger/")+strlen(opts.optarg)+1;
		if ((configfile = (char *)malloc(sz)) == NULL)
		    __pmNoMem("config file name", sz, PM_FATAL_ERR);
		snprintf(configfile, sz,
			"%s%c" "config%c" "pmlogger%c" "%s",
			sysconf, sep, sep, sep, opts.optarg);
		if (access(configfile, F_OK) != 0) {
		    /* still no good, error handling happens below */
		    free(configfile);
		    configfile = opts.optarg;
		}
	    }
	    break;

	case 'D':	/* debug flag */
	    sts = __pmParseDebug(opts.optarg);
	    if (sts < 0) {
		pmprintf("%s: unrecognized debug flag specification (%s)\n",
			pmProgname, opts.optarg);
		opts.errors++;
	    }
	    else
		pmDebug |= sts;
	    break;

	case 'h':		/* hostname for PMCD to contact */
	    pmcd_host_conn = opts.optarg;
	    break;

	case 'l':		/* log file name */
	    logfile = opts.optarg;
	    break;

	case 'L':		/* linger if not primary logger */
	    linger = 1;
	    break;

	case 'm':		/* note for port map file */
	    note = opts.optarg;
	    isdaemon = ((strcmp(note, "pmlogger_check") == 0) ||
			(strcmp(note, "pmlogger_daily") == 0));
	    break;

	case 'n':		/* alternative name space file */
	    pmnsfile = opts.optarg;
	    break;

	case 'p':
	    target_pid = (int)strtol(opts.optarg, &endnum, 10);
	    if (*endnum != '\0') {
		pmprintf("%s: invalid process identifier (%s)\n",
			 pmProgname, opts.optarg);
		opts.errors++;
	    } else if (!__pmProcessExists(target_pid)) {
		pmprintf("%s: PID error - no such process (%d)\n",
			 pmProgname, target_pid);
		opts.errors++;
	    }
	    break;

	case 'P':		/* this is the primary pmlogger */
	    primary = 1;
	    isdaemon = 1;
	    break;

	case 'r':		/* report sizes of pmResult records */
	    rflag = 1;
	    break;

	case 's':		/* exit size */
	    sts = ParseSize(opts.optarg, &exit_samples, &exit_bytes, &exit_time);
	    if (sts < 0) {
		pmprintf("%s: illegal size argument '%s' for exit size\n",
			pmProgname, opts.optarg);
		opts.errors++;
	    }
	    else if (exit_time.tv_sec > 0) {
		__pmAFregister(&exit_time, NULL, run_done_callback);
	    }
	    break;

	case 'T':		/* end time */
	    runtime = opts.optarg;
            break;

	case 't':		/* change default logging interval */
	    if (pmParseInterval(opts.optarg, &delta, &p) < 0) {
		pmprintf("%s: illegal -t argument\n%s", pmProgname, p);
		free(p);
		opts.errors++;
	    }
	    break;

	case 'U':		/* run as named user */
	    username = opts.optarg;
	    isdaemon = 1;
	    break;

	case 'u':		/* flush output buffers after each fetch */
	    /*
	     * all archive write I/O is unbuffered now, so maintain -u
	     * for backwards compatibility only
	     */
	    break;

	case 'v':		/* volume switch after given size */
	    sts = ParseSize(opts.optarg, &vol_switch_samples, &vol_switch_bytes,
			    &vol_switch_time);
	    if (sts < 0) {
		pmprintf("%s: illegal size argument '%s' for volume size\n", 
			pmProgname, opts.optarg);
		opts.errors++;
	    }
	    else if (vol_switch_time.tv_sec > 0) {
		vol_switch_afid = __pmAFregister(&vol_switch_time, NULL, 
						 vol_switch_callback);
            }
	    break;

        case 'V': 
	    archive_version = (int)strtol(opts.optarg, &endnum, 10);
	    if (*endnum != '\0' || archive_version != PM_LOG_VERS02) {
		pmprintf("%s: -V requires a version number of %d\n",
			 pmProgname, PM_LOG_VERS02); 
		opts.errors++;
	    }
	    break;

	case 'x':		/* recording session control fd */
	    rsc_fd = (int)strtol(opts.optarg, &endnum, 10);
	    if (*endnum != '\0' || rsc_fd < 0) {
		pmprintf("%s: -x requires a non-negative numeric argument\n", pmProgname);
		opts.errors++;
	    }
	    else {
		time(&rsc_start);
	    }
	    break;

	case 'y':
	    use_localtime = 1;
	    break;

	case '?':
	default:
	    opts.errors++;
	    break;
	}
    }

    if (primary && pmcd_host != NULL) {
	pmprintf(
	    "%s: -P and -h are mutually exclusive; use -P only when running\n"
	    "%s on the same (local) host as the PMCD to which it connects.\n",
		pmProgname, pmProgname);
	opts.errors++;
    }

    if (!opts.errors && opts.optind != argc - 1) {
	pmprintf("%s: insufficient arguments\n", pmProgname);
	opts.errors++;
    }

    if (opts.errors) {
	pmUsageMessage(&opts);
	exit(1);
    }

    if (rsc_fd != -1 && note == NULL) {
	/* add default note to indicate running with -x */
	static char	xnote[10];
	snprintf(xnote, sizeof(xnote), "-x %d", rsc_fd);
	note = xnote;
    }

    /* if we are running as a daemon, change user early */
    if (isdaemon)
	__pmSetProcessIdentity(username);

    __pmOpenLog("pmlogger", logfile, stderr, &sts);
    if (sts != 1) {
	fprintf(stderr, "%s: Warning: log file (%s) creation failed\n", pmProgname, logfile);
	/* continue on ... writing to stderr */
    }

    /* base name for archive is here ... */
    archBase = argv[opts.optind];

    if (pmcd_host_conn == NULL)
	pmcd_host_conn = "local:";

    /* initialise access control */
    if (__pmAccAddOp(PM_OP_LOG_ADV) < 0 ||
	__pmAccAddOp(PM_OP_LOG_MAND) < 0 ||
	__pmAccAddOp(PM_OP_LOG_ENQ) < 0) {
	fprintf(stderr, "%s: access control initialisation failed\n", pmProgname);
	exit(1);
    }

    if (pmnsfile != PM_NS_DEFAULT) {
	if ((sts = pmLoadASCIINameSpace(pmnsfile, 1)) < 0) {
	    fprintf(stderr, "%s: Cannot load namespace from \"%s\": %s\n", pmProgname, pmnsfile, pmErrStr(sts));
	    exit(1);
	}
    }

    if ((ctx = pmNewContext(PM_CONTEXT_HOST, pmcd_host_conn)) < 0) {
	fprintf(stderr, "%s: Cannot connect to PMCD on host \"%s\": %s\n", pmProgname, pmcd_host_conn, pmErrStr(ctx));
	exit(1);
    }
    pmcd_host = (char *)pmGetContextHostName(ctx);
    if (strlen(pmcd_host) == 0) {
	fprintf(stderr, "%s: pmGetContextHostName(%d) failed\n",
	    pmProgname, ctx);
	exit(1);
    }

    if (rsc_fd == -1) {
	/* no -x, so register client id with pmcd */
	__pmSetClientIdArgv(argc, argv);
    }

    /*
     * discover fd for comms channel to PMCD ... 
     */
    if ((ctxp = __pmHandleToPtr(ctx)) == NULL) {
	fprintf(stderr, "%s: botch: __pmHandleToPtr(%d) returns NULL!\n", pmProgname, ctx);
	exit(1);
    }
    pmcdfd = ctxp->c_pmcd->pc_fd;
    PM_UNLOCK(ctxp->c_lock);

    if (configfile != NULL) {
	if ((yyin = fopen(configfile, "r")) == NULL) {
	    fprintf(stderr, "%s: Cannot open config file \"%s\": %s\n",
		pmProgname, configfile, osstrerror());
	    exit(1);
	}
    }
    else {
	/* **ANY** Lex would read from stdin automagically */
	configfile = "<stdin>";
    }

    __pmOptFetchGetParams(&ocp);
    ocp.c_scope = 1;
    __pmOptFetchPutParams(&ocp);

    /* prevent early timer events ... */
    __pmAFblock();

    if (yyparse() != 0)
	exit(1);
    if (configfile != NULL)
	fclose(yyin);
    yyend();

#ifdef PCP_DEBUG
    fprintf(stderr, "Config parsed\n");
#endif

    fprintf(stderr, "Starting %slogger for host \"%s\" via \"%s\"\n",
            primary ? "primary " : "", pmcd_host, pmcd_host_conn);

#ifdef PCP_DEBUG
    if (pmDebug & DBG_TRACE_LOG) {
	fprintf(stderr, "optFetch Cost Parameters: pmid=%d indom=%d fetch=%d scope=%d\n",
		ocp.c_pmid, ocp.c_indom, ocp.c_fetch, ocp.c_scope);

	fprintf(stderr, "\nAfter loading config ...\n");
	for (tp = tasklist; tp != NULL; tp = tp->t_next) {
	    if (tp->t_numvalid == 0)
		continue;
	    fprintf(stderr, " state: %sin log, %savail, %s, %s",
		PMLC_GET_INLOG(tp->t_state) ? "" : "not ",
		PMLC_GET_AVAIL(tp->t_state) ? "" : "un",
		PMLC_GET_MAND(tp->t_state) ? "mand" : "adv",
		PMLC_GET_ON(tp->t_state) ? "on" : "off");
	    fprintf(stderr, " delta: %ld usec", 
			(long)1000 * tp->t_delta.tv_sec + tp->t_delta.tv_usec);
	    fprintf(stderr, " numpmid: %d\n", tp->t_numpmid);
	    for (i = 0; i < tp->t_numpmid; i++) {
		fprintf(stderr, "  %s (%s):\n", pmIDStr(tp->t_pmidlist[i]), tp->t_namelist[i]);
	    }
	    __pmOptFetchDump(stderr, tp->t_fetch);
	}
    }
#endif

    if (!primary && tasklist == NULL && !linger) {
	fprintf(stderr, "Nothing to log, and not the primary logger instance ... good-bye\n");
	exit(1);
    }

    if ((sts = __pmLogCreate(pmcd_host, archBase, archive_version, &logctl)) < 0) {
	fprintf(stderr, "__pmLogCreate: %s\n", pmErrStr(sts));
	exit(1);
    }
    else {
	/*
	 * try and establish $TZ from the remote PMCD ...
	 * Note the label record has been set up, but not written yet
	 */
	char		*name = "pmcd.timezone";
	pmID		pmid;
	pmResult	*resp;

	__pmtimevalNow(&epoch);
	sts = pmUseContext(ctx);

	if (sts >= 0)
	    sts = pmLookupName(1, &name, &pmid);
	if (sts >= 0)
	    sts = pmFetch(1, &pmid, &resp);
	if (sts >= 0) {
	    if (resp->vset[0]->numval > 0) { /* pmcd.timezone present */
		strcpy(logctl.l_label.ill_tz, resp->vset[0]->vlist[0].value.pval->vbuf);
		/* prefer to use remote time to avoid clock drift problems */
		epoch = resp->timestamp;		/* struct assignment */
		if (! use_localtime)
		    pmNewZone(logctl.l_label.ill_tz);
	    }
#ifdef PCP_DEBUG
	    else if (pmDebug & DBG_TRACE_LOG) {
		fprintf(stderr,
			"main: Could not get timezone from host %s\n",
			pmcd_host);
	    }
#endif
	    pmFreeResult(resp);
	}
    }

    /* do ParseTimeWindow stuff for -T */
    if (runtime) {
        struct timeval res_end;    /* time window end */
        struct timeval start;
        struct timeval end;
        struct timeval last_delta;
        char *err_msg;             /* parsing error message */
        time_t now;
        struct timeval now_tv;

        time(&now);
        now_tv.tv_sec = now;
        now_tv.tv_usec = 0; 

        start = now_tv;
        end.tv_sec = INT_MAX;
        end.tv_usec = INT_MAX;
        sts = __pmParseTime(runtime, &start, &end, &res_end, &err_msg);
        if (sts < 0) {
	    fprintf(stderr, "%s: illegal -T argument\n%s", pmProgname, err_msg);
            exit(1);
        }

        last_delta = res_end;
        tsub(&last_delta, &now_tv);
	__pmAFregister(&last_delta, NULL, run_done_callback);

        last_stamp = res_end;
    }

    fprintf(stderr, "Archive basename: %s\n", archBase);

#ifndef IS_MINGW
    /* detach yourself from the launching process */
    if (isdaemon)
        setpgid(getpid(), 0);
#endif

    /* set up control port */
    init_ports();
    __pmFD_ZERO(&fds);
    for (i = 0; i < CFD_NUM; ++i) {
	if (ctlfds[i] >= 0)
	    __pmFD_SET(ctlfds[i], &fds);
    }
#ifndef IS_MINGW
    __pmFD_SET(pmcdfd, &fds);
#endif
    if (rsc_fd != -1)
	__pmFD_SET(rsc_fd, &fds);
    numfds = maxfd() + 1;

    if ((sts = do_preamble()) < 0)
	fprintf(stderr, "Warning: problem writing archive preamble: %s\n",
	    pmErrStr(sts));

    sts = 0;		/* default exit status */

    parse_done = 1;	/* enable callback processing */
    __pmAFunblock();

    for ( ; ; ) {
	int		nready;

#ifdef PCP_DEBUG
	if ((pmDebug & DBG_TRACE_APPL2) && (pmDebug & DBG_TRACE_DESPERATE)) {
	    fprintf(stderr, "before __pmSelectRead(%d,...): run_done_alarm=%d vol_switch_alarm=%d log_alarm=%d\n", numfds, run_done_alarm, vol_switch_alarm, log_alarm);
	}
#endif

	niter = 0;
	while (log_alarm && niter++ < 10) {
	    __pmAFblock();
	    log_alarm = 0;
#ifdef PCP_DEBUG
	    if (pmDebug & DBG_TRACE_APPL2)
		fprintf(stderr, "delayed callback: log_alarm\n");
#endif
	    for (tp = tasklist; tp != NULL; tp = tp->t_next) {
		if (tp->t_alarm) {
		    tp->t_alarm = 0;
		    do_work(tp);
		}
	    }
	    __pmAFunblock();
	}

	if (vol_switch_alarm) {
	    __pmAFblock();
	    vol_switch_alarm = 0;
#ifdef PCP_DEBUG
	    if (pmDebug & DBG_TRACE_APPL2)
		fprintf(stderr, "delayed callback: vol_switch_alarm\n");
#endif
	    newvolume(VOL_SW_TIME);
	    __pmAFunblock();
	}

	if (run_done_alarm) {
#ifdef PCP_DEBUG
	    if (pmDebug & DBG_TRACE_APPL2)
		fprintf(stderr, "delayed callback: run_done_alarm\n");
#endif
	    run_done(0, NULL);
	    /*NOTREACHED*/
	}

	__pmFD_COPY(&readyfds, &fds);
	nready = __pmSelectRead(numfds, &readyfds, NULL);

#ifdef PCP_DEBUG
	if ((pmDebug & DBG_TRACE_APPL2) && (pmDebug & DBG_TRACE_DESPERATE)) {
	    fprintf(stderr, "__pmSelectRead(%d,...) done: nready=%d run_done_alarm=%d vol_switch_alarm=%d log_alarm=%d\n", numfds, nready, run_done_alarm, vol_switch_alarm, log_alarm);
	}
#endif

	__pmAFblock();
	if (nready > 0) {

	    /* handle request on control port */
	    for (i = 0; i < CFD_NUM; ++i) {
		if (ctlfds[i] >= 0 && __pmFD_ISSET(ctlfds[i], &readyfds)) {
		    if (control_req(ctlfds[i])) {
			/* new client has connected */
			__pmFD_SET(clientfd, &fds);
			if (clientfd >= numfds)
			    numfds = clientfd + 1;
		    }
		}
	    }
	    if (clientfd >= 0 && __pmFD_ISSET(clientfd, &readyfds)) {
		/* process request from client, save clientfd in case client
		 * closes connection, resetting clientfd to -1
		 */
		int	fd = clientfd;

		if (client_req()) {
		    /* client closed connection */
		    __pmFD_CLR(fd, &fds);
		    __pmCloseSocket(clientfd);
		    clientfd = -1;
		    numfds = maxfd() + 1;
		    qa_case = 0;
		}
	    }
#ifndef IS_MINGW
	    if (pmcdfd >= 0 && __pmFD_ISSET(pmcdfd, &readyfds)) {
		/*
		 * do not expect this, given synchronous commumication with the
		 * pmcd ... either pmcd has terminated, or bogus PDU ... or its
		 * Win32 and we are operating under the different conditions of
		 * our AF.c implementation there, which has to deal with a lack
		 * of signal support on Windows - race condition exists between
		 * this check and the async event timer callback.
		 */
		__pmPDU		*pb;
		__pmPDUHdr	*php;
		sts = __pmGetPDU(pmcdfd, ANY_SIZE, TIMEOUT_NEVER, &pb);
		if (sts <= 0) {
		    if (sts < 0)
			fprintf(stderr, "Error: __pmGetPDU: %s\n", pmErrStr(sts));
		    disconnect(sts);
		}
		else {
		    php = (__pmPDUHdr *)pb;
		    fprintf(stderr, "Error: Unsolicited %s PDU from PMCD\n",
			__pmPDUTypeStr(php->type));
		    disconnect(PM_ERR_IPC);
		}
		if (sts > 0)
		    __pmUnpinPDUBuf(pb);
	    }
#endif
	    if (rsc_fd >= 0 && __pmFD_ISSET(rsc_fd, &readyfds)) {
		/*
		 * some action on the recording session control fd
		 * end-of-file means launcher has quit, otherwise we
		 * expect one of these commands
		 *	V<number>\n	- version
		 *	F<folio>\n	- folio name
		 *	P<name>\n	- launcher's name
		 *	R\n		- launcher can replay
		 *	D\n		- detach from launcher
		 *	Q\n		- quit pmlogger
		 */
		char	rsc_buf[MAXPATHLEN];
		char	*rp = rsc_buf;
		char	myc;
		int	fake_x = 0;

		for (rp = rsc_buf; ; rp++) {
		    if (read(rsc_fd, &myc, 1) <= 0) {
#ifdef PCP_DEBUG
			if (pmDebug & DBG_TRACE_APPL2)
			    fprintf(stderr, "recording session control: eof\n");
#endif
			if (rp != rsc_buf) {
			    *rp = '\0';
			    fprintf(stderr, "Error: incomplete recording session control message: \"%s\"\n", rsc_buf);
			}
			fake_x = 1;
			break;
		    }
		    if (rp >= &rsc_buf[MAXPATHLEN]) {
			fprintf(stderr, "Error: absurd recording session control message: \"%100.100s ...\"\n", rsc_buf);
			fake_x = 1;
			break;
		    }
		    if (myc == '\n') {
			*rp = '\0';
			break;
		    }
		    *rp = myc;
		}

#ifdef PCP_DEBUG
		if (pmDebug & DBG_TRACE_APPL2) {
		    if (fake_x == 0)
			fprintf(stderr, "recording session control: \"%s\"\n", rsc_buf);
		}
#endif

		if (fake_x)
		    do_dialog('X');
		else if (strcmp(rsc_buf, "Q") == 0 ||
		         strcmp(rsc_buf, "D") == 0 ||
			 strcmp(rsc_buf, "?") == 0)
		    do_dialog(rsc_buf[0]);
		else if (rsc_buf[0] == 'F')
		    folio_name = strdup(&rsc_buf[1]);
		else if (rsc_buf[0] == 'P')
		    rsc_prog = strdup(&rsc_buf[1]);
		else if (strcmp(rsc_buf, "R") == 0)
		    rsc_replay = 1;
		else if (rsc_buf[0] == 'V' && rsc_buf[1] == '0') {
		    /*
		     * version 0 of the recording session control ...
		     * this is all we grok at the moment
		     */
		    ;
		}
		else {
		    fprintf(stderr, "Error: illegal recording session control message: \"%s\"\n", rsc_buf);
		    do_dialog('X');
		}
	    }
	}
	else if (vol_switch_flag) {
	    newvolume(VOL_SW_SIGHUP);
	    vol_switch_flag = 0;
	}
	else if (nready < 0 && neterror() != EINTR)
	    fprintf(stderr, "Error: select: %s\n", netstrerror());

	__pmAFunblock();

	if (target_pid && !__pmProcessExists(target_pid))
	    exit(EXIT_SUCCESS);

	if (exit_code)
	    break;
    }
    exit(exit_code);
}
示例#6
0
文件: pmproxy.c 项目: aeppert/pcp
static void
ParseOptions(int argc, char *argv[], int *nports)
{
    int		c;
    int		sts;
    int		usage = 0;

    while ((c = pmgetopt_r(argc, argv, &opts)) != EOF) {
	switch (c) {

	case 'A':   /* disable pmproxy service advertising */
	    __pmServerClearFeature(PM_SERVER_FEATURE_DISCOVERY);
	    break;

	case 'C':	/* path to NSS certificate database */
	    certdb = opts.optarg;
	    break;

	case 'D':	/* debug flag */
	    if ((sts = __pmParseDebug(opts.optarg)) < 0) {
		pmprintf("%s: unrecognized debug flag specification (%s)\n",
			pmProgname, opts.optarg);
		opts.errors++;
	    } else {
		pmDebug |= sts;
	    }
	    break;

	case 'f':	/* foreground, i.e. do _not_ run as a daemon */
	    run_daemon = 0;
	    break;

	case 'i':
	    /* one (of possibly several) interfaces for client requests */
	    __pmServerAddInterface(opts.optarg);
	    break;

	case 'l':
	    /* log file name */
	    logfile = opts.optarg;
	    break;

	case 'L': /* Maximum size for PDUs from clients */
	    sts = (int)strtol(opts.optarg, NULL, 0);
	    if (sts <= 0) {
		pmprintf("%s: -L requires a positive value\n", pmProgname);
		opts.errors++;
	    } else {
		__pmSetPDUCeiling(sts);
	    }
	    break;

	case 'p':
	    if (__pmServerAddPorts(opts.optarg) < 0) {
		pmprintf("%s: -p requires a positive numeric argument (%s)\n",
			pmProgname, opts.optarg);
		opts.errors++;
	    } else {
		*nports += 1;
	    }
	    break;

	case 'P':	/* password file for certificate database access */
	    dbpassfile = opts.optarg;
	    break;

	case 'U':	/* run as user username */
	    username = opts.optarg;
	    break;

	case 'x':
	    fatalfile = opts.optarg;
	    break;

	case '?':
	    usage = 1;
	    break;

	default:
	    opts.errors++;
	    break;
	}
    }

    if (usage || opts.errors || opts.optind < argc) {
	pmUsageMessage(&opts);
	if (usage)
	    exit(0);
	DontStart();
    }
}
示例#7
0
文件: pmnsmerge.c 项目: Aconex/pcp
int
main(int argc, char **argv)
{
    int		sts;
    int		first = 1;
    int		c;
    int		j;
    int		force = 0;
    int		asis = 0;
    int		dupok = 0;
    __pmnsNode	*tmp;

    umask((mode_t)022);		/* anything else is pretty silly */

    while ((c = pmgetopt_r(argc, argv, &opts)) != EOF) {
	switch (c) {

	case 'a':
	    asis = 1;
	    break;

	case 'd':	/* duplicate PMIDs are OK */
	    dupok = 1;
	    break;

	case 'D':	/* debug flag */
	    if ((sts = __pmParseDebug(opts.optarg)) < 0) {
		pmprintf("%s: unrecognized debug flag specification (%s)\n",
		    pmProgname, opts.optarg);
		opts.errors++;
	    } else {
		pmDebug |= sts;
	    }
	    break;

	case 'f':	/* force ... unlink file first */
	    force = 1;
	    break;

	case 'v':
	    verbose++;
	    break;

	case '?':
	default:
	    opts.errors++;
	    break;
	}
    }

    if (opts.errors || opts.optind > argc - 2) {
	pmUsageMessage(&opts);
	exit(1);
    }

    if (force)
	unlink(argv[argc-1]);

    if (access(argv[argc-1], F_OK) == 0) {
	fprintf(stderr, "%s: Error: output PMNS file \"%s\" already exists!\nYou must either remove it first, or use -f\n",
		pmProgname, argv[argc-1]);
	exit(1);
    }

    /*
     * from here on, ignore SIGHUP, SIGINT and SIGTERM to protect
     * the integrity of the new ouput file
     */
    __pmSetSignalHandler(SIGHUP, SIG_IGN);
    __pmSetSignalHandler(SIGINT, SIG_IGN);
    __pmSetSignalHandler(SIGTERM, SIG_IGN);

    if ((outf = fopen(argv[argc-1], "w+")) == NULL) {
	fprintf(stderr, "%s: Error: cannot create output PMNS file \"%s\": %s\n", pmProgname, argv[argc-1], osstrerror());
	exit(1);
    }

    if (!asis)
	sortargs(&argv[opts.optind], argc - opts.optind - 1);

    j = opts.optind;
    while (j < argc-1) {
	if (verbose)
	    printf("%s:\n", argv[j]);

	if ((sts = pmLoadASCIINameSpace(argv[j], dupok)) < 0) {
	    fprintf(stderr, "%s: Error: pmLoadNameSpace(%s): %s\n",
		pmProgname, argv[j], pmErrStr(sts));
	    exit(1);
	}
	{
	    __pmnsTree *t;
	    t = __pmExportPMNS();
	    if (t == NULL) {
	       /* sanity check - shouldn't ever happen */
	       fprintf(stderr, "Exported PMNS is NULL !");
	       exit(1);
	    }
	    tmp = t->root;
	}

	if (first) {
	    root = tmp;
	    first = 0;
	}
	else {
	    pmns_traverse(tmp, 0, "", merge);
	}
	j++;
    }

    pmns_output(root, outf);
    fclose(outf);

    /*
     * now load the merged PMNS to check for errors ...
     */
    if ((sts = pmLoadASCIINameSpace(argv[argc-1], dupok)) < 0) {
	fprintf(stderr, "%s: Error: pmLoadNameSpace(%s): %s\n",
	    pmProgname, argv[argc-1], pmErrStr(sts));
	exit(1);
    }

    exit(0);
}
示例#8
0
int
main(int argc, char *argv[])
{
    int			c;
    int			sts;
    char		*rawfile = NULL;
    int			i;
    int			ctxid;
    int			first = 1;
    int			dflag = 0;
    int			iflag = 0;
    int			Lflag = 0;
    int			lflag = 0;
    int			Mflag = 0;
    int			mflag = 0;
    int			tflag = 0;
    int			vflag = 0;
    int			mode = PM_MODE_FORW;
    __pmContext		*ctxp;
    pmResult		*raw_result;
    pmResult		*skel_result = NULL;
    pmResult		*result;
    struct timeval	done;

    while ((c = pmGetOptions(argc, argv, &opts)) != EOF) {
	switch (c) {

	case 'a':	/* dump everything */
	    dflag = iflag = lflag = mflag = sflag = tflag = 1;
	    break;

	case 'd':	/* dump pmDesc structures */
	    dflag = 1;
	    break;

	case 'i':	/* dump instance domains */
	    iflag = 1;
	    break;

	case 'L':	/* dump label, verbose */
	    Lflag = 1;
	    lflag = 1;
	    break;

	case 'l':	/* dump label */
	    lflag = 1;
	    break;

	case 'm':	/* dump metrics in log */
	    mflag = 1;
	    break;

	case 'M':	/* report <mark> records */
	    Mflag = 1;
	    break;

	case 'r':	/* read log in reverse chornological order */
	    mode = PM_MODE_BACK;
	    break;

	case 's':	/* report data size in log */
	    sflag = 1;
	    break;

	case 't':	/* dump temporal index */
	    tflag = 1;
	    break;

	case 'v':	/* verbose, dump in raw format */
	    vflag = 1;
	    rawfile = opts.optarg;
	    break;

	case 'x':	/* report Ddd Mmm DD <timestamp> YYYY */
			/* -xx reports numeric timeval also */
	    xflag++;
	    break;
	}
    }

    if (opts.errors ||
	(vflag && opts.optind != argc) ||
	(!vflag && opts.optind > argc - 1 && !opts.narchives)) {
	pmUsageMessage(&opts);
	exit(1);
    }

    if (vflag) {
	FILE	*f;
	if ((f = fopen(rawfile, "r")) == NULL) {
	    fprintf(stderr, "%s: Cannot open \"%s\": %s\n", pmProgname, rawfile, osstrerror());
	    exit(1);
	}
	printf("Raw dump of physical archive file \"%s\" ...\n", rawfile);
	rawdump(f);
	exit(0);
    }

    if (dflag + iflag + lflag + mflag + tflag == 0)
	mflag = 1;	/* default */

    /* delay option end processing until now that we have the archive name */
    if (opts.narchives == 0)
	__pmAddOptArchive(&opts, argv[opts.optind++]);
    opts.flags &= ~PM_OPTFLAG_DONE;
    __pmEndOptions(&opts);

    if ((sts = ctxid = pmNewContext(PM_CONTEXT_ARCHIVE, opts.archives[0])) < 0) {
	fprintf(stderr, "%s: Cannot open archive \"%s\": %s\n",
		pmProgname, opts.archives[0], pmErrStr(sts));
	exit(1);
    }
    /* complete TZ and time window option (origin) setup */
    if (pmGetContextOptions(ctxid, &opts)) {
	pmflush();
	exit(1);
    }

    numpmid = argc - opts.optind;
    if (numpmid) {
	numpmid = 0;
	pmid = NULL;
	for (i = 0; opts.optind < argc; i++, opts.optind++) {
	    numpmid++;
	    pmid = (pmID *)realloc(pmid, numpmid * sizeof(pmID));
	    if ((sts = pmLookupName(1, &argv[opts.optind], &pmid[numpmid-1])) < 0) {
		if (sts == PM_ERR_NONLEAF) {
		    numpmid--;
		    if ((sts = pmTraversePMNS(argv[opts.optind], dometric)) < 0)
			fprintf(stderr, "%s: pmTraversePMNS(%s): %s\n",
				pmProgname, argv[opts.optind], pmErrStr(sts));
		}
		else
		    fprintf(stderr, "%s: pmLookupName(%s): %s\n",
			    pmProgname, argv[opts.optind], pmErrStr(sts));
		if (sts < 0)
		    numpmid--;
	    }
	}
	if (numpmid == 0) {
	    fprintf(stderr, "No metric names can be translated, dump abandoned\n");
	    exit(1);
	}
    }

    if ((sts = pmGetArchiveLabel(&label)) < 0) {
	fprintf(stderr, "%s: Cannot get archive label record: %s\n",
		pmProgname, pmErrStr(sts));
	exit(1);
    }

    if (numpmid > 0) {
	/*
	 * setup dummy pmResult
	 */
	skel_result = (pmResult *)malloc(sizeof(pmResult)+(numpmid-1)*sizeof(pmValueSet *));
	if (skel_result == NULL) {
	    fprintf(stderr, "%s: malloc(skel_result): %s\n", pmProgname, osstrerror());
	    exit(1);

	}
    }

    /*
     * Note: ctxp->c_lock remains locked throughout ... __pmHandleToPtr()
     *       is only called once, and a single context is used throughout
     *       ... so there is no PM_UNLOCK(ctxp->c_lock) anywhere in the
     *       pmdumplog code.
     *       This works because ctxp->c_lock is a recursive lock and
     *       pmdumplog is single-threaded.
     */
    if ((ctxp = __pmHandleToPtr(ctxid)) == NULL) {
	fprintf(stderr, "%s: botch: __pmHandleToPtr(%d) returns NULL!\n",
		pmProgname, ctxid);
	exit(1);
    }

    pmSetMode(mode, &opts.start, 0);

    if (lflag)
	dumpLabel(Lflag);

    if (dflag)
	dumpDesc(ctxp);

    if (iflag)
	dumpInDom(ctxp);

    if (tflag)
	dumpTI(ctxp);

    if (mflag) {
	if (mode == PM_MODE_FORW) {
	    if (opts.start_optarg != NULL || opts.finish_optarg != NULL) {
		/* -S or -T */
		sts = pmSetMode(mode, &opts.start, 0);
		done = opts.finish;
	    }
	    else {
		/* read the whole archive */
		done.tv_sec = 0;
		done.tv_usec = 0;
		sts = pmSetMode(mode, &done, 0);
		done.tv_sec = INT_MAX;
	    }
	}
	else {
	    if (opts.start_optarg != NULL || opts.finish_optarg != NULL) {
		/* -S or -T */
		done.tv_sec = INT_MAX;
		done.tv_usec = 0;
		sts = pmSetMode(mode, &done, 0);
		done = opts.start;
	    }
	    else {
		/* read the whole archive backwards */
		done.tv_sec = INT_MAX;
		done.tv_usec = 0;
		sts = pmSetMode(mode, &done, 0);
		done.tv_sec = 0;
	    }
	}
	if (sts < 0) {
	    fprintf(stderr, "%s: pmSetMode: %s\n", pmProgname, pmErrStr(sts));
	    exit(1);
	}
	sts = 0;
	for ( ; ; ) {
	    sts = __pmLogFetch(ctxp, 0, NULL, &raw_result);
	    if (sts < 0)
		break;
	    if (numpmid == 0 || (raw_result->numpmid == 0 && Mflag)) {
		/*
		 * want 'em all or <mark> record ...
		 */
		result = raw_result;
	    }
	    else if (numpmid > 0) {
		/*
		 * cherry pick from raw_result if pmid matches one
		 * of interest
		 */
		int	picked = 0;
		int	j;
		skel_result->timestamp = raw_result->timestamp;
		for (j = 0; j < numpmid; j++)
		    skel_result->vset[j] = NULL;
		for (i = 0; i < raw_result->numpmid; i++) {
		    for (j = 0; j < numpmid; j++) {
			if (pmid[j] == raw_result->vset[i]->pmid) {
			    skel_result->vset[j] = raw_result->vset[i];
			    picked++;
			    break;
			}
		    }
		}
		if (picked == 0) {
		    /* no metrics of interest, skip this record */
		    pmFreeResult(raw_result);
		    continue;
		}
		skel_result->numpmid = picked;
		if (picked != numpmid) {
		    /* did not find 'em all ... shuffle time */
		    int		j;
		    i = 0;
		    for (j = 0; j < numpmid; j++) {
			if (skel_result->vset[j] != NULL)
			    skel_result->vset[i++] = skel_result->vset[j];
		    }
		}
		result = skel_result;
	    }
	    else {
		/* not interesting */
		pmFreeResult(raw_result);
		continue;
	    }
	    if (first && mode == PM_MODE_BACK) {
		first = 0;
		printf("\nLog finished at %24.24s - dump in reverse order\n",
			pmCtime(&result->timestamp.tv_sec, timebuf));
	    }
	    if ((mode == PM_MODE_FORW && tvcmp(result->timestamp, done) > 0) ||
		(mode == PM_MODE_BACK && tvcmp(result->timestamp, done) < 0)) {
		sts = PM_ERR_EOL;
		break;
	    }
	    putchar('\n');
	    dump_result(result);
	    pmFreeResult(raw_result);
	}
	if (sts != PM_ERR_EOL) {
	    fprintf(stderr, "%s: pmFetch: %s\n", pmProgname, pmErrStr(sts));
	    exit(1);
	}
    }

    exit(0);
}
示例#9
0
文件: pmclient.c 项目: ColeJackes/pcp
int
main(int argc, char **argv)
{
    int			c;
    int			sts;
    int			samples;
    int			pauseFlag = 0;
    int			lines = 0;
    char		*source;
    const char		*host;
    info_t		info;		/* values to report each sample */
    char		timebuf[26];	/* for pmCtime result */

    setlinebuf(stdout);

    while ((c = pmGetOptions(argc, argv, &opts)) != EOF) {
	switch (c) {
	case 'P':
	    pauseFlag++;
	    break;
	default:
	    opts.errors++;
	    break;
	}
    }

    if (pauseFlag && opts.context != PM_CONTEXT_ARCHIVE) {
	pmprintf("%s: pause can only be used with archives\n", pmProgname);
	opts.errors++;
    }

    if (opts.errors || opts.optind < argc - 1) {
	pmUsageMessage(&opts);
	exit(1);
    }

    if (opts.context == PM_CONTEXT_ARCHIVE) {
	source = opts.archives[0];
    } else if (opts.context == PM_CONTEXT_HOST) {
	source = opts.hosts[0];
    } else {
	opts.context = PM_CONTEXT_HOST;
	source = "local:";
    }

    if ((sts = c = pmNewContext(opts.context, source)) < 0) {
	if (opts.context == PM_CONTEXT_HOST)
	    fprintf(stderr, "%s: Cannot connect to PMCD on host \"%s\": %s\n",
		    pmProgname, source, pmErrStr(sts));
	else
	    fprintf(stderr, "%s: Cannot open archive \"%s\": %s\n",
		    pmProgname, source, pmErrStr(sts));
	exit(1);
    }

    /* complete TZ and time window option (origin) setup */
    if (pmGetContextOptions(c, &opts)) {
	pmflush();
	exit(1);
    }

    host = pmGetContextHostName(c);
    ncpu = get_ncpu();

    if ((opts.context == PM_CONTEXT_ARCHIVE) &&
	(opts.start.tv_sec != 0 || opts.start.tv_usec != 0)) {
	if ((sts = pmSetMode(PM_MODE_FORW, &opts.start, 0)) < 0) {
	    fprintf(stderr, "%s: pmSetMode failed: %s\n",
		    pmProgname, pmErrStr(sts));
	    exit(1);
	}
    }

    get_sample(&info);

    /* set a default sampling interval if none has been requested */
    if (opts.interval.tv_sec == 0 && opts.interval.tv_usec == 0)
	opts.interval.tv_sec = 5;

    /* set sampling loop termination via the command line options */
    samples = opts.samples ? opts.samples : -1;

    while (samples == -1 || samples-- > 0) {
	if (lines % 15 == 0) {
	    if (opts.context == PM_CONTEXT_ARCHIVE)
		printf("Archive: %s, ", opts.archives[0]);
	    printf("Host: %s, %d cpu(s), %s",
		    host, ncpu,
		    pmCtime((const time_t *)&info.timestamp.tv_sec, timebuf));
/* - report format
  CPU  Busy    Busy  Free Mem   Disk     Load Average
 Util   CPU    Util  (Mbytes)   IOPS    1 Min  15 Min
X.XXX   XXX   X.XXX XXXXX.XXX XXXXXX  XXXX.XX XXXX.XX
*/
	    printf("  CPU");
	    if (ncpu > 1)
		printf("  Busy    Busy");
	    printf("  Free Mem   Disk     Load Average\n");
	    printf(" Util");
	    if (ncpu > 1)
		printf("   CPU    Util");
	    printf("  (Mbytes)   IOPS    1 Min  15 Min\n");
	}
	if (opts.context != PM_CONTEXT_ARCHIVE || pauseFlag)
	    __pmtimevalSleep(opts.interval);
	get_sample(&info);
	printf("%5.2f", info.cpu_util);
	if (ncpu > 1)
	    printf("   %3d   %5.2f", info.peak_cpu, info.peak_cpu_util);
	printf(" %9.3f", info.freemem);
	printf(" %6d", info.dkiops);
	printf("  %7.2f %7.2f\n", info.load1, info.load15);
 	lines++;
    }
    exit(0);
}
示例#10
0
文件: dbpmda.c 项目: ColeJackes/pcp
int
main(int argc, char **argv)
{
    int			c;
    int			sts;
    char		*endnum;

    iflag = isatty(0);

    while ((c = pmgetopt_r(argc, argv, &opts)) != EOF) {
	switch (c) {

	case 'D':		/* debug flag */
	    sts = __pmParseDebug(opts.optarg);
	    if (sts < 0) {
		fprintf(stderr, "%s: unrecognized debug flag specification (%s)\n",
		    pmProgname, opts.optarg);
		opts.errors++;
	    }
	    else
		pmDebug |= sts;
	    break;

	case 'e':		/* echo input */
	    eflag++;
	    break;

	case 'f':		/* skip .dbpmdarc processing */
	    fflag++;
	    break;

	case 'i':		/* be interactive */
	    iflag = 1;
	    break;

	case 'n':		/* alternative name space file */
	    pmnsfile = opts.optarg;
	    break;

	case 'q':
	    sts = (int)strtol(opts.optarg, &endnum, 10);
	    if (*endnum != '\0' || sts <= 0.0) {
		pmprintf("%s: -q requires a positive numeric argument\n",
			pmProgname);
		opts.errors++;
	    } else {
		_creds_timeout = sts;
	    }
	    break;

	case 'U':		/* run under alternate user account */
	    __pmSetProcessIdentity(opts.optarg);
	    break;

	default:
	case '?':
	    opts.errors++;
	    break;
	}
    }

    if ((c = argc - opts.optind) > 0) {
	if (c > 1)
	    opts.errors++;
	else {
	    /* pid was specified */
	    if (primary) {
		pmprintf("%s: you may not specify both -P and a pid\n",
			pmProgname);
		opts.errors++;
	    }
	    else {
		pid = (int)strtol(argv[opts.optind], &endnum, 10);
		if (*endnum != '\0') {
		    pmprintf("%s: pid must be a numeric process id\n",
			    pmProgname);
		    opts.errors++;
		}
	    }
	}
    }

    if (opts.errors) {
	pmUsageMessage(&opts);
	exit(1);
    }

    if (pmnsfile == PM_NS_DEFAULT) {
	if ((sts = pmLoadNameSpace(pmnsfile)) < 0) {
		fprintf(stderr, "%s: Cannot load default namespace: %s\n",
			pmProgname, pmErrStr(sts));
	    exit(1);
	}
    }
    else {
	if ((sts = pmLoadASCIINameSpace(pmnsfile, 1)) < 0) {
		fprintf(stderr, "%s: Cannot load namespace from \"%s\": %s\n",
			pmProgname, pmnsfile, pmErrStr(sts));
	    exit(1);
	}
    }

    /* initialize the "fake context" ... */
    setup_context();

    setlinebuf(stdout);
    setlinebuf(stderr);

#ifdef HAVE_ATEXIT
    atexit(cleanup);
#endif

    for ( ; ; ) {
	initmetriclist();
	yyparse();
	if (yywrap()) {
	    if (iflag)
		putchar('\n');
	    break;
	}

	__pmSetInternalState(PM_STATE_PMCS);

	switch (stmt_type) {

	    case OPEN:
		profile_changed = 1;
		break;

	    case CLOSE:
		switch (connmode) {
		    case CONN_DSO:
			closedso();
			break;
		    
		    case CONN_DAEMON:
			closepmda();
			break;
		    
		    case NO_CONN:
			yywarn("No PMDA currently opened");
			break;
		}
		connmode = NO_CONN;
		break;

	    case DESC:
		switch (connmode) {
		    case CONN_DSO:
			dodso(PDU_DESC_REQ);
			break;
		    
		    case CONN_DAEMON:
			dopmda(PDU_DESC_REQ);
			break;
		    
		    case NO_CONN:
			yywarn("No PMDA currently opened");
			break;
		}
		break;

	    case FETCH:
		switch (connmode) {
		    case CONN_DSO:
			dodso(PDU_FETCH);
			break;
		    
		    case CONN_DAEMON:
			dopmda(PDU_FETCH);
			break;
		    
		    case NO_CONN:
			yywarn("No PMDA currently opened");
			break;
		}
		break;

	    case INSTANCE:
		switch (connmode) {
		    case CONN_DSO:
			dodso(PDU_INSTANCE_REQ);
			break;
		    
		    case CONN_DAEMON:
			dopmda(PDU_INSTANCE_REQ);
			break;
		    
		    case NO_CONN:
			yywarn("No PMDA currently opened");
			break;
		}
		break;

	    case STORE:
		switch (connmode) {
		    case CONN_DSO:
			dodso(PDU_RESULT);
			break;
		    
		    case CONN_DAEMON:
			dopmda(PDU_RESULT);
			break;
		    
		    case NO_CONN:
			yywarn("No PMDA currently opened");
			break;
		}
		break;

	    case HELP:
		dohelp(param.number, param.pmid);
		break;

	    case WATCH:
		break;

	    case DBG:
		pmDebug = param.number;
		break;

	    case QUIT:
		goto done;

	    case STATUS:
		dostatus();
		break;

	    case INFO:
		switch (connmode) {
		case CONN_DSO:
		    dodso(PDU_TEXT_REQ);
		    break;

		case CONN_DAEMON:
		    dopmda(PDU_TEXT_REQ);
		    break;

		case NO_CONN:
		    yywarn("No PMDA currently opened");
		    break;
		}
		break;
	    case NAMESPACE:
		if (cmd_namespace != NULL)
		    free(cmd_namespace);
		cmd_namespace = strdup(param.name);
		if (cmd_namespace == NULL) {
		    fprintf(stderr, "%s: No memory for new namespace\n",
			    pmProgname);
		    exit(1);
		}
		pmUnloadNameSpace();
		strcpy(cmd_namespace, param.name);
		if ((sts = pmLoadASCIINameSpace(cmd_namespace, 1)) < 0) {
		    fprintf(stderr, "%s: Cannot load namespace from \"%s\": %s\n",
			    pmProgname, cmd_namespace, pmErrStr(sts));

		    pmUnloadNameSpace();
		    if (pmnsfile == PM_NS_DEFAULT) {
			fprintf(stderr, "%s: Reload default namespace\n",
				pmProgname);
			if ((sts = pmLoadNameSpace(pmnsfile)) < 0) {
			    fprintf(stderr,
				    "%s: Cannot load default namespace: %s\n",
				    pmProgname, pmErrStr(sts));
			    exit(1);
			}
		    }
		    else {
			fprintf(stderr, "%s: Reload namespace from \"%s\"\n",
				pmProgname, pmnsfile);
			if ((sts = pmLoadASCIINameSpace(pmnsfile, 1)) < 0) {
			    fprintf(stderr,
				    "%s: Cannot load namespace from \"%s\""
				    ": %s\n",
				    pmProgname, pmnsfile, pmErrStr(sts));
			    exit(1);
			}
		    }
		}
		break;

	    case EOL:
		break;

	    case PMNS_NAME:
		switch (connmode) {
		    case CONN_DSO:
			dodso(PDU_PMNS_IDS);
			break;
		    
		    case CONN_DAEMON:
			dopmda(PDU_PMNS_IDS);
			break;
		    
		    case NO_CONN:
			yywarn("No PMDA currently opened");
			break;
		}
		break;

	    case PMNS_PMID:
		switch (connmode) {
		    case CONN_DSO:
			dodso(PDU_PMNS_NAMES);
			break;
		    
		    case CONN_DAEMON:
			dopmda(PDU_PMNS_NAMES);
			break;
		    
		    case NO_CONN:
			yywarn("No PMDA currently opened");
			break;
		}
		break;

	    case PMNS_CHILDREN:
		switch (connmode) {
		    case CONN_DSO:
			dodso(PDU_PMNS_CHILD);
			break;
		    
		    case CONN_DAEMON:
			dopmda(PDU_PMNS_CHILD);
			break;
		    
		    case NO_CONN:
			yywarn("No PMDA currently opened");
			break;
		}
		break;

	    case PMNS_TRAVERSE:
		switch (connmode) {
		    case CONN_DSO:
			dodso(PDU_PMNS_TRAVERSE);
			break;
		    
		    case CONN_DAEMON:
			dopmda(PDU_PMNS_TRAVERSE);
			break;
		    
		    case NO_CONN:
			yywarn("No PMDA currently opened");
			break;
		}
		break;

	    case ATTR:
		switch (connmode) {
		    case CONN_DSO:
			dodso(PDU_AUTH);
			break;
		    
		    case CONN_DAEMON:
			dopmda(PDU_AUTH);
			break;
		    
		    case NO_CONN:
			yywarn("No PMDA currently opened");
			break;
		}
		break;

	    default:
		printf("Unexpected result (%d) from parser?\n", stmt_type);
		break;
	}
	__pmSetInternalState(PM_STATE_APPL);
    }

done:
    cleanup();

    exit(0);
}
示例#11
0
int
main(int argc, char **argv)
{
    int		sep = __pmPathSeparator();
    int		sts;
    int		c;
    char	*p;
    char	pmnsfile[MAXPATHLEN];
    char	outfname[MAXPATHLEN];
    struct stat	sbuf;

    if ((p = getenv("PMNS_DEFAULT")) != NULL) {
	strncpy(pmnsfile, p, MAXPATHLEN);
        pmnsfile[MAXPATHLEN-1]= '\0';

    } else {
	snprintf(pmnsfile, sizeof(pmnsfile), "%s%c" "pmns" "%c" "root",
		pmGetConfig("PCP_VAR_DIR"), sep, sep);
    }

    while ((c = pmgetopt_r(argc, argv, &opts)) != EOF) {
	switch (c) {

	case 'd':	/* duplicate PMIDs are OK */
	    fprintf(stderr, "%s: Warning: -d deprecated, duplicate PMNS names allowed by default\n", pmProgname);
	    break;

	case 'D':	/* debug flag */
	    if ((sts = __pmParseDebug(opts.optarg)) < 0) {
		fprintf(stderr, "%s: unrecognized debug flag specification (%s)\n",
			pmProgname, opts.optarg);
		opts.errors++;
	    } else {
		pmDebug |= sts;
	    }
	    break;

	case 'n':	/* alternative name space file */
	    strncpy(pmnsfile, opts.optarg, MAXPATHLEN);
	    pmnsfile[MAXPATHLEN-1]= '\0';
	    break;

	case '?':
	default:
	    opts.errors++;
	    break;
	}
    }

    if (opts.errors || opts.optind > argc - 1) {
	pmUsageMessage(&opts);
	exit(1);
    }

    if ((sts = pmLoadASCIINameSpace(pmnsfile, 1)) < 0) {
	fprintf(stderr, "%s: Error: pmLoadASCIINameSpace(%s, 1): %s\n",
		pmProgname, pmnsfile, pmErrStr(sts));
	exit(1);
    }

    {
        __pmnsTree *t;
        t = __pmExportPMNS();
        if (t == NULL) {
           /* sanity check - shouldn't ever happen */
           fprintf(stderr, "Exported PMNS is NULL !");
           exit(1);
        }
        root = t->root;
    }


    while (opts.optind < argc) {
	delpmns(root, fullname = argv[opts.optind]);
	opts.optind++;
    }

    /*
     * from here on, ignore SIGHUP, SIGINT and SIGTERM to protect
     * the integrity of the new ouput file
     */
    __pmSetSignalHandler(SIGHUP, SIG_IGN);
    __pmSetSignalHandler(SIGINT, SIG_IGN);
    __pmSetSignalHandler(SIGTERM, SIG_IGN);

    snprintf(outfname, sizeof(outfname), "%s.new", pmnsfile);
    if ((outf = fopen(outfname, "w")) == NULL) {
	fprintf(stderr, "%s: Error: cannot open PMNS file \"%s\" for writing: %s\n",
		pmProgname, outfname, osstrerror());
	exit(1);
    }
    if (stat(pmnsfile, &sbuf) == 0) {
	/*
	 * preserve the mode and ownership of any existing PMNS file
	 */
	chmod(outfname, sbuf.st_mode & ~S_IFMT);
#if defined(HAVE_CHOWN)
	if (chown(outfname, sbuf.st_uid, sbuf.st_gid) < 0)
	    fprintf(stderr, "%s: chown(%s, ...) failed: %s\n",
		    pmProgname, outfname, osstrerror());
#endif
    }

    pmns_output(root, outf);
    fclose(outf);

    /* rename the PMNS */
    if (rename2(outfname, pmnsfile) == -1) {
	fprintf(stderr, "%s: cannot rename \"%s\" to \"%s\": %s\n",
		pmProgname, outfname, pmnsfile, osstrerror());
	/* remove the new PMNS */
	unlink(outfname);
	exit(1);
    }

    exit(0);
}
示例#12
0
文件: pmcpp.c 项目: Aconex/pcp
int
main(int argc, char **argv)
{
    int		c;
    int		skip_if_false = 0;
    int		incomment = 0;
    char	*ip;

    currfile = &file_ctl[0];

    while ((c = pmgetopt_r(argc, argv, &opts)) != EOF) {
	switch (c) {

	case 'D':	/* define */
	    for (ip = opts.optarg; *ip; ip++) {
		if (*ip == '=')
		    *ip = ' ';
	    }
	    snprintf(ibuf, sizeof(ibuf), "#define %s\n", opts.optarg);
	    currfile->fname = "<arg>";
	    currfile->lineno = opts.optind;
	    directive();
	    break;

	case '?':
	default:
	    opts.errors++;
	    break;
	}
    }

    if (opts.errors || opts.optind < argc - 1) {
	pmUsageMessage(&opts);
	exit(1);
    }

    currfile->lineno = 0;
    if (opts.optind == argc) {
	currfile->fname = "<stdin>";
	currfile->fin = stdin;
    }
    else {
	currfile->fname = argv[opts.optind];
	currfile->fin = openfile(currfile->fname);
	if (currfile->fin == NULL) {
	    err((char *)pmErrStr(-oserror()));
	    /*NOTREACHED*/
	}
    }
    printf("# %d \"%s\"\n", currfile->lineno+1, currfile->fname);

    for ( ; ; ) {
	if (fgets(ibuf, sizeof(ibuf), currfile->fin) == NULL) {
	    fclose(currfile->fin);
	    if (currfile == &file_ctl[0])
		break;
	    free(currfile->fname);
	    currfile--;
	    printf("# %d \"%s\"\n", currfile->lineno+1, currfile->fname);
	    continue;
	}
	currfile->lineno++;
 
	/* strip comments ... */
	for (ip = ibuf; *ip ; ip++) {
	    if (incomment) {
		if (*ip == '*' && ip[1] == '/') {
		    /* end of comment */
		    incomment = 0;
		    *ip++ = ' ';
		    *ip = ' ';
		}
		else
		    *ip = ' ';
	    }
	    else {
		if (*ip == '/' && ip[1] == '*') {
		    /* start of comment */
		    incomment = currfile->lineno;
		    *ip++ = ' ';
		    *ip = ' ';
		}
	    }
	}
	ip--;
	while (ip >= ibuf && isspace((int)*ip)) ip--;
	*++ip = '\n';
	*++ip = '\0';
	if (incomment && ibuf[0] == '\n') {
	    printf("\n");
	    continue;
	}

	if (ibuf[0] == '#') {
	    /* cpp control line */
	    if (strncmp(ibuf, "#include", strlen("#include")) == 0) {
		char		*p;
		char		*pend;
		char		c;
		FILE		*f;
		static char	tmpbuf[MAXPATHLEN];

		if (skip_if_false) {
		    printf("\n");
		    continue;
		}
		p = &ibuf[strlen("#include")];
		while (*p && isblank((int)*p)) p++;
		if (*p != '"' && *p != '<') {
		    err("Expected \" or < after #include");
		    /*NOTREACHED*/
		}
		pend = ++p;
		while (*pend && *pend != '\n' &&
		       ((p[-1] != '"' || *pend != '"') &&
		        (p[-1] != '<' || *pend != '>'))) pend++;
		if (p[-1] == '"' && *pend != '"') {
		    err("Expected \" after file name");
		    /*NOTREACHED*/
		}
		if (p[-1] == '<' && *pend != '>') {
		    err("Expected > after file name");
		    /*NOTREACHED*/
		}
		if (currfile == &file_ctl[MAXLEVEL-1]) {
		    err("#include nesting too deep");
		    /*NOTREACHED*/
		}
		if (pend[1] != '\n' && pend[1] != '\0') {
		    err("Unexpected extra text in #include line");
		    /*NOTREACHED*/
		}
		c = *pend;
		*pend = '\0';
		f = openfile(p);
		if (f == NULL && file_ctl[0].fin != stdin) {
		    /* check in directory of file from command line */
		    static int	sep;
		    static char	*dir = NULL;
		    if (dir == NULL) {
			/*
			 * some versions of dirname() clobber the input
			 * argument, some do not ... hence the obscurity
			 * here
			 */
			static char	*dirbuf;
			dirbuf = strdup(file_ctl[0].fname);
			if (dirbuf == NULL) {
			    __pmNoMem("pmcpp: dir name alloc", strlen(file_ctl[0].fname)+1, PM_FATAL_ERR);
			    /*NOTREACHED*/
			}
			dir = dirname(dirbuf);
			sep = __pmPathSeparator();
		    }
		    snprintf(tmpbuf, sizeof(tmpbuf), "%s%c%s", dir, sep, p);
		    f = openfile(tmpbuf);
		    if (f != NULL)
			p = tmpbuf;
		}
		if (f == NULL) {
		    /* check in $PCP_VAR_DIR/pmns */
		    static int	sep;
		    static char	*var_dir = NULL;
		    if (var_dir == NULL) {
			var_dir = pmGetConfig("PCP_VAR_DIR");
			sep = __pmPathSeparator();
		    }
		    snprintf(tmpbuf, sizeof(tmpbuf), "%s%cpmns%c%s", var_dir, sep, sep, p);
		    f = openfile(tmpbuf);
		    if (f != NULL)
			p = tmpbuf;
		}
		if (f == NULL) {
		    *pend = c;
		    err("Cannot open file for #include");
		    /*NOTREACHED*/
		}
		currfile++;
		currfile->lineno = 0;
		currfile->fin = f;
		currfile->fname = strdup(p);
		*pend = c;
		if (currfile->fname == NULL) {
		    __pmNoMem("pmcpp: file name alloc", strlen(p)+1, PM_FATAL_ERR);
		    /*NOTREACHED*/
		}
		printf("# %d \"%s\"\n", currfile->lineno+1, currfile->fname);
	    }
	    else {
		/* expect other cpp control ... */
		skip_if_false = directive();
		printf("\n");
	    }
	    continue;
	}
	if (skip_if_false)
	    printf("\n");
	else {
	    if (nmacro > 0)
		do_macro();
	    printf("%s", ibuf);
	}
    }

    /* EOF for the top level file */
    if (incomment) {
	char	msgbuf[80];
	snprintf(msgbuf, sizeof(msgbuf), "Comment at line %d not terminated before end of file", incomment);
	currfile->lineno = 0;
	err(msgbuf);
	exit(1);
    }

    exit(0);
}
示例#13
0
文件: newhelp.c 项目: Aconex/pcp
int
main(int argc, char **argv)
{
    int		n;
    int		c;
    int		i;
    int		sts;
    char	*pmnsfile = PM_NS_DEFAULT;
    char	*fname = NULL;
    char	pathname[MAXPATHLEN];
    FILE	*inf;
    char	buf[MAXENTRY+MAXLINE];
    char	*endnum;
    char	*bp;
    char	*p;
    int		skip;
    help_idx_t	hdr;

    while ((c = pmgetopt_r(argc, argv, &opts)) != EOF) {
	switch (c) {

	case 'D':	/* debug flag */
	    if ((sts = __pmParseDebug(opts.optarg)) < 0) {
		pmprintf("%s: unrecognized debug flag specification (%s)\n",
		    pmProgname, opts.optarg);
		opts.errors++;
	    }
	    else
		pmDebug |= sts;
	    break;

	case 'n':	/* alternative namespace file */
	    pmnsfile = opts.optarg;
	    break;

	case 'o':	/* alternative output file name */
	    fname = opts.optarg;
	    break;

	case 'V':	/* more chit-chat */
	    verbose++;
	    break;

	case 'v':	/* version 2 only these days */
	    version = (int)strtol(opts.optarg, &endnum, 10);
	    if (*endnum != '\0') {
		pmprintf("%s: -v requires numeric argument\n", pmProgname);
		opts.errors++;
	    }
	    if (version != 2) {
		pmprintf("%s: deprecated option - only version 2 is supported\n",
			pmProgname);
		opts.errors++;
	    }
	    break;

	case '?':
	default:
	    opts.errors++;
	    break;
	}
    }

    if (opts.errors) {
	pmUsageMessage(&opts);
	exit(2);
    }

    if ((n = pmLoadNameSpace(pmnsfile)) < 0) {
	fprintf(stderr, "%s: pmLoadNameSpace: %s\n", pmProgname, pmErrStr(n));
	exit(2);
    }

    do {
	if (opts.optind < argc) {
	    filename = argv[opts.optind];
	    if ((inf = fopen(filename, "r")) == NULL) {
		perror(filename);
		exit(2);
	    }
	    if (fname == NULL)
		fname = filename;
	}
	else {
	    if (fname == NULL) {
		fprintf(stderr, 
			"%s: need either a -o option or a filename "
			"argument to name the output file\n", pmProgname);
		exit(2);
	    }
	    filename = "<stdin>";
	    inf = stdin;
	}

	if (version == 2 && f == NULL) {
	    sprintf(pathname, "%s.pag", fname);
	    if ((f = fopen(pathname, "w")) == NULL) {
		fprintf(stderr, "%s: fopen(\"%s\", ...) failed: %s\n",
		    pmProgname, pathname, osstrerror());
		exit(2);
	    }
	    /* header: 2 => pag cf 1 => dir */
	    fprintf(f, "PcPh2%c\n", '0' + version);
	}

	bp = buf;
	skip = 1;
	for ( ; ; ) {
	    if (fgets(bp, MAXLINE, inf) == NULL) {
		skip = -1;
		*bp = '@';
	    }
	    ln++;
	    if (bp[0] == '#')
		continue;
	    if (bp[0] == '@') {
		/* start of a new entry */
		if (bp > buf) {
		    /* really have a prior entry */
		    p = bp - 1;
		    while (p > buf && *p == '\n')
			p--;
		    *++p = '\n';
		    *++p = '\0';
		    newentry(buf);
		}
		if (skip == -1)
		    break;
		skip = 0;
		bp++;	/* skip '@' */
		while (*bp && isspace((int)*bp))
		    bp++;
		if (bp[0] == '\0') {
		    if (verbose)
			fprintf(stderr, "%s: [%s:%d] null entry?\n", 
				pmProgname, filename, ln);
		    skip = 1;
		    bp = buf;
		    if (!status) status = 1;
		}
		else {
		    for (p = bp; *p; p++)
			;
		    memmove(buf, bp, p - bp + 1);
		    for (bp = buf; *bp; bp++)
			;
		}
	    }
	    if (skip)
		continue;
	    for (p = bp; *p; p++)
		;
	    if (bp > buf && p[-1] != '\n') {
		*p++ = '\n';
		*p = '\0';
		fprintf(stderr, "%s: [%s:%d] long line split after ...\n%s",
			    pmProgname, filename, ln, buf);
		ln--;
		if (!status) status = 1;
	    }
	    bp = p;
	    if (bp > &buf[MAXENTRY]) {
		bp = &buf[MAXENTRY];
		bp[-1] = '\0';
		bp[-2] = '\n';
		fprintf(stderr, "%s: [%s:%d] entry truncated after ... %s",
			    pmProgname, filename, ln, &bp[-64]);
		skip = 1;
		if (!status) status = 1;
	    }
	}

	fclose(inf);
	opts.optind++;
    } while (opts.optind < argc);

    if (f != NULL) {
	fclose(f);

	/* do the directory index ... */
	sprintf(pathname, "%s.dir", fname);
	if ((f = fopen(pathname, "w")) == NULL) {
	    fprintf(stderr, "%s: fopen(\"%s\", ...) failed: %s\n",
		pmProgname, pathname, osstrerror());
	    exit(2);
	}

	/* index header */
	hdr.pmid = 0x50635068;		/* "PcPh" */
	/* "1" => dir, next char is version */
	hdr.off_oneline = 0x31000000 | (('0' + version) << 16);
	hdr.off_text = thisindex + 1;	/* # entries */
	if (fwrite(&hdr, sizeof(hdr), 1, f) != 1 || ferror(f)) {
	     fprintf(stderr, "%s: fwrite index failed: %s\n",
		     pmProgname, osstrerror());
	     exit(2);
	}

	/* sort and write index */
	qsort((void *)hindex, thisindex+1, sizeof(hindex[0]), idcomp);
	for (i = 0; i <= thisindex; i++) {
	    if (fwrite(&hindex[i], sizeof(hindex[0]), 1, f) != 1
		|| ferror(f)) {
		 fprintf(stderr, "%s: fwrite index failed: %s\n",
			 pmProgname, osstrerror());
		 exit(2);
	    }
	}
    }

    exit(status);
}
示例#14
0
static void
ParseOptions(int argc, char *argv[], int *nports)
{
    int		c;
    int		sts;
    char	*endptr;
    int		usage = 0;
    int		val;

    endptr = pmGetConfig("PCP_PMCDCONF_PATH");
    strncpy(configFileName, endptr, sizeof(configFileName)-1);

    while ((c = pmgetopt_r(argc, argv, &opts)) != EOF) {
	switch (c) {

	    case 'A':	/* disable pmcd service advertising */
		__pmServerClearFeature(PM_SERVER_FEATURE_DISCOVERY);
		break;

	    case 'c':	/* configuration file */
		strncpy(configFileName, opts.optarg, sizeof(configFileName)-1);
		break;

	    case 'C':	/* path to NSS certificate database */
		certdb = opts.optarg;
		break;

	    case 'D':	/* debug flag */
		sts = __pmParseDebug(opts.optarg);
		if (sts < 0) {
		    pmprintf("%s: unrecognized debug flag specification (%s)\n",
			pmProgname, opts.optarg);
		    opts.errors++;
		}
		pmDebug |= sts;
		break;

	    case 'f':
		/* foreground, i.e. do _not_ run as a daemon */
		run_daemon = 0;
		break;

	    case 'i':
		/* one (of possibly several) interfaces for client requests */
		__pmServerAddInterface(opts.optarg);
		break;

	    case 'H':
		/* use the given name as the pmcd.hostname for this host */
		_pmcd_hostname = opts.optarg;
		break;

	    case 'l':
		/* log file name */
		logfile = opts.optarg;
		break;

	    case 'L': /* Maximum size for PDUs from clients */
		val = (int)strtol(opts.optarg, NULL, 0);
		if (val <= 0) {
		    pmprintf("%s: -L requires a positive value\n", pmProgname);
		    opts.errors++;
		} else {
		    __pmSetPDUCeiling(val);
		}
		break;

	    case 'N':
		dupok = 0;
		/*FALLTHROUGH*/
	    case 'n':
	    	/* name space file name */
		pmnsfile = opts.optarg;
		break;

	    case 'p':
		if (__pmServerAddPorts(opts.optarg) < 0) {
		    pmprintf("%s: -p requires a positive numeric argument (%s)\n",
			pmProgname, opts.optarg);
		    opts.errors++;
		} else {
		    *nports += 1;
		}
		break;
		    
	    case 'P':	/* password file for certificate database access */
		dbpassfile = opts.optarg;
		break;

	    case 'q':
		val = (int)strtol(opts.optarg, &endptr, 10);
		if (*endptr != '\0' || val <= 0.0) {
		    pmprintf("%s: -q requires a positive numeric argument\n",
			pmProgname);
		    opts.errors++;
		} else {
		    _creds_timeout = val;
		}
		break;

	    case 's':	/* path to local unix domain socket */
		snprintf(sockpath, sizeof(sockpath), "%s", opts.optarg);
		break;

	    case 'S':	/* only allow authenticated clients */
		__pmServerSetFeature(PM_SERVER_FEATURE_CREDS_REQD);
		break;

	    case 't':
		val = (int)strtol(opts.optarg, &endptr, 10);
		if (*endptr != '\0' || val < 0.0) {
		    pmprintf("%s: -t requires a positive numeric argument\n",
			pmProgname);
		    opts.errors++;
		} else {
		    _pmcd_timeout = val;
		}
		break;

	    case 'T':
		val = (int)strtol(opts.optarg, &endptr, 10);
		if (*endptr != '\0' || val < 0) {
		    pmprintf("%s: -T requires a positive numeric argument\n",
			pmProgname);
		    opts.errors++;
		} else {
		    _pmcd_trace_mask = val;
		}
		break;

	    case 'U':
		username = opts.optarg;
		break;

	    case 'x':
		fatalfile = opts.optarg;
		break;

	    case '?':
		usage = 1;
		break;

	    default:
		opts.errors++;
		break;
	}
    }

    if (usage || opts.errors || opts.optind < argc) {
	pmUsageMessage(&opts);
	if (usage)
	    exit(0);
	DontStart();
    }
}
示例#15
0
文件: pmstore.c 项目: Aconex/pcp
int
main(int argc, char **argv)
{
    int		sts;
    int		n;
    int		c;
    int		i;
    char	*p;
    char	*source;
    char	*namelist[1];
    pmID	pmidlist[1];
    pmResult	*result;
    char	**instnames = NULL;
    int		numinst = 0;
    int		force = 0;
    pmDesc	desc;
    pmAtomValue	nav;
    pmValueSet	*vsp;
    char        *subopt;

    while ((c = pmGetOptions(argc, argv, &opts)) != EOF) {
	switch (c) {
        case 'f':
            force++;
            break;

	case 'i':	/* list of instances */
#define WHITESPACE ", \t\n"
	    subopt = strtok(opts.optarg, WHITESPACE);
	    while (subopt != NULL) {
		numinst++;
		n = numinst * sizeof(char *);
		instnames = (char **)realloc(instnames, n);
		if (instnames == NULL)
		    __pmNoMem("pmstore.instnames", n, PM_FATAL_ERR);
		instnames[numinst-1] = subopt;
		subopt = strtok(NULL, WHITESPACE);
	    }
#undef WHITESPACE
	    break;

	default:
	    opts.errors++;
	    break;
	}
    }

    if (opts.errors || opts.optind != argc - 2) {
	pmUsageMessage(&opts);
	exit(1);
    }

    if (opts.context == PM_CONTEXT_HOST)
	source = opts.hosts[0];
    else if (opts.context == PM_CONTEXT_LOCAL)
	source = NULL;
    else {
	opts.context = PM_CONTEXT_HOST;
	source = "local:";
    }
    if ((sts = pmNewContext(opts.context, source)) < 0) {
	if (opts.context == PM_CONTEXT_LOCAL)
	    fprintf(stderr, "%s: Cannot make standalone local connection: %s\n",
		    pmProgname, pmErrStr(sts));
	else
	    fprintf(stderr, "%s: Cannot connect to PMCD on host \"%s\": %s\n",
		    pmProgname, source, pmErrStr(sts));
	exit(1);
    }

    namelist[0] = argv[opts.optind++];
    if ((n = pmLookupName(1, namelist, pmidlist)) < 0) {
	printf("%s: pmLookupName: %s\n", namelist[0], pmErrStr(n));
	exit(1);
    }
    if (pmidlist[0] == PM_ID_NULL) {
	printf("%s: unknown metric\n", namelist[0]);
	exit(1);
    }
    if ((n = pmLookupDesc(pmidlist[0], &desc)) < 0) {
	printf("%s: pmLookupDesc: %s\n", namelist[0], pmErrStr(n));
	exit(1);
    }
    if (desc.type == PM_TYPE_AGGREGATE || desc.type == PM_TYPE_AGGREGATE_STATIC) {
	fprintf(stderr, "%s: Cannot modify values for PM_TYPE_AGGREGATE metrics\n",
	    pmProgname);
	exit(1);
    }
    if (desc.type == PM_TYPE_EVENT || desc.type == PM_TYPE_HIGHRES_EVENT) {
	fprintf(stderr, "%s: Cannot modify values for event type metrics\n",
	    pmProgname);
	exit(1);
    }
    if (instnames != NULL) {
	pmDelProfile(desc.indom, 0, NULL);
	for (i = 0; i < numinst; i++) {
	    if ((n = pmLookupInDom(desc.indom, instnames[i])) < 0) {
		printf("pmLookupInDom %s[%s]: %s\n",
		    namelist[0], instnames[i], pmErrStr(n));
		exit(1);
	    }
	    if ((sts = pmAddProfile(desc.indom, 1, &n)) < 0) {
		printf("pmAddProfile %s[%s]: %s\n",
		    namelist[0], instnames[i], pmErrStr(sts));
		exit(1);
	    }
	}
    }
    if ((n = pmFetch(1, pmidlist, &result)) < 0) {
	printf("%s: pmFetch: %s\n", namelist[0], pmErrStr(n));
	exit(1);
    }

    /* value is argv[opts.optind] */
    mkAtom(&nav, desc.type, argv[opts.optind]);

    vsp = result->vset[0];
    if (vsp->numval < 0) {
	printf("%s: Error: %s\n", namelist[0], pmErrStr(vsp->numval));
	exit(1);
    }

    if (vsp->numval == 0) {
        if (!force) {
            printf("%s: No value(s) available!\n", namelist[0]);
            exit(1);
        }
        else {
            pmAtomValue tmpav;

            mkAtom(&tmpav, PM_TYPE_STRING, "(none)");

            vsp->numval = 1;
            vsp->valfmt = __pmStuffValue(&tmpav, &vsp->vlist[0], PM_TYPE_STRING);
        }
    }

    for (i = 0; i < vsp->numval; i++) {
	pmValue	*vp = &vsp->vlist[i];
	printf("%s", namelist[0]);
	if (desc.indom != PM_INDOM_NULL) {
	    if ((n = pmNameInDom(desc.indom, vp->inst, &p)) < 0)
		printf(" inst [%d]", vp->inst);
	    else {
		printf(" inst [%d or \"%s\"]", vp->inst, p);
		free(p);
	    }
	}
	printf(" old value=");
	pmPrintValue(stdout, vsp->valfmt, desc.type, vp, 1);
	vsp->valfmt = __pmStuffValue(&nav, &vsp->vlist[i], desc.type);
	printf(" new value=");
	pmPrintValue(stdout, vsp->valfmt, desc.type, vp, 1);
	putchar('\n');
    }
    if ((n = pmStore(result)) < 0) {
	printf("%s: pmStore: %s\n", namelist[0], pmErrStr(n));
	exit(1);
    }
    pmFreeResult(result);
    exit(0);
}
示例#16
0
int
main(int argc, char *argv[])
{
    int			c;
    int			sts;
    int			ctx;
    int			i;
    int			lflag = 0;	/* no label by default */
    int			nfile;
    int			n;
    char		*p;
    struct dirent	**namelist;
    __pmContext		*ctxp;
    char		*archpathname;	/* from the command line */
    char		*archdirname;	/* after dirname() */
    char		archname[MAXPATHLEN];	/* full pathname to base of archive name */

    while ((c = pmGetOptions(argc, argv, &opts)) != EOF) {
	switch (c) {
	case 'l':	/* display the archive label */
	    lflag = 1;
	    break;
	case 'v':	/* bump verbosity */
	    vflag++;
	    break;
	}
    }

    if (!opts.errors && opts.optind >= argc) {
	pmprintf("Error: no archive specified\n\n");
	opts.errors++;
    }

    if (opts.errors) {
	pmUsageMessage(&opts);
	exit(EXIT_FAILURE);
    }

    sep = __pmPathSeparator();
    setlinebuf(stderr);

    __pmAddOptArchive(&opts, argv[opts.optind]);
    opts.flags &= ~PM_OPTFLAG_DONE;
    __pmEndOptions(&opts);

    archpathname = argv[opts.optind];
    archbasename = strdup(basename(strdup(archpathname)));
    /*
     * treat foo, foo.index, foo.meta, foo.NNN as all equivalent
     * to "foo"
     */
    p = strrchr(archbasename, '.');
    if (p != NULL) {
	if (strcmp(p, ".index") == 0 || strcmp(p, ".meta") == 0)
	    *p = '\0';
	else {
	    char	*q = p;
	    q++;
	    if (isdigit(*q)) {
		/*
		 * foo.<digit> ... if archpathname does exist, then
		 * safe to strip digits, else leave as is for the
		 * case of, e.g. archive-20150415.041154 which is the
		 * pmmgr basename for an archive with a first volume
		 * named archive-20150415.041154.0
		 */
		if (access(archpathname, F_OK) == 0) {
		    q++;
		    while (*q && isdigit(*q))
			q++;
		    if (*q == '\0')
			*p = '\0';
		}
	    }
	}
    }
    archdirname = dirname(strdup(archpathname));
    if (vflag)
	fprintf(stderr, "Scanning for components of archive \"%s\"\n", archpathname);
    nfile = scandir(archdirname, &namelist, filter, NULL);
    if (nfile < 1) {
	fprintf(stderr, "%s: no PCP archive files match \"%s\"\n", pmProgname, archpathname);
	exit(EXIT_FAILURE);
    }

    /*
     * Pass 0 for data, metadata and index files ... check physical
     * archive record structure, then label record
     */
    sts = STS_OK;
    for (i = 0; i < nfile; i++) {
	char	path[MAXPATHLEN];
	if (strcmp(archdirname, ".") == 0) {
	    /* skip ./ prefix */
	    strncpy(path, namelist[i]->d_name, sizeof(path));
	}
	else {
	    snprintf(path, sizeof(path), "%s%c%s", archdirname, sep, namelist[i]->d_name);
	}
	if (pass0(path) == STS_FATAL)
	    /* unrepairable or unrepaired error */
	    sts = STS_FATAL;
    }
    if (meta_state == STATE_MISSING) {
	fprintf(stderr, "%s%c%s.meta: missing metadata file\n", archdirname, sep, archbasename);
	sts = STS_FATAL;
    }
    if (log_state == STATE_MISSING) {
	fprintf(stderr, "%s%c%s.0 (or similar): missing log file \n", archdirname, sep, archbasename);
	sts = STS_FATAL;
    }

    if (sts == STS_FATAL) {
	if (vflag) fprintf(stderr, "Due to earlier errors, cannot continue ... bye\n");
	exit(EXIT_FAILURE);
    }

    if ((sts = ctx = pmNewContext(PM_CONTEXT_ARCHIVE, archpathname)) < 0) {
	fprintf(stderr, "%s: cannot open archive \"%s\": %s\n", pmProgname, archpathname, pmErrStr(sts));
	fprintf(stderr, "Checking abandoned.\n");
	exit(EXIT_FAILURE);
    }

    if (pmGetContextOptions(ctx, &opts) < 0) {
        pmflush();      /* runtime errors only at this stage */
        exit(EXIT_FAILURE);
    }

    if (lflag)
	dumpLabel();

    /*
     * Note: ctxp->c_lock remains locked throughout ... __pmHandleToPtr()
     *       is only called once, and a single context is used throughout
     *       ... so there is no PM_UNLOCK(ctxp->c_lock) anywhere in the
     *       pmchecklog code.
     *       This works because ctxp->c_lock is a recursive lock and
     *       pmchecklog is single-threaded.
     */
    if ((n = pmWhichContext()) >= 0) {
	if ((ctxp = __pmHandleToPtr(n)) == NULL) {
	    fprintf(stderr, "%s: botch: __pmHandleToPtr(%d) returns NULL!\n", pmProgname, n);
	    exit(EXIT_FAILURE);
	}
    }
    else {
	fprintf(stderr, "%s: botch: %s!\n", pmProgname, pmErrStr(PM_ERR_NOCONTEXT));
	exit(EXIT_FAILURE);
    }

    if (strcmp(archdirname, ".") == 0)
	/* skip ./ prefix */
	strncpy(archname, archbasename, sizeof(archname) - 1);
    else
	snprintf(archname, sizeof(archname), "%s%c%s", archdirname, sep, archbasename);

    sts = pass1(ctxp, archname);

    if (index_state == STATE_BAD) {
	/* prevent subsequent use of bad temporal index */
	ctxp->c_archctl->ac_log->l_numti = 0;
    }

    sts = pass2(ctxp, archname);

    sts = pass3(ctxp, archname, &opts);

    if (vflag) {
	if (result_count > 0)
	    fprintf(stderr, "Processed %d pmResult records\n", result_count);
	if (mark_count > 0)
	    fprintf(stderr, "Processed %d <mark> records\n", mark_count);
    }

    return 0;
}
示例#17
0
文件: template.c 项目: goodwinos/pcp
int
main(int argc, char **argv)
{
    int		c;
    char	*p;
    int		ctx;
    int		sts;
    char 	*configfile = NULL;
    int		fflag = 0;
    int		iflag = 0;
    int		lflag = 0;

    pmSetProgname(argv[0]);

    while ((c = pmGetOptions(argc, argv, &opts)) != EOF) {
	switch (c) {

	case 'c':	/* my configfile */
	    if (configfile != NULL) {
		fprintf(stderr, "%s: at most one -c option allowed\n", pmGetProgname());
		exit(EXIT_FAILURE);
	    }
	    configfile = opts.optarg;
	    break;	

	case 'f':	/* my flag */
	    fflag++;
	    break;

	case 'i':	/* my instances */
	    iflag++;
	    /* TODO extract instances from opts.optarg */
	    break;

	case 'l':	/* my logfile */
	    if (lflag) {
		fprintf(stderr, "%s: at most one -l option allowed\n", pmGetProgname());
		exit(EXIT_FAILURE);
	    }
	    pmOpenLog(pmGetProgname(), opts.optarg, stderr, &sts);
	    if (sts != 1) {
		fprintf(stderr, "%s: Could not open logfile \"%s\"\n", pmGetProgname(), opts.optarg);
		exit(EXIT_FAILURE);
	    }
	    lflag++;
	    break;	

	}
    }

    if (opts.flags & PM_OPTFLAG_EXIT) {
	pmflush();
	pmUsageMessage(&opts);
	exit(0);
    }

    if (opts.narchives == 1) {
	if ((ctx = pmNewContext(PM_CONTEXT_ARCHIVE, opts.archives[0])) < 0) {
	    fprintf(stderr, "%s: Cannot open archive \"%s\": %s\n",
		    pmGetProgname(), opts.archives[0],  pmErrStr(ctx));
	    exit(EXIT_FAILURE);
	}
	if ((sts = pmGetContextOptions(ctx, &opts)) < 0) {
	    pmflush();
	    fprintf(stderr, "%s: pmGetContextOptions(%d, ...) failed: %s\n",
			pmGetProgname(), pmWhichContext(), pmErrStr(sts));
		exit(EXIT_FAILURE);
	}
    }
    else if (opts.narchives > 0) {
	fprintf(stderr, "%s: at most one archive allowed\n", pmGetProgname());
	exit(EXIT_FAILURE);
    }

    if (opts.nhosts == 1) {
	if ((ctx = pmNewContext(PM_CONTEXT_HOST, opts.hosts[0])) < 0) {
	    fprintf(stderr, "%s: Cannot connect to pmcd on host \"%s\": %s\n",
		    pmGetProgname(), opts.hosts[0],  pmErrStr(ctx));
	    exit(EXIT_FAILURE);
	}
    }
    else if (opts.nhosts > 0) {
	fprintf(stderr, "%s: at most one host allowed\n", pmGetProgname());
	exit(EXIT_FAILURE);
    }

    if (opts.errors) {
	pmUsageMessage(&opts);
	exit(EXIT_FAILURE);
    }

    if (opts.align_optarg != NULL)
	printf("Got -A \"%s\"\n", opts.align_optarg);

    if (opts.guiflag)
	printf("Got -g\n");

    if (opts.nsflag)
	printf("Loaded PMNS\n");

    if (opts.guiport)
	printf("Got -p \"%s\"\n", opts.guiport_optarg);

    if (opts.align_optarg != NULL || opts.start_optarg != NULL ||
        opts.finish_optarg != NULL || opts.origin_optarg != NULL) {
	printf("Start time: ");
	pmPrintStamp(stdout, &opts.start);
	putchar('\n');
	printf("Origin time: ");
	pmPrintStamp(stdout, &opts.origin);
	putchar('\n');
	printf("Finish time: ");
	pmPrintStamp(stdout, &opts.finish);
	putchar('\n');
    }

    if (sflag)
	printf("Got -s \"%d\"\n", opts.samples);

    if (opts.interval.tv_sec > 0 || opts.interval.tv_usec > 0)
	printf("Got -t %d.%06d (secs)\n",
		(int)opts.interval.tv_sec, (int)opts.interval.tv_usec);

    p = getenv("PCP_CONTAINER");
    if (p != NULL)
	printf("Got --container=\"%s\"\n", p);

    if (opts.timezone != NULL)
	printf("Got -Z \"%s\"\n", opts.timezone);

    if (opts.tzflag)
	printf("Got -z\n");

    if (opts.Lflag)
	printf("Got -L\n");

    /* non-flag args are argv[optind] ... argv[argc-1] */
    while (opts.optind < argc) {
	printf("extra argument[%d]: %s\n", opts.optind, argv[opts.optind]);
	opts.optind++;
    }

    while (!sflag || opts.samples-- > 0) {
	/* put real stuff here */
	break;
    }

    return 0;
}
示例#18
0
int
main(int argc, char **argv)
{
    int			c;
    int			sts;
    int			samples;
    int			pauseFlag = 0;
    int			lines = 0;
    char		*source;
    const char		*host;
    char		timebuf[26];	/* for pmCtime result */

    setlinebuf(stdout);

    while ((c = pmGetOptions(argc, argv, &opts)) != EOF) {
	switch (c) {
	case 'P':
	    pauseFlag++;
	    break;
	default:
	    opts.errors++;
	    break;
	}
    }

    if (pauseFlag && opts.context != PM_CONTEXT_ARCHIVE) {
	pmprintf("%s: pause can only be used with archives\n", pmGetProgname());
	opts.errors++;
    }

    if (opts.errors || opts.optind < argc - 1) {
	pmUsageMessage(&opts);
	exit(1);
    }

    if (opts.context == PM_CONTEXT_ARCHIVE) {
	source = opts.archives[0];
    } else if (opts.context == PM_CONTEXT_HOST) {
	source = opts.hosts[0];
    } else {
	opts.context = PM_CONTEXT_HOST;
	source = "local:";
    }

    sts = pmCreateFetchGroup(& pmfg, opts.context, source);
    if (sts < 0) {
	if (opts.context == PM_CONTEXT_HOST)
	    fprintf(stderr, "%s: Cannot connect to PMCD on host \"%s\": %s\n",
		    pmGetProgname(), source, pmErrStr(sts));
	else
	    fprintf(stderr, "%s: Cannot open archive \"%s\": %s\n",
		    pmGetProgname(), source, pmErrStr(sts));
	exit(1);
    }
    c = pmGetFetchGroupContext(pmfg);
    
    /* complete TZ and time window option (origin) setup */
    if (pmGetContextOptions(c, &opts)) {
	pmflush();
	exit(1);
    }

    host = pmGetContextHostName(c);

    /* set a default sampling interval if none has been requested */
    if (opts.interval.tv_sec == 0 && opts.interval.tv_usec == 0)
	opts.interval.tv_sec = 5;

    if (opts.context == PM_CONTEXT_ARCHIVE) {
	if ((sts = pmSetMode(PM_MODE_INTERP, &opts.start, (int)(opts.interval.tv_sec*1000 + opts.interval.tv_usec/1000))) < 0) {
	    fprintf(stderr, "%s: pmSetMode failed: %s\n",
		    pmGetProgname(), pmErrStr(sts));
	    exit(1);
	}
    }

    if (opts.context == PM_CONTEXT_ARCHIVE)
	get_sample(); /* fetch the separate early ncpu record */
    get_sample(); /* fetch other rate metrics */

    /* set sampling loop termination via the command line options */
    samples = opts.samples ? opts.samples : -1;

    while (samples == -1 || samples-- > 0) {
	if (lines % 15 == 0) {
	    time_t	now = info.timestamp.tv_sec;
	    if (opts.context == PM_CONTEXT_ARCHIVE)
		printf("Archive: %s, ", opts.archives[0]);
	    printf("Host: %s, %d cpu(s), %s",
		   host, info.ncpu.l,
		   pmCtime(&now, timebuf));
/* - report format
  CPU  Busy    Busy  Free Mem   Disk     Load Average
 Util   CPU    Util  (Mbytes)   IOPS    1 Min  15 Min
X.XXX   XXX   X.XXX XXXXX.XXX XXXXXX  XXXX.XX XXXX.XX
*/
	    printf("  CPU");
	    if (info.ncpu.l > 1)
		printf("  Busy    Busy");
	    printf("  Free Mem   Disk     Load Average\n");
	    printf(" Util");
	    if (info.ncpu.l > 1)
		printf("   CPU    Util");
	    printf("  (Mbytes)   IOPS    1 Min  15 Min\n");
	}
	if (opts.context != PM_CONTEXT_ARCHIVE || pauseFlag)
	    __pmtimevalSleep(opts.interval);
	get_sample();
	printf("%5.2f", info.cpu_util);
	if (info.ncpu.l > 1)
	    printf("   %3d   %5.2f", info.peak_cpu, info.peak_cpu_util);
	printf(" %9.3f", info.freemem.d);
	printf(" %6d", info.dkiops.l);
	printf("  %7.2f %7.2f\n", info.load1.d, info.load15.d);
 	lines++;
    }
    exit(0);
}
示例#19
0
文件: pmlogreduce.c 项目: tongfw/pcp
int
main(int argc, char **argv)
{
    int		sts;
    char	*msg;
    pmResult	*irp;		/* input pmResult */
    pmResult	*orp;		/* output pmResult */
    __pmPDU	*pb;		/* pdu buffer */
    struct timeval	unused;
    unsigned long	peek_offset;

    /* process cmd line args */
    if (parseargs(argc, argv) < 0) {
	pmUsageMessage(&opts);
	exit(1);
    }

    /* input  archive name is argv[opts.optind] */
    /* output archive name is argv[argc-1]) */

    /* output archive */
    oname = argv[argc-1];

    /* input archive */
    iname = argv[opts.optind];

    /*
     * This is the interp mode context
     */
    if ((ictx_a = pmNewContext(PM_CONTEXT_ARCHIVE, iname)) < 0) {
	fprintf(stderr, "%s: Error: cannot open archive \"%s\" (ctx_a): %s\n",
		pmProgname, iname, pmErrStr(ictx_a));
	exit(1);
    }

    if ((sts = pmGetArchiveLabel(&ilabel)) < 0) {
	fprintf(stderr, "%s: Error: cannot get archive label record (%s): %s\n", pmProgname, iname, pmErrStr(sts));
	exit(1);
    }

    /* start time */
    logstart_tval.tv_sec = ilabel.ll_start.tv_sec;
    logstart_tval.tv_usec = ilabel.ll_start.tv_usec;

    /* end time */
    if ((sts = pmGetArchiveEnd(&logend_tval)) < 0) {
	fprintf(stderr, "%s: Error: cannot get end of archive (%s): %s\n",
		pmProgname, iname, pmErrStr(sts));
	exit(1);
    }

    if (zarg) {
	/* use TZ from metrics source (input-archive) */
	if ((sts = pmNewZone(ilabel.ll_tz)) < 0) {
	    fprintf(stderr, "%s: Cannot set context timezone: %s\n",
		    pmProgname, pmErrStr(sts));
            exit(1);
	}
	printf("Note: timezone set to local timezone of host \"%s\" from archive\n\n", ilabel.ll_hostname);
    }
    else if (tz != NULL) {
	/* use TZ as specified by user */
	if ((sts = pmNewZone(tz)) < 0) {
	    fprintf(stderr, "%s: Cannot set timezone to \"%s\": %s\n",
		    pmProgname, tz, pmErrStr(sts));
	    exit(1);
	}
	printf("Note: timezone set to \"TZ=%s\"\n\n", tz);
    }
    else {
	char	*tz;
        tz = __pmTimezone();
	/* use TZ from local host */
	if ((sts = pmNewZone(tz)) < 0) {
	    fprintf(stderr, "%s: Cannot set local host's timezone: %s\n",
		    pmProgname, pmErrStr(sts));
	    exit(1);
	}
    }

    /* set winstart and winend timevals */
    sts = pmParseTimeWindow(Sarg, Targ, Aarg, Oarg,
			    &logstart_tval, &logend_tval,
			    &winstart_tval, &winend_tval, &unused, &msg);
    if (sts < 0) {
	fprintf(stderr, "%s: Invalid time window specified: %s\n",
		pmProgname, msg);
	exit(1);
    }
#if PCP_DEBUG
    if (pmDebug & DBG_TRACE_APPL0) {
	char	buf[26];
	pmCtime((const time_t *)&winstart_tval.tv_sec, buf);
	fprintf(stderr, "Start time: %s", buf);
	pmCtime((const time_t *)&winend_tval.tv_sec, buf);
	fprintf(stderr, "End time: %s", buf);
    }
#endif

    if ((sts = pmSetMode(PM_MODE_INTERP | PM_XTB_SET(PM_TIME_SEC),
                         &winstart_tval, (int)targ)) < 0) {
	fprintf(stderr, "%s: pmSetMode(PM_MODE_INTERP ...) failed: %s\n",
		pmProgname, pmErrStr(sts));
	exit(1);
    }

    /* create output log - must be done before writing label */
    if ((sts = __pmLogCreate("", oname, PM_LOG_VERS02, &logctl)) < 0) {
	fprintf(stderr, "%s: Error: __pmLogCreate: %s\n",
		pmProgname, pmErrStr(sts));
	exit(1);
    }

    /* This must be done after log is created:
     *		- checks that archive version, host, and timezone are ok
     *		- set archive version, host, and timezone of output archive
     *		- set start time
     *		- write labels
     */
    newlabel();
    current.tv_sec = logctl.l_label.ill_start.tv_sec = winstart_tval.tv_sec;
    current.tv_usec = logctl.l_label.ill_start.tv_usec = winstart_tval.tv_usec;
    /* write label record */
    writelabel();
    /*
     * Supress any automatic label creation in libpcp at the first
     * pmResult write.
     */
    logctl.l_state = PM_LOG_STATE_INIT;

    /*
     * Traverse the PMNS to get all the metrics and their metadata
     */
    if ((sts = pmTraversePMNS ("", dometric)) < 0) {
	fprintf(stderr, "%s: Error traversing namespace ... %s\n",
		pmProgname, pmErrStr(sts));
	goto cleanup;
    }

    /*
     * All the initial metadata has been generated, add timestamp
     */
    fflush(logctl.l_mdfp);
    __pmLogPutIndex(&logctl, &current);

    written = 0;

    /*
     * main loop
     */
    while (sarg == -1 || written < sarg) {
	/*
	 * do stuff
	 */
	if ((sts = pmUseContext(ictx_a)) < 0) {
	    fprintf(stderr, "%s: Error: cannot use context (%s): %s\n",
		    pmProgname, iname, pmErrStr(sts));
	    goto cleanup;
	}
	if ((sts = pmFetch(numpmid, pmidlist, &irp)) < 0) {
	    if (sts == PM_ERR_EOL)
		break;
	    fprintf(stderr,
		"%s: Error: pmFetch failed: %s\n", pmProgname, pmErrStr(sts));
	    exit(1);
	}
	if (irp->timestamp.tv_sec > winend_tval.tv_sec ||
	    (irp->timestamp.tv_sec == winend_tval.tv_sec &&
	     irp->timestamp.tv_usec > winend_tval.tv_usec)) {
	    /* past end time as per -T */
	    break;
	}
#if PCP_DEBUG
	if (pmDebug & DBG_TRACE_APPL2) {
	    fprintf(stderr, "input record ...\n");
	    __pmDumpResult(stderr, irp);
	}
#endif

	/*
	 * traverse the interval, looking at every archive record ...
	 * we are particularly interested in:
	 * 	- metric-values that are interpolated but not present in
	 * 	  this interval
	 * 	- counter wraps
	 *	- mark records
	 */
	doscan(&irp->timestamp);

	if ((sts = pmUseContext(ictx_a)) < 0) {
	    fprintf(stderr, "%s: Error: cannot use context (%s): %s\n",
		    pmProgname, iname, pmErrStr(sts));
	    goto cleanup;
	}

	orp = rewrite(irp);
#if PCP_DEBUG
	if (pmDebug & DBG_TRACE_APPL2) {
	    if (orp == NULL)
		fprintf(stderr, "output record ... none!\n");
	    else {
		fprintf(stderr, "output record ...\n");
		__pmDumpResult(stderr, orp);
	    }
	}
#endif
	if (orp == NULL)
	    goto next;

	/*
	 * convert log record to a PDU, and enforce V2 encoding semantics,
	 * then write it out
	 */
	sts = __pmEncodeResult(PDU_OVERRIDE2, orp, &pb);
	if (sts < 0) {
	    fprintf(stderr, "%s: Error: __pmEncodeResult: %s\n",
		    pmProgname, pmErrStr(sts));
	    goto cleanup;
	}

	/* switch volumes if required */
	if (varg > 0) {
	    if (written > 0 && (written % varg) == 0) {
		__pmTimeval	next_stamp;
		next_stamp.tv_sec = irp->timestamp.tv_sec;
		next_stamp.tv_usec = irp->timestamp.tv_usec;
		newvolume(oname, &next_stamp);
	    }
	}
	/*
	 * Even without a -v option, we may need to switch volumes
	 * if the data file exceeds 2^31-1 bytes
	 */
	peek_offset = ftell(logctl.l_mfp);
	peek_offset += ((__pmPDUHdr *)pb)->len - sizeof(__pmPDUHdr) + 2*sizeof(int);
	if (peek_offset > 0x7fffffff) {
	    __pmTimeval	next_stamp;
	    next_stamp.tv_sec = irp->timestamp.tv_sec;
	    next_stamp.tv_usec = irp->timestamp.tv_usec;
	    newvolume(oname, &next_stamp);
	}

	current.tv_sec = orp->timestamp.tv_sec;
	current.tv_usec = orp->timestamp.tv_usec;

	doindom(orp);

	/* write out log record */
	sts = __pmLogPutResult2(&logctl, pb);
	__pmUnpinPDUBuf(pb);
	if (sts < 0) {
	    fprintf(stderr, "%s: Error: __pmLogPutResult2: log data: %s\n",
		    pmProgname, pmErrStr(sts));
	    goto cleanup;
	}
	written++;

	rewrite_free();

next:
	pmFreeResult(irp);
    }

    /* write the last time stamp */
    fflush(logctl.l_mfp);
    fflush(logctl.l_mdfp);
    __pmLogPutIndex(&logctl, &current);

    exit(exit_status);

cleanup:
    {
	char    fname[MAXNAMELEN];
	fprintf(stderr, "Archive \"%s\" not created.\n", oname);
	snprintf(fname, sizeof(fname), "%s.0", oname);
	unlink(fname);
	snprintf(fname, sizeof(fname), "%s.meta", oname);
	unlink(fname);
	snprintf(fname, sizeof(fname), "%s.index", oname);
	unlink(fname);
	exit(1);
    }
}
示例#20
0
文件: pmtop.c 项目: tongfw/pcp
int
main(int argc, char *argv[])
{
    int		c;
    int		sts;
    char	*endnum;
    pmDesc	desc;
    int		one_trip = 1;

    while ((c = pmGetOptions(argc, argv, &opts)) != EOF) {
	switch (c) {

	case 'w':	/* wide flag */
	    line_fmt = "%.1024s";
	    break;

	case 'p':	/* show flag */
	    if (one_trip) {
		show_spec = 0;
		one_trip = 0;
	    }
	    if ((sts = parse_show_spec(opts.optarg)) < 0) {
		pmprintf("%s: unrecognized print flag specification (%s)\n",
			pmProgname, opts.optarg);
		opts.errors++;
	    } else {
		show_spec |= sts;
	    }
	    break;

	case 'm':	/* top N */
	    top = (int)strtol(opts.optarg, &endnum, 10);
	    if (top <= 0) {
		pmprintf("%s: -m requires a positive integer\n", pmProgname);
		opts.errors++;	
	    }
	    break;
	}
    }

    if (opts.optind < argc)
        opts.errors++;

    if (opts.errors) {
	pmUsageMessage(&opts);
	exit(1);
    }

    create_namelist();

    if (opts.interval.tv_sec == 0)
	opts.interval.tv_sec = 2;

    if (opts.nhosts > 0)
	hostname = opts.hosts[0];
    else
	hostname = "local:";

    if ((sts = c = pmNewContext(PM_CONTEXT_HOST, hostname)) < 0) {
	fprintf(stderr, "%s: Cannot connect to PMCD on host \"%s\": %s\n",
		pmProgname, hostname, pmErrStr(sts));
	exit(1);
    }
    hostname = (char *)pmGetContextHostName(c);

    if (pmGetContextOptions(c, &opts)) {
	pmflush();
	exit(1);
    }

    if ((sts = pmLookupName(num_pmid, namelist, pmidlist)) < 0) {
	fprintf(stderr, "%s: Failed to lookup metrics : %s\n",
		pmProgname, pmErrStr(sts));
	exit(1);
    }

    for (c = 0; c < num_pmid; c++) {
	if ((sts = pmLookupDesc(pmidlist[c], &desc)) < 0) {
	    fprintf(stderr, "%s: Failed to lookup descriptor for metric \"%s\": %s\n",
		    pmProgname, namelist[c], pmErrStr(sts));
	    exit(1);
	}
	type_tab[c] = desc.type;	
	/* ASSUMES that the first metric will always be a proc metric */
	if (c == 0) {
	    proc_indom = desc.indom;
	}
    }

    for (;;) {
	doit();
	__pmtimevalSleep(opts.interval);
    }

    return 0;
}
示例#21
0
文件: pmconfig.c 项目: Aconex/pcp
int
main(int argc, char **argv)
{
    int		c;
    int		sflag = 0;

    while ((c = pmgetopt_r(argc, argv, &opts)) != EOF) {
        switch (c) {
	case 'a':       /* show all, default (unmodified) list format */
	case 'l':
	    sflag = 0;
	    break;
	case 's':       /* show all, guarded format for shell expansion */
	    sflag = 1;
	    break;
	case 'L':
	    apiflag = 1;
	    break;
	default:
	    opts.errors++;
	    break;
	}
    }

    if (opts.errors) {
	pmUsageMessage(&opts);
	exit(1);
    }

    if (sflag) {
	putenv("SHELL=/bin/sh");
	empty = none;
    }

    /* the complete list of variables is to be reported */
    if (opts.optind >= argc) {
	if (apiflag)
	    __pmAPIConfig(sflag ? export_report : direct_report);
	else
	    __pmConfig(sflag ? pcp_conf_shell_extract : pcp_conf_extract);
	exit(0);
    }

    /* an explicit list of variables has been requested */
    if (sflag) {
	if (apiflag)
	    for (c = opts.optind; c < argc; c++)
		export_report(argv[c], __pmGetAPIConfig(argv[c]));
	else
	    for (c = opts.optind; c < argc; c++)
		export_report(argv[c], pmGetConfig(argv[c]));
    } else {
	if (apiflag)
	    for (c = opts.optind; c < argc; c++)
		direct_report(argv[c], __pmGetAPIConfig(argv[c]));
	else
	    for (c = opts.optind; c < argc; c++)
		direct_report(argv[c], pmGetConfig(argv[c]));
    }
    exit(0);
}
示例#22
0
文件: pminfo.c 项目: rwongone/pcp
int
main(int argc, char **argv)
{
    int		a, c;
    int		sts;
    int		exitsts = 0;
    char	*source;
    char	*endnum;

    while ((c = pmGetOptions(argc, argv, &opts)) != EOF) {
        switch (c) {
        case 'b':		/* batchsize */
            batchsize = (int)strtol(opts.optarg, &endnum, 10);
            if (*endnum != '\0') {
                pmprintf("%s: -b requires numeric argument\n", pmProgname);
                opts.errors++;
            }
            break;

        case 'c':		/* derived metrics config file */
            sts = pmLoadDerivedConfig(opts.optarg);
            if (sts < 0) {
                fprintf(stderr, "%s: derived configuration(s) error: %s\n", pmProgname, pmErrStr(sts));
                /* errors are not necessarily fatal ... */
            }
            break;

        case 'd':
            p_desc = 1;
            need_context = 1;
            need_pmid = 1;
            break;

        case 'F':
            p_force = p_value = 1;
            need_context = 1;
            need_pmid = 1;
            break;

        case 'f':
            p_value = 1;
            need_context = 1;
            need_pmid = 1;
            break;

        case 'M':
            p_fullmid = 1;
            p_mid = 1;
            need_pmid = 1;
            break;

        case 'm':
            p_mid = 1;
            need_pmid = 1;
            break;

        case 't':
            p_oneline = 1;
            need_context = 1;
            need_pmid = 1;
            break;

        case 'T':
            p_help = 1;
            need_context = 1;
            need_pmid = 1;
            break;

        case 'v':
            verify = 1;
            need_context = 1;
            need_pmid = 1;
            break;

        case 'x':
            events = p_value = 1;
            need_context = 1;
            need_pmid = 1;
            break;
        }
    }
    if (opts.errors) {
        pmUsageMessage(&opts);
        exit(1);
    }

    if (opts.context)
        need_context = 1;

    if (opts.context == PM_CONTEXT_ARCHIVE)
        /*
         * for archives, one metric per batch and start at beginning of
         * archive for each batch so metric will be found if it is in
         * the archive
         */
        batchsize = 1;

    if (verify)
        p_desc = p_mid = p_fullmid = p_help = p_oneline = p_value = p_force = 0;



    if ((namelist = (char **)malloc(batchsize * sizeof(char *))) == NULL) {
        fprintf(stderr, "%s: namelist malloc: %s\n", pmProgname, osstrerror());
        exit(1);
    }

    if ((pmidlist = (pmID *)malloc(batchsize * sizeof(pmID))) == NULL) {
        fprintf(stderr, "%s: pmidlist malloc: %s\n", pmProgname, osstrerror());
        exit(1);
    }

    if (!opts.nsflag)
        need_context = 1; /* for distributed PMNS as no PMNS file given */

    if (need_context) {
        int ctxid;

        if (opts.context == PM_CONTEXT_ARCHIVE)
            source = opts.archives[0];
        else if (opts.context == PM_CONTEXT_HOST)
            source = opts.hosts[0];
        else if (opts.context == PM_CONTEXT_LOCAL)
            source = NULL;
        else {
            opts.context = PM_CONTEXT_HOST;
            source = "local:";
        }
        if ((sts = pmNewContext(opts.context, source)) < 0) {
            if (opts.context == PM_CONTEXT_HOST)
                fprintf(stderr, "%s: Cannot connect to PMCD on host \"%s\": %s\n",
                        pmProgname, source, pmErrStr(sts));
            else if (opts.context == PM_CONTEXT_LOCAL)
                fprintf(stderr, "%s: Cannot make standalone connection on localhost: %s\n",
                        pmProgname, pmErrStr(sts));
            else
                fprintf(stderr, "%s: Cannot open archive \"%s\": %s\n",
                        pmProgname, source, pmErrStr(sts));
            exit(1);
        }
        ctxid = sts;

        if (opts.context == PM_CONTEXT_ARCHIVE) {
            pmTrimNameSpace();
            /* complete TZ and time window option (origin) setup */
            if (pmGetContextOptions(ctxid, &opts)) {
                pmflush();
                exit(1);
            }
        }
    }

    if (opts.optind >= argc) {
        sts = pmTraversePMNS("", dometric);
        if (sts < 0) {
            fprintf(stderr, "Error: %s\n", pmErrStr(sts));
            exitsts = 1;
        }
    }
    else {
        for (a = opts.optind; a < argc; a++) {
            sts = pmTraversePMNS(argv[a], dometric);
            if (sts < 0) {
                fprintf(stderr, "Error: %s: %s\n", argv[a], pmErrStr(sts));
                exitsts = 1;
            }
        }
    }
    report();

    exit(exitsts);
}