1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 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 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 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 178 179 180 181 182 183 184 185 186 187 188 189 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 215 216 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 246 247 248 249 250 251 252 253 254 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 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 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 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 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718
|
/*
Copyright 2019 Northern.tech AS
This file is part of CFEngine 3 - written and maintained by Northern.tech AS.
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; version 3.
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, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
To the extent this program is licensed as part of the Enterprise
versions of CFEngine, the applicable Commercial Open Source License
(COSL) may apply to this file if you as a licensee so wish it. See
included file COSL.txt.
*/
#include <cf-execd.h>
#include <cf-execd-runner.h>
#include <item_lib.h>
#include <known_dirs.h>
#include <man.h>
#include <ornaments.h>
#include <exec_tools.h>
#include <signals.h>
#include <processes_select.h>
#include <bootstrap.h>
#include <policy_server.h>
#include <sysinfo.h>
#include <timeout.h>
#include <time_classes.h>
#include <loading.h>
#include <printsize.h>
#include <cleanup.h>
#include <repair.h>
#include <dbm_api.h> /* CheckDBRepairFlagFile() */
#include <string_lib.h>
#include <cf-windows-functions.h>
#define CF_EXEC_IFELAPSED 0
#define CF_EXEC_EXPIREAFTER 1
static bool PERFORM_DB_CHECK = false;
static int NO_FORK = false; /* GLOBAL_A */
static int ONCE = false; /* GLOBAL_A */
static int WINSERVICE = true; /* GLOBAL_A */
static pthread_attr_t threads_attrs; /* GLOBAL_T, initialized by pthread_attr_init */
/*******************************************************************/
static GenericAgentConfig *CheckOpts(int argc, char **argv);
void ThisAgentInit(void);
static bool ScheduleRun(EvalContext *ctx, Policy **policy, GenericAgentConfig *config,
ExecdConfig **execd_config, ExecConfig **exec_config);
#ifndef __MINGW32__
static void Apoptosis(void);
#endif
static bool LocalExecInThread(const ExecConfig *config);
/*******************************************************************/
/* Command line options */
/*******************************************************************/
static const char *const CF_EXECD_SHORT_DESCRIPTION =
"scheduling daemon for cf-agent";
static const char *const CF_EXECD_MANPAGE_LONG_DESCRIPTION =
"cf-execd is the scheduling daemon for cf-agent. It runs cf-agent locally according to a schedule specified in "
"policy code (executor control body). After a cf-agent run is completed, cf-execd gathers output from cf-agent, "
"and may be configured to email the output to a specified address. It may also be configured to splay (randomize) the "
"execution schedule to prevent synchronized cf-agent runs across a network. "
"Note: this daemon reloads it's config when the SIGHUP signal is received.";
static const struct option OPTIONS[] =
{
{"help", no_argument, 0, 'h'},
{"debug", no_argument, 0, 'd'},
{"verbose", no_argument, 0, 'v'},
{"dry-run", no_argument, 0, 'n'},
{"version", no_argument, 0, 'V'},
{"file", required_argument, 0, 'f'},
{"define", required_argument, 0, 'D'},
{"negate", required_argument, 0, 'N'},
{"no-lock", no_argument, 0, 'K'},
{"inform", no_argument, 0, 'I'},
{"diagnostic", no_argument, 0, 'x'},
{"log-level", required_argument, 0, 'g'},
{"no-fork", no_argument, 0, 'F'},
{"once", no_argument, 0, 'O'},
{"no-winsrv", no_argument, 0, 'W'},
{"ld-library-path", required_argument, 0, 'L'},
{"color", optional_argument, 0, 'C'},
{"timestamp", no_argument, 0, 'l'},
{"skip-db-check", optional_argument, 0, 0 },
{NULL, 0, 0, '\0'}
};
static const char *const HINTS[] =
{
"Print the help message",
"Enable debugging output",
"Output verbose information about the behaviour of cf-execd",
"All talk and no action mode - make no changes, only inform of promises not kept",
"Output the version of the software",
"Specify an alternative input file than the default. This option is overridden by FILE if supplied as argument.",
"Define a list of comma separated classes to be defined at the start of execution",
"Define a list of comma separated classes to be undefined at the start of execution",
"Ignore locking constraints during execution (ifelapsed/expireafter) if \"too soon\" to run",
"Print basic information about changes made to the system, i.e. promises repaired",
"Activate internal diagnostics (developers only)",
"Specify how detailed logs should be. Possible values: 'error', 'warning', 'notice', 'info', 'verbose', 'debug'",
"Run as a foreground processes (do not fork)",
"Run once and then exit (implies no-fork)",
"Do not run as a service on windows - use this when running from a command shell (CFEngine Nova only)",
"Set the internal value of LD_LIBRARY_PATH for child processes",
"Enable colorized output. Possible values: 'always', 'auto', 'never'. If option is used, the default value is 'auto'",
"Log timestamps on each line of log output",
"Do not run database integrity checks and repairs at startup",
NULL
};
/*****************************************************************************/
int main(int argc, char *argv[])
{
GenericAgentConfig *config = CheckOpts(argc, argv);
bool force_repair = CheckDBRepairFlagFile();
if (force_repair || PERFORM_DB_CHECK)
{
repair_lmdb_default(force_repair);
}
EvalContext *ctx = EvalContextNew();
GenericAgentConfigApply(ctx, config);
GenericAgentDiscoverContext(ctx, config);
Policy *policy = SelectAndLoadPolicy(config, ctx, false, false);
if (!policy)
{
Log(LOG_LEVEL_ERR, "Error reading CFEngine policy. Exiting...");
DoCleanupAndExit(EXIT_FAILURE);
}
GenericAgentPostLoadInit(ctx);
ThisAgentInit();
ExecConfig *exec_config = ExecConfigNew(!ONCE, ctx, policy);
ExecdConfig *execd_config = ExecdConfigNew(ctx, policy);
SetFacility(execd_config->log_facility);
#ifdef __MINGW32__
if (WINSERVICE)
{
NovaWin_StartExecService();
}
else
#endif /* __MINGW32__ */
{
StartServer(ctx, policy, config, &execd_config, &exec_config);
}
GenericAgentFinalize(ctx, config);
ExecConfigDestroy(exec_config);
ExecdConfigDestroy(execd_config);
return 0;
}
/*****************************************************************************/
/* Level 1 */
/*****************************************************************************/
static GenericAgentConfig *CheckOpts(int argc, char **argv)
{
extern char *optarg;
int c;
GenericAgentConfig *config = GenericAgentConfigNewDefault(AGENT_TYPE_EXECUTOR, GetTTYInteractive());
int longopt_idx;
while ((c = getopt_long(argc, argv, "dvnKIf:g:D:N:VxL:hFOV1gMWC::l",
OPTIONS, &longopt_idx))
!= -1)
{
switch (c)
{
case 'f':
GenericAgentConfigSetInputFile(config, GetInputDir(), optarg);
MINUSF = true;
break;
case 'd':
LogSetGlobalLevel(LOG_LEVEL_DEBUG);
break;
case 'K':
config->ignore_locks = true;
break;
case 'D':
{
StringSet *defined_classes = StringSetFromString(optarg, ',');
if (! config->heap_soft)
{
config->heap_soft = defined_classes;
}
else
{
StringSetJoin(config->heap_soft, defined_classes, xstrdup);
StringSetDestroy(defined_classes);
}
}
break;
case 'N':
{
StringSet *negated_classes = StringSetFromString(optarg, ',');
if (! config->heap_negated)
{
config->heap_negated = negated_classes;
}
else
{
StringSetJoin(config->heap_negated, negated_classes, xstrdup);
StringSetDestroy(negated_classes);
}
}
break;
case 'I':
LogSetGlobalLevel(LOG_LEVEL_INFO);
break;
case 'v':
LogSetGlobalLevel(LOG_LEVEL_VERBOSE);
NO_FORK = true; // TODO: really?
break;
case 'g':
LogSetGlobalLevelArgOrExit(optarg);
break;
case 'n':
DONTDO = true;
config->ignore_locks = true;
break;
case 'L':
{
Log(LOG_LEVEL_VERBOSE, "Setting 'LD_LIBRARY_PATH=%s'", optarg);
setenv_wrapper("LD_LIBRARY_PATH", optarg, 1);
break;
}
case 'W':
WINSERVICE = false;
break;
case 'F':
NO_FORK = true;
break;
case 'O':
ONCE = true;
NO_FORK = true;
break;
case 'V':
{
Writer *w = FileWriter(stdout);
GenericAgentWriteVersion(w);
FileWriterDetach(w);
}
DoCleanupAndExit(EXIT_SUCCESS);
case 'h':
{
Writer *w = FileWriter(stdout);
WriterWriteHelp(w, "cf-execd", OPTIONS, HINTS, NULL, false, true);
FileWriterDetach(w);
}
DoCleanupAndExit(EXIT_SUCCESS);
case 'M':
{
Writer *out = FileWriter(stdout);
ManPageWrite(out, "cf-execd", time(NULL),
CF_EXECD_SHORT_DESCRIPTION,
CF_EXECD_MANPAGE_LONG_DESCRIPTION,
OPTIONS, HINTS,
NULL, false,
true);
FileWriterDetach(out);
DoCleanupAndExit(EXIT_SUCCESS);
}
case 'x':
Log(LOG_LEVEL_ERR, "Self-diagnostic functionality is retired.");
DoCleanupAndExit(EXIT_SUCCESS);
case 'C':
if (!GenericAgentConfigParseColor(config, optarg))
{
DoCleanupAndExit(EXIT_FAILURE);
}
break;
case 'l':
LoggingEnableTimestamps(true);
break;
case 0:
{
const char *const option_name = OPTIONS[longopt_idx].name;
if (StringSafeEqual(option_name, "skip-db-check"))
{
if (optarg == NULL)
{
PERFORM_DB_CHECK = false; // Skip (no arg), check = false
}
else if (StringSafeEqual_IgnoreCase(optarg, "yes"))
{
PERFORM_DB_CHECK = false; // Skip = yes, check = false
}
else if (StringSafeEqual_IgnoreCase(optarg, "no"))
{
PERFORM_DB_CHECK = true; // Skip = no, check = true
}
else
{
Log(LOG_LEVEL_ERR,
"Invalid argument for --skip-db-check(yes/no): '%s'",
optarg);
DoCleanupAndExit(EXIT_FAILURE);
}
}
break;
}
default:
{
Writer *w = FileWriter(stdout);
WriterWriteHelp(w, "cf-execd", OPTIONS, HINTS, NULL, false, true);
FileWriterDetach(w);
}
DoCleanupAndExit(EXIT_FAILURE);
}
}
if (!GenericAgentConfigParseArguments(config, argc - optind, argv + optind))
{
Log(LOG_LEVEL_ERR, "Too many arguments");
DoCleanupAndExit(EXIT_FAILURE);
}
return config;
}
/*****************************************************************************/
void ThisAgentInit(void)
{
umask(077);
}
/*****************************************************************************/
// msg should include exactly one reference to unsigned int.
static unsigned int MaybeSleepLog(LogLevel level, const char *msg, unsigned int seconds)
{
if (IsPendingTermination())
{
return seconds;
}
Log(level, msg, seconds);
return sleep(seconds);
}
/*****************************************************************************/
/* Might be called back from NovaWin_StartExecService */
void StartServer(EvalContext *ctx, Policy *policy, GenericAgentConfig *config, ExecdConfig **execd_config, ExecConfig **exec_config)
{
pthread_attr_init(&threads_attrs);
pthread_attr_setdetachstate(&threads_attrs, PTHREAD_CREATE_DETACHED);
pthread_attr_setstacksize(&threads_attrs, (size_t)2048*1024);
Banner("Starting executor");
#ifndef __MINGW32__
if (!ONCE)
{
/* Kill previous instances of cf-execd if those are still running */
Apoptosis();
}
time_t now = time(NULL);
if ((!NO_FORK) && (fork() != 0))
{
Log(LOG_LEVEL_INFO, "cf-execd starting %.24s", ctime(&now));
_exit(EXIT_SUCCESS);
}
if (!NO_FORK)
{
ActAsDaemon();
}
#else /* __MINGW32__ */
if (!NO_FORK)
{
Log(LOG_LEVEL_VERBOSE, "Windows does not support starting processes in the background - starting in foreground");
}
#endif
WritePID("cf-execd.pid");
signal(SIGINT, HandleSignalsForDaemon);
signal(SIGTERM, HandleSignalsForDaemon);
signal(SIGBUS, HandleSignalsForDaemon);
signal(SIGHUP, HandleSignalsForDaemon);
signal(SIGPIPE, SIG_IGN);
signal(SIGUSR1, HandleSignalsForDaemon);
signal(SIGUSR2, HandleSignalsForDaemon);
umask(077);
if (ONCE)
{
LocalExec(*exec_config);
CloseLog();
}
else
{
while (!IsPendingTermination())
{
if (ScheduleRun(ctx, &policy, config, execd_config, exec_config))
{
MaybeSleepLog(LOG_LEVEL_VERBOSE,
"Sleeping for splaytime %u seconds",
(*execd_config)->splay_time);
// We are sleeping both above and inside ScheduleRun(), so make
// sure a terminating signal did not arrive during that time.
if (IsPendingTermination())
{
break;
}
if (!LocalExecInThread(*exec_config))
{
Log(LOG_LEVEL_INFO,
"Unable to run agent in thread, falling back to blocking execution");
LocalExec(*exec_config);
}
}
}
}
PolicyDestroy(policy);
}
/*****************************************************************************/
static void Thread_AllSignalsBlock(void)
{
#ifndef __MINGW32__
sigset_t sigmask;
sigfillset(&sigmask);
int ret = pthread_sigmask(SIG_SETMASK, &sigmask, NULL);
if (ret != 0)
{
Log(LOG_LEVEL_ERR,
"Unable to block signals in child thread,"
" killing cf-execd might fail (pthread_sigmask: %s)",
GetErrorStr());
}
#endif
}
static void Thread_AllSignalsUnblock(void)
{
#ifndef __MINGW32__
sigset_t sigmask;
sigemptyset(&sigmask);
int ret = pthread_sigmask(SIG_SETMASK, &sigmask, NULL);
if (ret != 0)
{
Log(LOG_LEVEL_ERR,
"Unable to unblock signals again (pthread_sigmask: %s)",
GetErrorStr());
}
#endif
}
static void *LocalExecThread(void *param)
{
ExecConfig *config = (ExecConfig *) param;
LocalExec(config);
ExecConfigDestroy(config);
Log(LOG_LEVEL_VERBOSE, "Finished exec_command execution, terminating thread");
return NULL;
}
static bool LocalExecInThread(const ExecConfig *config)
{
ExecConfig *thread_config = ExecConfigCopy(config);
pthread_t tid;
Log(LOG_LEVEL_VERBOSE, "Spawning thread for exec_command execution");
/* ENT-3147: Block all signals so that child thread inherits it and
* signals get only delivered to the main thread. Unblock all signals
* right after thread has been spawned. */
Thread_AllSignalsBlock();
int ret = pthread_create(&tid, &threads_attrs, LocalExecThread, thread_config);
Thread_AllSignalsUnblock();
if (ret != 0)
{
ExecConfigDestroy(thread_config);
Log(LOG_LEVEL_ERR, "Failed to create thread (pthread_create: %s)",
GetErrorStr());
return false;
}
return true;
}
#ifndef __MINGW32__
static void Apoptosis(void)
{
char promiser_buf[CF_SMALLBUF];
snprintf(promiser_buf, sizeof(promiser_buf), "%s%ccf-execd",
GetBinDir(), FILE_SEPARATOR);
if (LoadProcessTable())
{
char myuid[PRINTSIZE(unsigned)];
xsnprintf(myuid, sizeof(myuid), "%u", (unsigned) getuid());
Rlist *owners = NULL;
RlistPrepend(&owners, myuid, RVAL_TYPE_SCALAR);
ProcessSelect process_select = PROCESS_SELECT_INIT;
process_select.owner = owners;
process_select.process_result = "process_owner";
Item *killlist = SelectProcesses(promiser_buf, &(process_select), true);
RlistDestroy(owners);
for (Item *ip = killlist; ip != NULL; ip = ip->next)
{
pid_t pid = ip->counter;
if (pid != getpid() && kill(pid, SIGTERM) < 0)
{
if (errno == ESRCH)
{
/* That's ok, process exited voluntarily */
}
else
{
Log(LOG_LEVEL_ERR, "Unable to kill stale cf-execd process pid=%d. (kill: %s)",
(int)pid, GetErrorStr());
}
}
}
}
ClearProcessTable();
Log(LOG_LEVEL_VERBOSE, "Pruning complete");
}
#endif
typedef enum
{
RELOAD_ENVIRONMENT,
RELOAD_FULL
} Reload;
static Reload CheckNewPromises(GenericAgentConfig *config)
{
Log(LOG_LEVEL_DEBUG, "Checking file updates for input file '%s'", config->input_file);
time_t validated_at = ReadTimestampFromPolicyValidatedFile(config, NULL);
bool reload_config = false;
if (config->agent_specific.daemon.last_validated_at < validated_at)
{
Log(LOG_LEVEL_VERBOSE, "New promises detected...");
reload_config = true;
}
if (ReloadConfigRequested())
{
Log(LOG_LEVEL_VERBOSE, "Force reload of inputs files...");
reload_config = true;
}
if (reload_config)
{
ClearRequestReloadConfig();
/* Rereading policies now, so update timestamp. */
config->agent_specific.daemon.last_validated_at = validated_at;
if (GenericAgentArePromisesValid(config))
{
return RELOAD_FULL;
}
else
{
Log(LOG_LEVEL_INFO, "New promises file contains syntax errors -- ignoring");
}
}
else
{
Log(LOG_LEVEL_DEBUG, "No new promises found");
}
return RELOAD_ENVIRONMENT;
}
static bool ScheduleRun(EvalContext *ctx, Policy **policy, GenericAgentConfig *config,
ExecdConfig **execd_config, ExecConfig **exec_config)
{
/* 1 Minute resolution is enough */
MaybeSleepLog(LOG_LEVEL_VERBOSE, "Sleeping for pulse time %u seconds...", CFPULSETIME);
/*
* FIXME: this logic duplicates the one from cf-serverd.c. Unify ASAP.
*/
if (CheckNewPromises(config) == RELOAD_FULL)
{
/* Full reload */
Log(LOG_LEVEL_INFO, "Re-reading promise file '%s'", config->input_file);
EvalContextClear(ctx);
strcpy(VDOMAIN, "undefined.domain");
PolicyDestroy(*policy);
*policy = NULL;
EvalContextSetPolicyServerFromFile(ctx, GetWorkDir());
UpdateLastPolicyUpdateTime(ctx);
DetectEnvironment(ctx);
GenericAgentDiscoverContext(ctx, config);
EvalContextClassPutHard(ctx, CF_AGENTTYPES[AGENT_TYPE_EXECUTOR], "cfe_internal,source=agent");
time_t t = SetReferenceTime();
UpdateTimeClasses(ctx, t);
GenericAgentConfigSetBundleSequence(config, NULL);
*policy = LoadPolicy(ctx, config);
ExecConfigDestroy(*exec_config);
ExecdConfigDestroy(*execd_config);
*exec_config = ExecConfigNew(!ONCE, ctx, *policy);
*execd_config = ExecdConfigNew(ctx, *policy);
SetFacility((*execd_config)->log_facility);
}
else
{
/* Environment reload */
EvalContextClear(ctx);
DetectEnvironment(ctx);
time_t t = SetReferenceTime();
UpdateTimeClasses(ctx, t);
}
{
StringSetIterator it = StringSetIteratorInit((*execd_config)->schedule);
const char *time_context = NULL;
while ((time_context = StringSetIteratorNext(&it)))
{
if (IsDefinedClass(ctx, time_context))
{
Log(LOG_LEVEL_VERBOSE, "Waking up the agent at %s ~ %s", ctime(&CFSTARTTIME), time_context);
return true;
}
}
}
Log(LOG_LEVEL_VERBOSE, "Nothing to do at %s", ctime(&CFSTARTTIME));
return false;
}
|