runcron.c 16.2 KB
Newer Older
ale's avatar
ale committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/*
 * runcron - a cron job wrapper with some useful features.
 *
 * Copyright (c) 2014 <ale@incal.net>.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
ale's avatar
ale committed
20 21

#define _GNU_SOURCE
ale's avatar
ale committed
22 23 24 25
#include <errno.h>
#include <getopt.h>
#include <math.h>
#include <signal.h>
ale's avatar
ale committed
26 27 28 29
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/file.h>
ale's avatar
ale committed
30
#include <sys/stat.h>
ale's avatar
ale committed
31 32
#include <sys/types.h>
#include <sys/wait.h>
ale's avatar
ale committed
33 34
#include <time.h>
#include <unistd.h>
ale's avatar
ale committed
35 36 37 38 39

#include "config.h"

/* Global options */
char *job_name = NULL;
ale's avatar
ale committed
40
char *node_exporter_dir = "/var/lib/prometheus/node-exporter";
ale's avatar
ale committed
41 42 43 44 45 46 47 48 49 50
int splay_time = 0;
int run_timeout = 0;
int syslog = 0;
int log_on_failure = 0;
int locking = 1;
int lock_timeout = 0;
int lock_wait = 0;

char *lock_dir = "/var/tmp";

ale's avatar
ale committed
51 52
struct timespec one_second = {.tv_sec = 1, .tv_nsec = 0};

ale's avatar
ale committed
53 54
time_t start_time, end_time;

ale's avatar
ale committed
55
int usage() {
ale's avatar
ale committed
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
  fprintf(
      stderr,
      "%s v%s - a cron job wrapper\n"
      "Usage: %s [<OPTIONS>] [--] <COMMAND> [<ARGS>...]\n"
      "\n"
      "Known options:\n"
      "\n"
      "   --help            Show this help message\n"
      "   --splay SECONDS   Wait a random amount of time between 0 and SECONDS "
      "before\n"
      "                     actually starting the command.\n"
      "   --timeout SECONDS\n"
      "                     If the command runs for more than the specified "
      "amount of\n"
      "                     time, terminate it. By default commands can run "
      "forever.\n"
      "\n"
      "Options controlling the command output:\n"
      "\n"
      "   --quiet           Only show output from the command if it fails, "
      "suppress\n"
      "                     all output if the exit status is 0.\n"
      "   --syslog          Log command output to syslog, instead of stderr.\n"
      "\n"
      "Options controlling locking behavior:\n"
      "\n"
      "   -n, --name NAME   Set the job name. By default, the basename of "
      "COMMAND will\n"
      "                     be used.\n"
      "   --no-lock         Disable locking, allow running multiple instances "
      "at once.\n"
      "   --wait            Wait for the lock to be released. If another "
      "instance of\n"
      "                     this command is running, wait until it terminates "
      "(or\n"
      "                     until the lock timeout expires).\n"
      "   --lock-timeout SECONDS\n"
      "                     Wait at most the specified amount of time for the "
      "instance\n"
      "                     lock to be released, failing with an error if "
      "after SECONDS\n"
      "                     the lock could not be obtained. If set to 0 (the "
      "default),\n"
      "                     wait forever. Specifying this option implies "
      "--wait.\n"
      "\n"
ale's avatar
ale committed
102 103 104 105 106 107 108 109 110 111 112
      "Options for Prometheus integration:\n"
      "\n"
      "   --node-exporter-dir PATH\n"
      "                    Look for the prometheus-node-exporter state directory "
      "in PATH\n"
      "                    (default /var/lib/prometheus/node-exporter). If the "
      "directory\n"
      "                    exists, the program will write a small node-exporter "
      "textfile\n"
      "                    snippet in there.\n"
      "\n"
ale's avatar
ale committed
113 114 115 116 117
      "If you are passing options to COMMAND, remember to use `--' to tell the "
      "runcron\n"
      "option parser to stop interpreting options for itself.\n"
      "\n",
      PACKAGE, PACKAGE_VERSION, PACKAGE);
ale's avatar
ale committed
118 119 120 121 122 123 124 125 126 127 128 129 130 131
  return 2;
}

int to_int(char *s) {
  long n;
  char *endptr = NULL;
  errno = 0;
  n = strtol(s, &endptr, 10);
  if (errno != 0 || *endptr != '\0') {
    return -1;
  }
  return n;
}

ale's avatar
ale committed
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
/* hashpjw implementation, based on glibc/intl/hash-string.c */
void hash_add(unsigned long *hvalp, const char *s) {
  unsigned long hval = *hvalp, g;
  unsigned const char *sptr = (unsigned const char *)s;
  for (; *sptr; sptr++) {
    hval <<= 4;
    hval += *sptr;
    g = hval & ((unsigned long)0xf << (32 - 4));
    if (g != 0) {
      hval ^= g >> (32 - 8);
      hval ^= g;
    }
  }
  *hvalp = hval;
}

/* Convert a floating-point time (seconds) to a struct timespec. */
void time_to_spec(float t, struct timespec *out) {
  int secs = (int)floor(t);
  out->tv_sec = (time_t)secs;
  out->tv_nsec = (long)floor((t - (float)secs) * 1e9);
}

/* Return a time in the range [0, mod), based on the given hash value. */
float hash_time(unsigned long hval, float mod) {
  /* Use the lower 16 bits to obtain a value in the [0,1) range. */
  static const unsigned long maxhashbits = (1 << 16) - 1;
  float f = (float)(hval & maxhashbits) / (float)maxhashbits;
  return mod * f;
}

void splay(char **argv) {
  /* The splay time should be different for every host / job
   * combination, but it should also be only a function of those
   * parameters. To achieve this and also guarantee a reasonable
   * spread over the time space, we use a very simple hash of hostid +
   * command line.
   */
  unsigned long hval = gethostid();
  struct timespec sleep_time;
  for (; *argv; argv++) {
    hash_add(&hval, *argv);
  }

  time_to_spec(hash_time(hval, splay_time), &sleep_time);
  nanosleep(&sleep_time, NULL);
ale's avatar
ale committed
178 179 180 181 182 183 184 185 186 187 188
}

void lock_wait_expired(int signum) {
  fprintf(stderr, "Error: could not acquire lock within the timeout\n");
  exit(3);
}

void lock_with_timeout() {
  char *lockfile = NULL;
  sighandler_t old_handler = NULL;
  int fd, r, lock_flags;
ale's avatar
ale committed
189

ale's avatar
ale committed
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
  if (asprintf(&lockfile, "%s/runcron.lock.%s", lock_dir, job_name) < 0) {
    fprintf(stderr, "Error: could not allocate memory\n");
    exit(1);
  }
  fd = open(lockfile, O_RDWR | O_CREAT, 0600);
  if (fd < 0) {
    fprintf(stderr, "Error: could not open lock file: %s\n", strerror(errno));
    exit(1);
  }

  lock_flags = LOCK_EX;
  if (lock_wait) {
    if (lock_timeout > 0) {
      old_handler = signal(SIGALRM, lock_wait_expired);
      alarm(lock_timeout);
    }
  } else {
    lock_flags |= LOCK_NB;
  }

  r = flock(fd, lock_flags);
  if (r < 0) {
    if (errno == EWOULDBLOCK) {
      fprintf(stderr, "Error: another instance is already running\n");
    } else {
ale's avatar
ale committed
215 216
      fprintf(stderr, "Error: lock could not be obtained: %s\n",
              strerror(errno));
ale's avatar
ale committed
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
    }
    exit(3);
  }
  if (lock_wait && lock_timeout > 0) {
    signal(SIGALRM, old_handler);
    alarm(0);
  }
}

void setup_syslog() {
  char *tag = NULL;
  int pipefd[2], pid, r;

  if (asprintf(&tag, "cron(%s)", job_name) < 0) {
    fprintf(stderr, "Error: could not setup syslog: no memory\n");
    return;
  }

  r = pipe(pipefd);
  if (r < 0) {
    fprintf(stderr, "Error: could not create log pipe: %s\n", strerror(errno));
    return;
  }

  pid = fork();
  if (pid < 0) {
    fprintf(stderr, "Error: could not spawn logger: %s\n", strerror(errno));
    return;
  } else if (pid == 0) {
246
    int i;
ale's avatar
ale committed
247
    char *logger_args[] = {
ale's avatar
ale committed
248
        "logger", "-p", "daemon.info", "-t", tag, NULL,
ale's avatar
ale committed
249
    };
250
    /* Put the pipe on stdin, close all other fds. */
ale's avatar
ale committed
251
    dup2(pipefd[0], 0);
252 253 254
    for (i = 1; i < 1024; i++) {
      close(i);
    }
ale's avatar
ale committed
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
    r = execvp(logger_args[0], logger_args);
    if (r < 0) {
      fprintf(stderr, "Error: logger: %s\n", strerror(errno));
    }
    exit(1);
  }

  dup2(pipefd[1], 1);
  dup2(pipefd[1], 2);
}

void dumpfd(int from, int to) {
  char buf[4096];
  int n;

  lseek(from, 0, SEEK_SET);
  while (1) {
    n = read(from, buf, sizeof(buf));
    if (n <= 0) {
      break;
    }
    n = write(to, buf, n);
    if (n < 0) {
      break;
    }
  }
}

/* State for the process terminator. */
int child_pid = -1;
int termination_signal = SIGTERM;
volatile int timeout_expired = 0;
ale's avatar
ale committed
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
sigset_t parent_sigset, child_sigset;

int wait_and_forward_signals(int *status) {
  siginfo_t sig;

  while (1) {
    // Wait for a signal.
    if (sigtimedwait(&parent_sigset, &sig, &one_second) < 0) {
      switch (errno) {
      case EAGAIN:
        break;
      case EINTR:
        break;
      default:
        fprintf(stderr, "Error: unexpected error in sigtimedwait(): %s\n",
                strerror(errno));
        return -1;
      }
    } else {
      switch (sig.si_signo) {
      case SIGCHLD:
        // Fall through to reaping the child process.
        break;

      case SIGALRM:
        // Timeout expired, kill the child process.
        if (kill(child_pid, termination_signal) < 0) {
          if (errno == ESRCH) {
            // Process is already gone, reap it.
            break;
          }
          fprintf(stderr, "Error: sending signal %d to pid %d: %s",
                  sig.si_signo, child_pid, strerror(errno));
          return -1;
        }
        // Retry in 3 seconds with SIGKILL.
        timeout_expired = 1;
        termination_signal = SIGKILL;
        alarm(3);

      default:
        // Send signal to child pid.
        if (kill(child_pid, sig.si_signo) < 0) {
          if (errno == ESRCH) {
            // Process is already gone, reap it.
            break;
          }
          fprintf(stderr, "Error: sending signal %d to pid %d: %s",
                  sig.si_signo, child_pid, strerror(errno));
          return -1;
        }
        continue;
      }
    }

    // Call waitpid().
    if (waitpid(child_pid, status, WNOHANG) > 0) {
      return 0;
    }
  }
}

int setup_signals() {
  // Signals that should bypass the main loop.
  int i, signals_to_skip[] = {
             SIGFPE,  SIGILL, SIGSEGV, SIGBUS,  SIGABRT,
             SIGTRAP, SIGSYS, SIGTTIN, SIGTTOU,
         };
ale's avatar
ale committed
355

ale's avatar
ale committed
356 357 358 359 360 361 362 363 364 365 366 367
  // Set up the signal mask, before forking.
  if (sigfillset(&parent_sigset)) {
    fprintf(stderr, "Error: sigfillset() failed: %s\n", strerror(errno));
    return -1;
  }

  for (i = 0; i < sizeof(signals_to_skip) / sizeof(int); i++) {
    if (sigdelset(&parent_sigset, signals_to_skip[i])) {
      fprintf(stderr, "Error: sigdelset() failed: %s\n", strerror(errno));
      return -1;
    }
  }
ale's avatar
ale committed
368

ale's avatar
ale committed
369 370 371
  if (sigprocmask(SIG_SETMASK, &parent_sigset, &child_sigset)) {
    fprintf(stderr, "Error: sigprocmask() failed: %s\n", strerror(errno));
    return -1;
ale's avatar
ale committed
372
  }
ale's avatar
ale committed
373 374

  return 0;
ale's avatar
ale committed
375 376 377 378 379 380
}

int run(char **argv) {
  char temp_name[] = "/tmp/runcron.out.XXXXXX";
  int r, wait_status, exit_status = -1, logfd = -1;

ale's avatar
ale committed
381 382 383 384
  if (setup_signals() < 0) {
    return -1;
  }

ale's avatar
ale committed
385 386 387
  if (log_on_failure) {
    logfd = mkstemp(temp_name);
    if (logfd < 0) {
ale's avatar
ale committed
388 389
      fprintf(stderr, "Error: could not create temporary output file: %s\n",
              strerror(errno));
ale's avatar
ale committed
390 391 392 393 394
    } else {
      unlink(temp_name);
    }
  }

ale's avatar
ale committed
395 396
  start_time = time(NULL);

ale's avatar
ale committed
397 398 399 400 401 402 403 404 405
  child_pid = fork();
  if (child_pid < 0) {
    fprintf(stderr, "Error: fork(): %s\n", strerror(errno));
  } else if (child_pid == 0) {
    if (logfd >= 0) {
      dup2(logfd, 1);
      dup2(logfd, 2);
    }

ale's avatar
ale committed
406 407 408 409 410
    if (sigprocmask(SIG_SETMASK, &child_sigset, NULL)) {
      fprintf(stderr, "Error: sigprocmask(): %s\n", strerror(errno));
      exit(1);
    }

ale's avatar
ale committed
411 412 413 414 415 416 417 418 419 420
    r = execvp(argv[0], argv);
    if (r < 0) {
      fprintf(stderr, "Error: exec(%s): %s\n", argv[0], strerror(errno));
      exit(1);
    }
  } else {
    if (run_timeout > 0) {
      alarm(run_timeout);
    }

ale's avatar
ale committed
421
    r = wait_and_forward_signals(&wait_status);
ale's avatar
ale committed
422 423 424 425 426 427 428 429
    if (r < 0) {
      return 1;
    } else {
      if (WIFEXITED(wait_status)) {
        exit_status = WEXITSTATUS(wait_status);
      } else if (WIFSIGNALED(wait_status)) {
        if (timeout_expired) {
          fprintf(stderr, "Error: %s execution timed out\n", argv[0]);
ale's avatar
ale committed
430
          exit_status = 142;
ale's avatar
ale committed
431
        } else {
ale's avatar
ale committed
432 433 434
          fprintf(stderr, "Error: %s terminated by signal %d\n", argv[0],
                  WTERMSIG(wait_status));
          exit_status = 128 + WTERMSIG(wait_status);
ale's avatar
ale committed
435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
        }
      } else {
        fprintf(stderr, "Error: %s terminated for unknown reason\n", argv[0]);
      }
    }
  }

  if (logfd >= 0) {
    if (exit_status != 0) {
      /* Dump the actual output to stderr. */
      dumpfd(logfd, 2);
    }
  }

  return exit_status;
}

ale's avatar
ale committed
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495
int export_metrics(int exit_status) {
  struct stat sb;
  char *tmp_file = NULL, *metrics_file = NULL;
  int elapsed;
  FILE *fp;

  if (stat(node_exporter_dir, &sb) < 0 || ((sb.st_mode & S_IFMT) != S_IFDIR)) {
    return 0;
  }

  if (asprintf(&tmp_file, "%s/.cron-%s.prom.tmp~", node_exporter_dir, job_name) < 0) {
    fprintf(stderr, "Error: could not allocate memory for metrics\n");
    return -1;
  }
  if (asprintf(&metrics_file, "%s/cron-%s.prom", node_exporter_dir, job_name) < 0) {
    fprintf(stderr, "Error: could not allocate memory for metrics\n");
    return -1;
  }

  end_time = time(NULL);
  elapsed = end_time - start_time;

  fp = fopen(tmp_file, "w");
  if (fp == NULL) {
    fprintf(stderr, "Error: could not open %s: %s\n", metrics_file, strerror(errno));
    return -1;
  }
  fprintf(fp, "cronjob_status{cronjob=\"%s\"} %d\n", job_name, (exit_status == 0) ? 1 : 0);
  fprintf(fp, "cronjob_last_start{cronjob=\"%s\"} %ld\n", job_name, start_time);
  fprintf(fp, "cronjob_last_end{cronjob=\"%s\"} %ld\n", job_name, end_time);
  fprintf(fp, "cronjob_runtime_seconds{cronjob=\"%s\"} %d\n", job_name, elapsed);
  if (exit_status == 0) {
    fprintf(fp, "cronjob_last_success{cronjob=\"%s\"} %ld\n", job_name, end_time);
  }
  fclose(fp);

  if (rename(tmp_file, metrics_file) < 0) {
    fprintf(stderr, "Error: could not write metrics: %s\n", strerror(errno));
    unlink(tmp_file);
    return -1;
  }
  return 0;
}

ale's avatar
ale committed
496
int main(int argc, char **argv) {
ale's avatar
ale committed
497
  int c, r;
ale's avatar
ale committed
498 499 500 501 502

  while (1) {
    int option_index = 0;
    const char *opt_name = NULL;
    static struct option long_options[] = {
ale's avatar
ale committed
503 504 505 506 507 508 509 510 511 512 513 514 515 516
        {"help", no_argument, 0, 'h'},
        {"name", required_argument, 0, 'n'},
        {"splay", required_argument, 0, 0},
        {"timeout", required_argument, 0, 0},
        {"quiet", no_argument, &log_on_failure, 1},
        {"syslog", no_argument, &syslog, 1},
        {"no-lock", no_argument, &locking, 0},
        {"nolock", no_argument, &locking, 0},
        {"lock-timeout", required_argument, 0, 0},
        {"wait", no_argument, &lock_wait, 1},
        {"node-exporter-dir", required_argument, 0, 0},
        {0, 0, 0, 0}};

    c = getopt_long(argc, argv, "hqn:", long_options, &option_index);
ale's avatar
ale committed
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
    if (c == -1) {
      break;
    }

    switch (c) {
    case 0:
      opt_name = long_options[option_index].name;
      if (!strcmp(opt_name, "splay")) {
        splay_time = to_int(optarg);
        if (splay_time < 0) {
          fprintf(stderr, "Error: --splay argument must be an integer\n");
          exit(2);
        }
      } else if (!strcmp(opt_name, "timeout")) {
        run_timeout = to_int(optarg);
        if (run_timeout < 0) {
          fprintf(stderr, "Error: --timeout argument must be an integer\n");
          exit(2);
        }
      } else if (!strcmp(opt_name, "lock-timeout")) {
        lock_timeout = to_int(optarg);
        if (lock_timeout < 0) {
ale's avatar
ale committed
539 540
          fprintf(stderr,
                  "Error: --lock-timeout argument must be an integer\n");
ale's avatar
ale committed
541 542
          exit(2);
        }
ale's avatar
ale committed
543 544
      } else if (!strcmp(opt_name, "node-exporter-dir")) {
        node_exporter_dir = optarg;
ale's avatar
ale committed
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
      }
      break;

    case 'q':
      log_on_failure = 1;
      break;
    case 'n':
      job_name = optarg;
      break;

    case 'h':
      usage();
      exit(0);
      break;
    case '?':
      exit(usage());
      break;
    }
  }

ale's avatar
ale committed
565 566 567
  /* Check for option consistency. */
  if (!locking) {
    if (lock_wait) {
ale's avatar
ale committed
568 569
      fprintf(stderr,
              "Error: --wait and --no-lock should not be specified together\n");
ale's avatar
ale committed
570 571 572
      exit(2);
    }
    if (lock_timeout > 0) {
ale's avatar
ale committed
573 574
      fprintf(stderr, "Error: --no-lock and --lock-timeout should not be "
                      "specified together\n");
ale's avatar
ale committed
575 576 577 578 579 580 581 582
      exit(2);
    }
  } else {
    if (lock_timeout > 0) {
      lock_wait = 1;
    }
  }

ale's avatar
ale committed
583 584 585 586 587 588 589 590 591 592
  if (optind >= argc) {
    fprintf(stderr, "Error: no command specified\n");
    exit(2);
  }

  if (job_name == NULL) {
    job_name = basename(argv[optind]);
  }

  if (splay_time > 0) {
ale's avatar
ale committed
593
    splay(argv + optind);
ale's avatar
ale committed
594 595 596 597 598 599 600 601 602 603
  }

  if (syslog) {
    setup_syslog();
  }

  if (locking) {
    lock_with_timeout();
  }

ale's avatar
ale committed
604 605 606
  r = run(argv + optind);
  export_metrics(r);
  return r;
ale's avatar
ale committed
607
}