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

	logformat = DEFAULT_LOGFORMAT;
	user = RUN_AS_USER;

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

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

			case 's':
				monhost = optarg;
				break;

			case 'l':
				logfn = optarg;
				break;

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

			case 'f':
				logformat = optarg;
				break;

			case 'u':
				user = optarg;
				break;

			case 'V':
				exit(EXIT_SUCCESS);

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

	argc -= optind;
	argv += optind;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	open_syslog(prog); 

	if (logfile != stdout)
		background();

	setup_signals();

	writepid(pidfilebase);

	become_user(new_uid);

	compile_format();

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

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

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

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

		run_flist();

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

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

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

	upscli_disconnect(&ups);
	
	exit(EXIT_SUCCESS);
}
Example #2
0
int main(int argc, char *argv[])
{
    const char	*prog = xbasename(argv[0]);
    int	i, cmd = 0, checking_flag = 0;

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

    /* if no configuration file is specified on the command line, use default */
    configfile = xmalloc(SMALLBUF);
    snprintf(configfile, SMALLBUF, "%s/upsmon.conf", confpath());
    configfile = xrealloc(configfile, strlen(configfile) + 1);

    run_as_user = xstrdup(RUN_AS_USER);

    while ((i = getopt(argc, argv, "+Dhic:f:pu:VK46")) != -1) {
        switch (i) {
        case 'c':
            if (!strncmp(optarg, "fsd", strlen(optarg)))
                cmd = SIGCMD_FSD;
            if (!strncmp(optarg, "stop", strlen(optarg)))
                cmd = SIGCMD_STOP;
            if (!strncmp(optarg, "reload", strlen(optarg)))
                cmd = SIGCMD_RELOAD;

            /* bad command name given */
            if (cmd == 0)
                help(argv[0]);
            break;
        case 'D':
            nut_debug_level++;
            break;
        case 'f':
            free(configfile);
            configfile = xstrdup(optarg);
            break;
        case 'h':
            help(argv[0]);
            break;
        case 'K':
            checking_flag = 1;
            break;
        case 'p':
            use_pipe = 0;
            break;
        case 'u':
            free(run_as_user);
            run_as_user = xstrdup(optarg);
            break;
        case 'V':
            /* just show the banner */
            exit(EXIT_SUCCESS);
        case '4':
            opt_af = AF_INET;
            break;
        case '6':
            opt_af = AF_INET6;
            break;
        default:
            help(argv[0]);
            break;
        }
    }

    if (cmd) {
        sendsignal(prog, cmd);
        exit(EXIT_SUCCESS);
    }

    /* otherwise, we are being asked to start.
     * so check if a previous instance is running by sending signal '0'
     * (Ie 'kill <pid> 0') */
    if (sendsignal(prog, 0) == 0) {
        printf("Fatal error: A previous upsmon instance is already running!\n");
        printf("Either stop the previous instance first, or use the 'reload' command.\n");
        exit(EXIT_FAILURE);
    }

    argc -= optind;
    argv += optind;

    open_syslog(prog);

    loadconfig();

    if (checking_flag)
        exit(check_pdflag());

    if (shutdowncmd == NULL)
        printf("Warning: no shutdown command defined!\n");

    /* we may need to get rid of a flag from a previous shutdown */
    if (powerdownflag != NULL)
        clear_pdflag();
    /* FIXME (else): POWERDOWNFLAG is not defined!!
     * => fallback to a default value */

    if (totalpv < minsupplies) {
        printf("\nFatal error: insufficient power configured!\n\n");

        printf("Sum of power values........: %d\n", totalpv);
        printf("Minimum value (MINSUPPLIES): %d\n", minsupplies);

        printf("\nEdit your upsmon.conf and change the values.\n");
        exit(EXIT_FAILURE);
    }

    if (nut_debug_level < 1) {
        background();
    } else {
        upsdebugx(1, "debug level is '%d'", nut_debug_level);
    }

    /* only do the pipe stuff if the user hasn't disabled it */
    if (use_pipe) {
        struct passwd	*new_uid = get_user_pwent(run_as_user);

        /* === root parent and unprivileged child split here === */
        start_pipe();

        /* write the pid file now, as we will soon lose root */
        writepid(prog);

        become_user(new_uid);
    } else {
        upslogx(LOG_INFO, "Warning: running as one big root process by request (upsmon -p)");

        writepid(prog);
    }

    /* prep our signal handlers */
    setup_signals();

    /* reopen the log for the child process */
    closelog();
    open_syslog(prog);

    while (exit_flag == 0) {
        utype_t	*ups;

        /* check flags from signal handlers */
        if (userfsd)
            forceshutdown();

        if (reload_flag)
            reload_conf();

        for (ups = firstups; ups != NULL; ups = ups->next)
            pollups(ups);

        recalc();

        /* make sure the parent hasn't died */
        if (use_pipe)
            check_parent();

        /* reap children that have exited */
        waitpid(-1, NULL, WNOHANG);

        sleep(sleepval);
    }

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

    exit(EXIT_SUCCESS);
}