mirror of
https://github.com/Security-Onion-Solutions/securityonion.git
synced 2026-12-03 00:56:13 +01:00
Compare commits
13
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1a717897f9 | ||
|
|
316bfbeadc | ||
|
|
5cb6fd7057 | ||
|
|
ddbf3e971a | ||
|
|
dd4165fa56 | ||
|
|
eb3ff80154 | ||
|
|
f78382fee2 | ||
|
|
274803b930 | ||
|
|
e321b92248 | ||
|
|
b6a597bb05 | ||
|
|
2f97a2c283 | ||
|
|
303fefe84d | ||
|
|
8a1179d403 |
No files matched your search
@@ -10,6 +10,17 @@
|
||||
# NOTE: This script depends on so-common
|
||||
IMAGEREPO=security-onion-solutions
|
||||
STATUS_CONF='/opt/so/conf/so-status/so-status.conf'
|
||||
# PIDs of the current launch_pool children, so the INT/TERM trap can kill them.
|
||||
POOL_PIDS=()
|
||||
_pool_tree=()
|
||||
IMAGE_PARALLEL_JOBS=4
|
||||
IMAGE_INSPECT_TIMEOUT=120
|
||||
IMAGE_RETRIES=5
|
||||
IMAGE_RETRY_DELAY=30
|
||||
# The preflight is a quick check, not a retry budget: one retry at most, and a
|
||||
# definite answer from the registry ends it right away.
|
||||
PREFLIGHT_ATTEMPTS=2
|
||||
PREFLIGHT_RETRY_DELAY=10
|
||||
|
||||
# shellcheck disable=SC2120
|
||||
container_list() {
|
||||
@@ -79,6 +90,420 @@ container_list() {
|
||||
fi
|
||||
}
|
||||
|
||||
registry_host() {
|
||||
if [ -z "$HOSTNAME" ]; then
|
||||
HOSTNAME=$(hostname)
|
||||
fi
|
||||
printf '%s' "$HOSTNAME"
|
||||
}
|
||||
|
||||
manifest_blob_digests() {
|
||||
jq -r '(.config.digest // empty), (.layers[]? | .digest)' "$1"
|
||||
}
|
||||
|
||||
# Registries link blobs per repo and buildx cannot mount across registries, so
|
||||
# pre-link shared layers or every image re-downloads them from ghcr.io.
|
||||
mount_shared_blobs() {
|
||||
local host=$1
|
||||
local target_repo=$2
|
||||
local manifest_file=$3
|
||||
local log_file=$4
|
||||
local -n blob_repo=$5
|
||||
local digest source_repo code
|
||||
while IFS= read -r digest; do
|
||||
if [ -z "$digest" ]; then
|
||||
continue
|
||||
fi
|
||||
source_repo="${blob_repo[$digest]:-}"
|
||||
if [ -z "$source_repo" ] || [ "$source_repo" == "$target_repo" ]; then
|
||||
continue
|
||||
fi
|
||||
code=$(curl -sk --connect-timeout 5 --max-time 30 -o /dev/null -w '%{http_code}' -X POST \
|
||||
"https://${host}:5000/v2/${IMAGEREPO}/${target_repo}/blobs/uploads/?mount=${digest}&from=${IMAGEREPO}/${source_repo}" \
|
||||
2>> "$log_file")
|
||||
if [ "$code" != "201" ]; then
|
||||
echo "Could not pre-link $digest from $source_repo into $target_repo (HTTP ${code:-error}), buildx will download it" >> "$log_file"
|
||||
fi
|
||||
done < <(manifest_blob_digests "$manifest_file")
|
||||
}
|
||||
|
||||
record_shared_blobs() {
|
||||
local target_repo=$1
|
||||
local manifest_file=$2
|
||||
local -n blob_repo=$3
|
||||
local digest
|
||||
while IFS= read -r digest; do
|
||||
if [ -n "$digest" ] && [ -z "${blob_repo[$digest]:-}" ]; then
|
||||
blob_repo["$digest"]=$target_repo
|
||||
fi
|
||||
done < <(manifest_blob_digests "$manifest_file")
|
||||
}
|
||||
|
||||
image_ref() { # image_ref <image:tag> => the full registry reference
|
||||
printf '%s/%s/%s' "$CONTAINER_REGISTRY" "$IMAGEREPO" "$1"
|
||||
}
|
||||
|
||||
# One small function per inspect: retry_cmd logs its attempts on stdout, so the
|
||||
# command's own output is redirected to its file here.
|
||||
fetch_manifest() { # fetch_manifest <ref> <out file>
|
||||
timeout "$IMAGE_INSPECT_TIMEOUT" docker buildx imagetools inspect --raw "$1" >"$2"
|
||||
}
|
||||
|
||||
# buildx's --format output is the contract with the signed .txt, so it stays in
|
||||
# one place that is easy to adjust.
|
||||
fetch_config() { # fetch_config <ref> <out file>
|
||||
timeout "$IMAGE_INSPECT_TIMEOUT" docker buildx imagetools inspect \
|
||||
--format '{{json .Image}}' "$1" >"$2"
|
||||
}
|
||||
|
||||
# The ES image follows the elasticsearch version, everything else the SO
|
||||
# version. Prints "<image>:<tag> <signature url>".
|
||||
resolve_image() { # resolve_image <image>
|
||||
local i=$1
|
||||
local image_version
|
||||
if [[ " ${IMAGES_USING_ES_VERSION[*]} " =~ [[:space:]]${i}[[:space:]] ]]; then
|
||||
# this is an es container so use version defined in elasticsearch defaults.yaml
|
||||
local UPDATE_DIR='/tmp/sogh/securityonion'
|
||||
if [ ! -d "$UPDATE_DIR" ]; then
|
||||
UPDATE_DIR=/securityonion
|
||||
fi
|
||||
local v1=0
|
||||
local v2=0
|
||||
if [[ -f "$UPDATE_DIR/salt/elasticsearch/defaults.yaml" ]]; then
|
||||
v1=$(grep -E " +version: " "$UPDATE_DIR/salt/elasticsearch/defaults.yaml" | awk -F: '{print $2}' | tr -d '[:space:]')
|
||||
fi
|
||||
if [[ -f "$DEFAULT_SALT_DIR/salt/elasticsearch/defaults.yaml" ]]; then
|
||||
v2=$(grep -E " +version: " "$DEFAULT_SALT_DIR/salt/elasticsearch/defaults.yaml" | awk -F: '{print $2}' | tr -d '[:space:]')
|
||||
fi
|
||||
image_version=$(compare_es_versions "$v1" "$v2")
|
||||
printf '%s:%s%s https://sigs.securityonion.net/es-%s/%s:%s%s.sig\n' \
|
||||
"$i" "$image_version" "$IMAGE_TAG_SUFFIX" "$image_version" "$i" "$image_version" "$IMAGE_TAG_SUFFIX"
|
||||
else
|
||||
# this is not an es container so use the so version for the version
|
||||
image_version=$VERSION
|
||||
printf '%s:%s%s https://sigs.securityonion.net/%s/%s:%s%s.sig\n' \
|
||||
"$i" "$image_version" "$IMAGE_TAG_SUFFIX" "$image_version" "$i" "$image_version" "$IMAGE_TAG_SUFFIX"
|
||||
fi
|
||||
}
|
||||
|
||||
verify_trusted_image() {
|
||||
local i=$1
|
||||
local IMAGE_LOG=$SIGNPATH/$i.verify.log
|
||||
|
||||
local image sig_url
|
||||
read -r image sig_url < <(resolve_image "$i")
|
||||
|
||||
local image_name=$i
|
||||
local manifest_file=$SIGNPATH/$image.manifest
|
||||
local config_file=$SIGNPATH/$image.config
|
||||
local REF
|
||||
REF=$(image_ref "$image")
|
||||
local VERIFIED_REF
|
||||
|
||||
local rc=0
|
||||
local digest_re='^sha256:[a-f0-9]{64}$'
|
||||
|
||||
retry_cmd "$IMAGE_RETRIES" "$IMAGE_RETRY_DELAY" fetch_manifest "$REF" "$manifest_file" >>"$IMAGE_LOG" 2>&1 || rc=$?
|
||||
if [ "$rc" -ne 0 ]; then
|
||||
echo "Could not fetch manifest for $image, please ensure connectivity to $CONTAINER_REGISTRY" >>"$IMAGE_LOG" 2>&1
|
||||
echo "Command failed with error $rc" >>"$IMAGE_LOG" 2>&1
|
||||
return 1
|
||||
fi
|
||||
if [ ! -s "$manifest_file" ] || ! jq -e . "$manifest_file" >/dev/null 2>&1; then
|
||||
echo "Unable to read the manifest for $image: empty or not JSON" >>"$IMAGE_LOG" 2>&1
|
||||
return 1
|
||||
fi
|
||||
# The sig covers these exact bytes, so an index would sign the wrong document.
|
||||
if jq -e '.manifests | type == "array"' "$manifest_file" >/dev/null 2>&1; then
|
||||
echo "$image manifest is a multi-platform index, expected a single manifest" >>"$IMAGE_LOG" 2>&1
|
||||
return 1
|
||||
fi
|
||||
|
||||
local manifest_digest
|
||||
manifest_digest=$(sha256sum "$manifest_file" | awk '{print $1}')
|
||||
local config_digest
|
||||
config_digest=$(jq -r '.config.digest // empty' "$manifest_file")
|
||||
if [ -z "$manifest_digest" ] || [ -z "$config_digest" ] || [ "$config_digest" = "null" ]; then
|
||||
echo "Unable to read the manifest for $image: no config digest" >>"$IMAGE_LOG" 2>&1
|
||||
return 1
|
||||
fi
|
||||
|
||||
# Every digest ends up in a URL (blob fetches, blob mounts, the wave
|
||||
# planner), so one malformed digest rejects the whole manifest.
|
||||
if [[ ! $config_digest =~ $digest_re ]]; then
|
||||
echo "Unable to inspect $image: invalid config digest '$config_digest'" >>"$IMAGE_LOG" 2>&1
|
||||
return 1
|
||||
fi
|
||||
local layer_digest
|
||||
while IFS= read -r layer_digest; do
|
||||
if [ -z "$layer_digest" ]; then
|
||||
continue
|
||||
fi
|
||||
if [[ ! $layer_digest =~ $digest_re ]]; then
|
||||
echo "Unable to inspect $image: invalid layer digest '$layer_digest'" >>"$IMAGE_LOG" 2>&1
|
||||
return 1
|
||||
fi
|
||||
done < <(jq -r '.layers[]? | .digest' "$manifest_file")
|
||||
|
||||
rc=0
|
||||
# By digest, not by tag: a tag can be re-pushed between the two calls, and the
|
||||
# .txt must describe the manifest bytes that sha256sum and the sig cover.
|
||||
VERIFIED_REF="${CONTAINER_REGISTRY}/${IMAGEREPO}/${image_name}@sha256:${manifest_digest}"
|
||||
retry_cmd "$IMAGE_RETRIES" "$IMAGE_RETRY_DELAY" fetch_config "$VERIFIED_REF" "$config_file" >>"$IMAGE_LOG" 2>&1 || rc=$?
|
||||
if [ "$rc" -ne 0 ]; then
|
||||
echo "Could not fetch image config for $image, please ensure connectivity to $CONTAINER_REGISTRY" >>"$IMAGE_LOG" 2>&1
|
||||
echo "Command failed with error $rc" >>"$IMAGE_LOG" 2>&1
|
||||
return 1
|
||||
fi
|
||||
if [ ! -s "$config_file" ]; then
|
||||
echo "Unable to read the config for $image" >>"$IMAGE_LOG" 2>&1
|
||||
return 1
|
||||
fi
|
||||
|
||||
# Get signature
|
||||
rc=0
|
||||
curl --fail --connect-timeout 10 --max-time 120 --retry 5 --retry-delay 60 -sSL \
|
||||
-A "$CURLTYPE/$CURRENTVERSION/$OS/$(uname -r)" \
|
||||
--output "$SIGNPATH/$image.sig" "$sig_url" >>"$IMAGE_LOG" 2>&1 || rc=$?
|
||||
if [ "$rc" -ne 0 ]; then
|
||||
echo "Could not pull signature file for $image, please ensure connectivity to https://sigs.securityonion.net " >>"$IMAGE_LOG" 2>&1
|
||||
echo "Command failed with error $rc" >>"$IMAGE_LOG" 2>&1
|
||||
return 1
|
||||
fi
|
||||
|
||||
# .txt layout must stay byte-identical to the old `docker inspect | jq` output
|
||||
# because the gpg signature is verified against it.
|
||||
if ! printf '%s\n' "\"${VERIFIED_REF}\"" >"$SIGNPATH/$image.txt"; then
|
||||
echo "Unable to write the signed ref line for $image" >>"$IMAGE_LOG" 2>&1
|
||||
return 1
|
||||
fi
|
||||
if ! jq ".created, .rootfs.diff_ids" "$config_file" >>"$SIGNPATH/$image.txt"; then
|
||||
echo "Unable to extract created and diff_ids for $image" >>"$IMAGE_LOG" 2>&1
|
||||
return 1
|
||||
fi
|
||||
local GPGTEST
|
||||
if ! GPGTEST=$(gpg --verify "$SIGNPATH/$image.sig" "$SIGNPATH/$image.txt" 2>&1); then
|
||||
echo "Signature verification failed for $image. Details:" >>"$IMAGE_LOG" 2>&1
|
||||
echo "$GPGTEST" >>"$IMAGE_LOG" 2>&1
|
||||
return 1
|
||||
fi
|
||||
|
||||
printf '%s\n%s\n%s\n' "$image" "$VERIFIED_REF" "$manifest_file" >"$SIGNPATH/$i.ref"
|
||||
return 0
|
||||
}
|
||||
|
||||
# retry()/run_check_net_err() eval their command string, so the argv helper is
|
||||
# used for anything that must not be re-parsed by the shell.
|
||||
retry_cmd() {
|
||||
local max_attempts=$1
|
||||
local delay=$2
|
||||
shift 2
|
||||
local attempt=1 rc=0
|
||||
while :; do
|
||||
if "$@"; then
|
||||
return 0
|
||||
else
|
||||
rc=$?
|
||||
fi
|
||||
echo "Command failed with error $rc (attempt $attempt of $max_attempts): $*"
|
||||
if [ "$attempt" -ge "$max_attempts" ]; then
|
||||
return $rc
|
||||
fi
|
||||
attempt=$((attempt + 1))
|
||||
sleep "$delay"
|
||||
done
|
||||
}
|
||||
|
||||
copy_verified_image() {
|
||||
local i=$1
|
||||
local IMAGE_LOG=$SIGNPATH/$i.copy.log
|
||||
local image VERIFIED_REF manifest_file
|
||||
{
|
||||
read -r image
|
||||
read -r VERIFIED_REF
|
||||
read -r manifest_file
|
||||
} <"$SIGNPATH/$i.ref"
|
||||
|
||||
local host
|
||||
host=$(registry_host)
|
||||
mount_shared_blobs "$host" "$i" "$manifest_file" "$IMAGE_LOG" pushed_blob_repo
|
||||
# imagetools create, not docker push: Docker 29's containerd store cannot push a
|
||||
# freshly pulled image. GODEBUG prefix keeps http2client=0 local (#16342).
|
||||
# It reads from ghcr.io, so it gets the same budget as the verify fetches.
|
||||
retry_cmd "$IMAGE_RETRIES" "$IMAGE_RETRY_DELAY" env GODEBUG="${GODEBUG:+${GODEBUG},}http2client=0" \
|
||||
docker buildx imagetools create --tag "${host}:5000/${IMAGEREPO}/${image}" "$VERIFIED_REF" \
|
||||
>>"$IMAGE_LOG" 2>&1 || {
|
||||
echo "Unable to copy $image to embedded registry" >>"$IMAGE_LOG" 2>&1
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
pull_verified_image() {
|
||||
local i=$1
|
||||
local IMAGE_LOG=$SIGNPATH/$i.pull.log
|
||||
local image VERIFIED_REF
|
||||
{
|
||||
read -r image
|
||||
read -r VERIFIED_REF
|
||||
} <"$SIGNPATH/$i.ref"
|
||||
|
||||
local host
|
||||
host=$(registry_host)
|
||||
# Pull by the digest that gpg verified, not by the mutable tag a compromised
|
||||
# grid node could have re-pushed. Keep the tag name visible to `docker images`
|
||||
# and to the salt checks that look for it.
|
||||
local digest=${VERIFIED_REF#*@}
|
||||
local digest_ref="${host}:5000/${IMAGEREPO}/${image%:*}@${digest}"
|
||||
local tag_ref="${host}:5000/${IMAGEREPO}/${image}"
|
||||
retry_cmd 3 10 docker pull "$digest_ref" >>"$IMAGE_LOG" 2>&1 || {
|
||||
echo "Unable to pull $image from embedded registry" >>"$IMAGE_LOG" 2>&1
|
||||
return 1
|
||||
}
|
||||
if ! docker tag "$digest_ref" "$tag_ref" >>"$IMAGE_LOG" 2>&1; then
|
||||
echo "Unable to tag $image" >>"$IMAGE_LOG" 2>&1
|
||||
return 1
|
||||
fi
|
||||
return 0
|
||||
}
|
||||
|
||||
log_downloading() {
|
||||
echo "Downloading $1" >> "$LOG_FILE" 2>&1
|
||||
}
|
||||
|
||||
# Kill a pool job and everything it spawned: in a non-interactive shell the
|
||||
# background docker/curl children ignore SIGINT, so killing only the subshell
|
||||
# would leave them writing to $SIGNPATH. Only PIDs the pool started are walked.
|
||||
pool_collect_tree() { # pool_collect_tree <pid>; appends to _pool_tree
|
||||
local pid=$1
|
||||
local child
|
||||
_pool_tree+=("$pid")
|
||||
while IFS= read -r child; do
|
||||
if [ -n "$child" ]; then
|
||||
pool_collect_tree "$child"
|
||||
fi
|
||||
done < <(pgrep -P "$pid" 2>/dev/null)
|
||||
}
|
||||
|
||||
_pool_abort() { # _pool_abort <exit code>
|
||||
local code=$1
|
||||
local pid
|
||||
trap '' INT TERM
|
||||
_pool_tree=()
|
||||
# Skipping reaped PIDs matters: their numbers may already belong to an
|
||||
# unrelated process, whose tree would then be killed as root.
|
||||
for pid in "${POOL_PIDS[@]}"; do
|
||||
if kill -0 "$pid" 2>/dev/null; then
|
||||
pool_collect_tree "$pid"
|
||||
fi
|
||||
done
|
||||
for pid in "${_pool_tree[@]}"; do
|
||||
kill -TERM "$pid" 2>/dev/null || true
|
||||
done
|
||||
sleep 2
|
||||
for pid in "${_pool_tree[@]}"; do
|
||||
kill -KILL "$pid" 2>/dev/null || true
|
||||
done
|
||||
exit "$code"
|
||||
}
|
||||
|
||||
# Fail fast: once a finished job of this pool failed, no new job is launched, so
|
||||
# an unreachable registry costs one round of retries instead of one per image.
|
||||
pool_failed() { # pool_failed <phase> <image>...
|
||||
local phase=$1
|
||||
shift
|
||||
local img rc
|
||||
for img in "$@"; do
|
||||
# No .rc yet means the job is still running, so it is not a failure.
|
||||
if rc=$(cat "$SIGNPATH/$img.$phase.rc" 2>/dev/null) && [ "$rc" != "0" ]; then
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
# Append one phase's per-image logs, then name what failed or was skipped.
|
||||
pool_collect() { # pool_collect <phase> <image>...; non-zero if any did not pass
|
||||
local phase=$1
|
||||
shift
|
||||
local img failed=0
|
||||
local -a bad=() skipped=()
|
||||
for img in "$@"; do
|
||||
cat "$SIGNPATH/$img.$phase.log" >> "$LOG_FILE" 2>/dev/null
|
||||
if [ ! -f "$SIGNPATH/$img.$phase.rc" ]; then
|
||||
skipped+=("$img")
|
||||
failed=1
|
||||
elif [ "$(cat "$SIGNPATH/$img.$phase.rc" 2>/dev/null)" != "0" ]; then
|
||||
bad+=("$img")
|
||||
failed=1
|
||||
fi
|
||||
done
|
||||
if [ "$failed" -ne 0 ]; then
|
||||
echo "$phase failed: ${bad[*]:-none}; skipped: ${skipped[*]:-none}" >> "$LOG_FILE" 2>&1
|
||||
return 1
|
||||
fi
|
||||
return 0
|
||||
}
|
||||
|
||||
launch_pool() {
|
||||
local func=$1
|
||||
local phase=$2
|
||||
local jobs=$3
|
||||
local hook=$4
|
||||
shift 4
|
||||
local -a active=() still=() launched=()
|
||||
local img pid rc
|
||||
local stop=0
|
||||
POOL_PIDS=()
|
||||
local saved_int saved_term
|
||||
saved_int=$(trap -p INT)
|
||||
saved_term=$(trap -p TERM)
|
||||
trap '_pool_abort 130' INT
|
||||
trap '_pool_abort 143' TERM
|
||||
for img in "$@"; do
|
||||
if [ "$stop" -ne 0 ]; then
|
||||
# No .rc is written, so the caller counts this image as failed too.
|
||||
echo "Skipped $img: an earlier image failed" >>"$SIGNPATH/$img.$phase.log" 2>&1
|
||||
continue
|
||||
fi
|
||||
if [ -n "$hook" ]; then
|
||||
"$hook" "$img"
|
||||
fi
|
||||
(
|
||||
("$func" "$img") >>"$SIGNPATH/$img.$phase.log" 2>&1
|
||||
rc=$?
|
||||
# Write then rename: a truncated .rc reads as a failure to pool_failed.
|
||||
echo "$rc" >"$SIGNPATH/$img.$phase.rc.tmp"
|
||||
mv "$SIGNPATH/$img.$phase.rc.tmp" "$SIGNPATH/$img.$phase.rc"
|
||||
) &
|
||||
pid=$!
|
||||
POOL_PIDS+=("$pid")
|
||||
active+=("$pid")
|
||||
launched+=("$img")
|
||||
while [ ${#active[@]} -ge "$jobs" ]; do
|
||||
wait -n "${active[@]}" 2>/dev/null || true
|
||||
still=()
|
||||
for pid in "${active[@]}"; do
|
||||
if kill -0 "$pid" 2>/dev/null; then
|
||||
still+=("$pid")
|
||||
fi
|
||||
done
|
||||
active=("${still[@]}")
|
||||
if [ "$stop" -eq 0 ] && pool_failed "$phase" "${launched[@]}"; then
|
||||
stop=1
|
||||
fi
|
||||
done
|
||||
done
|
||||
# Only wait on PIDs started here: soup may run its own background jobs in this
|
||||
# shell (e.g. the grid highstate), and a bare `wait` would block on those.
|
||||
if [ ${#POOL_PIDS[@]} -gt 0 ]; then
|
||||
wait "${POOL_PIDS[@]}" 2>/dev/null || true
|
||||
fi
|
||||
# Restore whatever the caller had; soup installs its own EXIT/ERR handlers.
|
||||
eval "${saved_int:-trap - INT}"
|
||||
eval "${saved_term:-trap - TERM}"
|
||||
}
|
||||
|
||||
update_docker_containers() {
|
||||
local CURLTYPE=$1
|
||||
local IMAGE_TAG_SUFFIX=$2
|
||||
@@ -130,91 +555,117 @@ update_docker_containers() {
|
||||
grep -q "so-logscan" "$STATUS_CONF" && TRUSTED_CONTAINERS+=("so-logscan")
|
||||
fi
|
||||
|
||||
# Download the containers from the interwebs
|
||||
for i in "${TRUSTED_CONTAINERS[@]}"
|
||||
do
|
||||
if [ -z "$PROGRESS_CALLBACK" ]; then
|
||||
echo "Downloading $i" >> "$LOG_FILE" 2>&1
|
||||
else
|
||||
$PROGRESS_CALLBACK $i
|
||||
fi
|
||||
local -A pushed_blob_repo=()
|
||||
|
||||
if [[ " ${IMAGES_USING_ES_VERSION[*]} " =~ [[:space:]]${i}[[:space:]] ]]; then
|
||||
# this is an es container so use version defined in elasticsearch defaults.yaml
|
||||
local UPDATE_DIR='/tmp/sogh/securityonion'
|
||||
if [ ! -d "$UPDATE_DIR" ]; then
|
||||
UPDATE_DIR=/securityonion
|
||||
fi
|
||||
local v1=0
|
||||
local v2=0
|
||||
if [[ -f "$UPDATE_DIR/salt/elasticsearch/defaults.yaml" ]]; then
|
||||
v1=$(egrep " +version: " "$UPDATE_DIR/salt/elasticsearch/defaults.yaml" | awk -F: '{print $2}' | tr -d '[:space:]')
|
||||
fi
|
||||
if [[ -f "$DEFAULT_SALT_DIR/salt/elasticsearch/defaults.yaml" ]]; then
|
||||
v2=$(egrep " +version: " "$DEFAULT_SALT_DIR/salt/elasticsearch/defaults.yaml" | awk -F: '{print $2}' | tr -d '[:space:]')
|
||||
fi
|
||||
local highest_es_version=$(compare_es_versions "$v1" "$v2")
|
||||
local image=$i:$highest_es_version$IMAGE_TAG_SUFFIX
|
||||
local sig_url=https://sigs.securityonion.net/es-$highest_es_version/$image.sig
|
||||
else
|
||||
# this is not an es container so use the so version for the version
|
||||
local image=$i:$VERSION$IMAGE_TAG_SUFFIX
|
||||
local sig_url=https://sigs.securityonion.net/$VERSION/$image.sig
|
||||
fi
|
||||
# Pull down the trusted docker image
|
||||
run_check_net_err \
|
||||
"docker pull $CONTAINER_REGISTRY/$IMAGEREPO/$image" \
|
||||
"Could not pull $image, please ensure connectivity to $CONTAINER_REGISTRY" >> "$LOG_FILE" 2>&1
|
||||
local jobs=$IMAGE_PARALLEL_JOBS
|
||||
|
||||
# Get signature
|
||||
run_check_net_err \
|
||||
"curl --retry 5 --retry-delay 60 -A '$CURLTYPE/$CURRENTVERSION/$OS/$(uname -r)' $sig_url --output $SIGNPATH/$image.sig" \
|
||||
"Could not pull signature file for $image, please ensure connectivity to https://sigs.securityonion.net " \
|
||||
noretry >> "$LOG_FILE" 2>&1
|
||||
# Dump our hash values
|
||||
DOCKERINSPECT=$(docker inspect $CONTAINER_REGISTRY/$IMAGEREPO/$image)
|
||||
|
||||
echo "$DOCKERINSPECT" | jq ".[0].RepoDigests[] | select(. | contains(\"$CONTAINER_REGISTRY\"))" > $SIGNPATH/$image.txt
|
||||
echo "$DOCKERINSPECT" | jq ".[0].Created, .[0].RootFS.Layers" >> $SIGNPATH/$image.txt
|
||||
|
||||
if [[ $? -ne 0 ]]; then
|
||||
echo "Unable to inspect $image" >> "$LOG_FILE" 2>&1
|
||||
exit 1
|
||||
fi
|
||||
GPGTEST=$(gpg --verify $SIGNPATH/$image.sig $SIGNPATH/$image.txt 2>&1)
|
||||
if [[ $? -eq 0 ]]; then
|
||||
if [[ -z "$SKIP_TAGPUSH" ]]; then
|
||||
# Tag it with the new registry destination
|
||||
if [ -z "$HOSTNAME" ]; then
|
||||
HOSTNAME=$(hostname)
|
||||
fi
|
||||
docker tag $CONTAINER_REGISTRY/$IMAGEREPO/$image $HOSTNAME:5000/$IMAGEREPO/$image >> "$LOG_FILE" 2>&1 || {
|
||||
echo "Unable to tag $image" >> "$LOG_FILE" 2>&1
|
||||
exit 1
|
||||
}
|
||||
# Push to the embedded registry via a registry-to-registry copy. Avoids
|
||||
# `docker push`, which on Docker 29.x with the containerd image store
|
||||
# represents freshly-pulled images as an index whose layer content
|
||||
# isn't reachable through the push path. The local `docker tag` above
|
||||
# is preserved so so-image-pull's `:5000` existence check still works.
|
||||
# Pin to the digest already gpg-verified above so we copy exactly the
|
||||
# bytes we approved.
|
||||
local VERIFIED_REF
|
||||
VERIFIED_REF=$(echo "$DOCKERINSPECT" | jq -r ".[0].RepoDigests[] | select(. | contains(\"$CONTAINER_REGISTRY\"))" | head -n 1)
|
||||
if [ -z "$VERIFIED_REF" ] || [ "$VERIFIED_REF" = "null" ]; then
|
||||
echo "Unable to determine verified digest for $image" >> "$LOG_FILE" 2>&1
|
||||
exit 1
|
||||
fi
|
||||
docker buildx imagetools create --tag $HOSTNAME:5000/$IMAGEREPO/$image "$VERIFIED_REF" >> "$LOG_FILE" 2>&1 || {
|
||||
echo "Unable to copy $image to embedded registry" >> "$LOG_FILE" 2>&1
|
||||
exit 1
|
||||
}
|
||||
fi
|
||||
else
|
||||
echo "There is a problem downloading the $image image. Details: " >> "$LOG_FILE" 2>&1
|
||||
echo "" >> "$LOG_FILE" 2>&1
|
||||
echo $GPGTEST >> "$LOG_FILE" 2>&1
|
||||
# Nothing is copied or pulled unless every image verified (a bad signature
|
||||
# publishes nothing). The hook runs in the parent: it mutates caller globals.
|
||||
local progress_hook
|
||||
if [ -z "$PROGRESS_CALLBACK" ]; then
|
||||
progress_hook=log_downloading
|
||||
else
|
||||
progress_hook=$PROGRESS_CALLBACK
|
||||
fi
|
||||
|
||||
# One preflight before the pool, so every verify job does not spend the long
|
||||
# retry budget in parallel. It is a quick check: a definite answer from the
|
||||
# registry ends it at once, and only an unclear error gets one more try.
|
||||
# Upstream registry, not :5000. --foreground keeps it in this shell's process
|
||||
# group, so Ctrl-C reaches it before launch_pool installs its own trap.
|
||||
if [ ${#TRUSTED_CONTAINERS[@]} -gt 0 ]; then
|
||||
local preflight_image preflight_ref preflight_out
|
||||
local attempt=1 preflight_ok=0 preflight_kind=transient
|
||||
read -r preflight_image _ < <(resolve_image "${TRUSTED_CONTAINERS[0]}")
|
||||
preflight_ref=$(image_ref "$preflight_image")
|
||||
while [ "$attempt" -le "$PREFLIGHT_ATTEMPTS" ]; do
|
||||
if preflight_out=$(timeout --foreground "$IMAGE_INSPECT_TIMEOUT" \
|
||||
docker buildx imagetools inspect --raw "$preflight_ref" 2>&1); then
|
||||
preflight_ok=1
|
||||
break
|
||||
fi
|
||||
# A registry answer never changes on a retry; anything else might.
|
||||
case "$preflight_out" in
|
||||
*"not found"*|*"manifest unknown"*) preflight_kind=notfound ;;
|
||||
*denied*|*unauthorized*) preflight_kind=denied ;;
|
||||
esac
|
||||
if [ "$preflight_kind" != transient ]; then
|
||||
break
|
||||
fi
|
||||
attempt=$((attempt + 1))
|
||||
if [ "$attempt" -le "$PREFLIGHT_ATTEMPTS" ]; then
|
||||
sleep "$PREFLIGHT_RETRY_DELAY"
|
||||
fi
|
||||
done
|
||||
if [ "$preflight_ok" -ne 1 ]; then
|
||||
echo "Could not inspect $preflight_ref on $CONTAINER_REGISTRY" >>"$LOG_FILE" 2>&1
|
||||
case "$preflight_kind" in
|
||||
notfound) echo "The image or tag for $preflight_image was not found" >>"$LOG_FILE" 2>&1 ;;
|
||||
denied) echo "Access to $preflight_ref was denied by $CONTAINER_REGISTRY" >>"$LOG_FILE" 2>&1 ;;
|
||||
*) echo "Check connectivity to $CONTAINER_REGISTRY or the proxy" >>"$LOG_FILE" 2>&1 ;;
|
||||
esac
|
||||
echo "$preflight_out" >>"$LOG_FILE" 2>&1
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
launch_pool verify_trusted_image verify "$jobs" "$progress_hook" "${TRUSTED_CONTAINERS[@]}"
|
||||
|
||||
pool_collect verify "${TRUSTED_CONTAINERS[@]}" || exit 1
|
||||
|
||||
# Verify only from here: no copy and no local pull.
|
||||
if [[ -n "$SKIP_TAGPUSH" ]]; then
|
||||
return 0
|
||||
fi
|
||||
|
||||
local -A ref_manifest=()
|
||||
for i in "${TRUSTED_CONTAINERS[@]}"; do
|
||||
{ read -r _; read -r _; read -r ref_manifest["$i"]; } < "$SIGNPATH/$i.ref"
|
||||
done
|
||||
|
||||
# Copy in waves: a wave's images share no unstored blob, so each layer is
|
||||
# downloaded once. The parent must record the blob map (subshells can't).
|
||||
local -a remaining=("${TRUSTED_CONTAINERS[@]}")
|
||||
local wave_no=0
|
||||
while [ ${#remaining[@]} -gt 0 ]; do
|
||||
wave_no=$((wave_no + 1))
|
||||
local -a wave=() deferred=()
|
||||
local -A claimed=()
|
||||
local img digest conflict
|
||||
for img in "${remaining[@]}"; do
|
||||
conflict=0
|
||||
while IFS= read -r digest; do
|
||||
[ -z "$digest" ] && continue
|
||||
[ -n "${pushed_blob_repo[$digest]:-}" ] && continue
|
||||
if [ -n "${claimed[$digest]:-}" ]; then
|
||||
conflict=1
|
||||
break
|
||||
fi
|
||||
done < <(manifest_blob_digests "${ref_manifest[$img]}")
|
||||
if [ "$conflict" -eq 0 ]; then
|
||||
wave+=("$img")
|
||||
while IFS= read -r digest; do
|
||||
[ -n "$digest" ] && claimed["$digest"]=1
|
||||
done < <(manifest_blob_digests "${ref_manifest[$img]}")
|
||||
else
|
||||
deferred+=("$img")
|
||||
fi
|
||||
done
|
||||
if [ ${#wave[@]} -eq 0 ]; then
|
||||
wave=("${remaining[0]}")
|
||||
deferred=("${remaining[@]:1}")
|
||||
fi
|
||||
|
||||
echo "Copying images (batch $wave_no): ${wave[*]}" >> "$LOG_FILE" 2>&1
|
||||
launch_pool copy_verified_image copy "$jobs" "" "${wave[@]}"
|
||||
|
||||
pool_collect copy "${wave[@]}" || exit 1
|
||||
for img in "${wave[@]}"; do
|
||||
record_shared_blobs "$img" "${ref_manifest[$img]}" pushed_blob_repo
|
||||
done
|
||||
remaining=("${deferred[@]}")
|
||||
done
|
||||
|
||||
launch_pool pull_verified_image pull "$jobs" "" "${TRUSTED_CONTAINERS[@]}"
|
||||
pool_collect pull "${TRUSTED_CONTAINERS[@]}" || exit 1
|
||||
}
|
||||
@@ -164,7 +164,6 @@ if [[ $EXCLUDE_FALSE_POSITIVE_ERRORS == 'Y' ]]; then
|
||||
EXCLUDED_ERRORS="$EXCLUDED_ERRORS|syncing rule" # false positive (rule sync log line includes rule name which can contain 'error')
|
||||
EXCLUDED_ERRORS="$EXCLUDED_ERRORS|request_unauthorized" # false positive (login failures to Hydra result in an 'error' log)
|
||||
EXCLUDED_ERRORS="$EXCLUDED_ERRORS|adding index lifecycle policy" # false positive (elasticsearch policy names contain 'error')
|
||||
EXCLUDED_ERRORS="$EXCLUDED_ERRORS|updating index lifecycle policy" # false positive (elasticsearch policy names contain 'error')
|
||||
EXCLUDED_ERRORS="$EXCLUDED_ERRORS|adding ingest pipeline" # false positive (elasticsearch ingest pipeline names contain 'error')
|
||||
EXCLUDED_ERRORS="$EXCLUDED_ERRORS|updating index template" # false positive (elasticsearch index or template names contain 'error')
|
||||
EXCLUDED_ERRORS="$EXCLUDED_ERRORS|updating component template" # false positive (elasticsearch index or template names contain 'error')
|
||||
@@ -180,7 +179,6 @@ if [[ $EXCLUDE_FALSE_POSITIVE_ERRORS == 'Y' ]]; then
|
||||
EXCLUDED_ERRORS="$EXCLUDED_ERRORS|Static assets preprocessor only supports GET and HEAD requests" # expected WARN log lines indicating invalid auth header
|
||||
EXCLUDED_ERRORS="$EXCLUDED_ERRORS|respondError" # respondError is a function name, output via http middleware as standard request logging
|
||||
EXCLUDED_ERRORS="$EXCLUDED_ERRORS|GET /kibana/" # Ignore Kibana queries with triggered words
|
||||
EXCLUDED_ERRORS="$EXCLUDED_ERRORS|error-logs" # Elastic indexes can contain error-logs in their names, which can trigger false positives in log checks
|
||||
fi
|
||||
|
||||
if [[ $EXCLUDE_KNOWN_ERRORS == 'Y' ]]; then
|
||||
|
||||
@@ -41,7 +41,6 @@
|
||||
'logstash.node': 'logstash.stack_monitoring.node',
|
||||
'logstash.node_cel': 'logstash.node',
|
||||
'logstash.node_stats': 'logstash.stack_monitoring.node_stats',
|
||||
'mqtt.traces': 'traces-mqtt.traces',
|
||||
'synthetics.browser': 'synthetics-browser',
|
||||
'synthetics.browser_network': 'synthetics-browser.network',
|
||||
'synthetics.browser_screenshot': 'synthetics-browser.screenshot',
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
elasticsearch:
|
||||
enabled: false
|
||||
esheap: '600m'
|
||||
version: 9.4.10
|
||||
version: 9.4.8
|
||||
index_clean: true
|
||||
data_retention_method: DLM
|
||||
vm:
|
||||
|
||||
@@ -17,10 +17,7 @@ elasticsearch:
|
||||
global: True
|
||||
advanced: True
|
||||
esheap:
|
||||
description: Heap size to use for Elasticsearch, as a number followed by m (megabytes) or g (gigabytes), such as 600m.
|
||||
forcedType: string
|
||||
regex: ^[1-9][0-9]*[mMgG]$
|
||||
regexFailureMessage: Must be a number followed by m or g, such as 600m.
|
||||
description: Specify the memory heap size in (m)egabytes for Elasticsearch.
|
||||
helpLink: elasticsearch
|
||||
index_clean:
|
||||
description: Determines if indices should be considered for deletion by available disk space in the cluster. Otherwise, data is retained by the configured lifecycle settings. This setting only applies to EVAL, STANDALONE, and HEAVY NODE installations. Other installations use lifecycle settings only.
|
||||
|
||||
@@ -140,23 +140,7 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"dynamic_templates": [
|
||||
{
|
||||
"event_data_scalars_as_keyword": {
|
||||
"path_match": "event_data.*",
|
||||
"match_mapping_type": [
|
||||
"long",
|
||||
"double",
|
||||
"boolean"
|
||||
],
|
||||
"mapping": {
|
||||
"type": "keyword",
|
||||
"ignore_above": 1024
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"_meta": {
|
||||
|
||||
@@ -8,10 +8,10 @@ influxdb:
|
||||
flux-log-enabled: false
|
||||
hardening-enabled: true
|
||||
http-bind-address: :8086
|
||||
http-idle-timeout: 0s
|
||||
http-idle-timeout: 0
|
||||
http-read-header-timeout: 10s
|
||||
http-read-timeout: 0s
|
||||
http-write-timeout: 0s
|
||||
http-read-timeout: 0
|
||||
http-write-timeout: 0
|
||||
influxql-max-select-buckets: 0
|
||||
influxql-max-select-point: 0
|
||||
influxql-max-select-series: 0
|
||||
|
||||
@@ -42,17 +42,17 @@ influxdb:
|
||||
advanced: True
|
||||
helpLink: influxdb
|
||||
http-idle-timeout:
|
||||
description: Keep-alive timeout while a connection waits for new requests. A value of 0s is the same as no timeout enforced.
|
||||
description: Keep-alive timeout while a connection waits for new requests. A value of 0 is the same as no timeout enforced.
|
||||
global: True
|
||||
advanced: True
|
||||
helpLink: influxdb
|
||||
http-read-header-timeout:
|
||||
description: The duration to wait for a request header before closing the connection. A value of 0s is the same as no timeout enforced.
|
||||
description: The duration to wait for a request header before closing the connection. A value of 0 is the same as no timeout enforced.
|
||||
global: True
|
||||
advanced: True
|
||||
helpLink: influxdb
|
||||
http-read-timeout:
|
||||
description: The duration to wait for the request to be fully read before closing the connection. A value of 0s is the same as no timeout enforced.
|
||||
description: The duration to wait for the request to be fully read before closing the connection. A value of 0 is the same as no timeout enforced.
|
||||
global: True
|
||||
advanced: True
|
||||
helpLink: influxdb
|
||||
|
||||
@@ -128,7 +128,7 @@ lookup_org_id_with_wait() {
|
||||
wait=10
|
||||
while [[ $attempts -lt $max_attempts ]]; do
|
||||
response=$(request orgs?org=Security+Onion)
|
||||
oid=$(echo "$response" | jq -r ".orgs[]? | select(.name == \"Security Onion\").id")
|
||||
oid=$(echo "$response" | jq -r ".orgs[] | select(.name == \"Security Onion\").id")
|
||||
if [[ -z $oid ]]; then
|
||||
attempts=$((attempts+1))
|
||||
log "Server does not appear to be running or fully initialized - will try again in $wait seconds ($attempts / $max_attempts)"
|
||||
|
||||
@@ -22,7 +22,7 @@ kibana:
|
||||
- default
|
||||
- file
|
||||
migrations:
|
||||
discardCorruptObjects: "9.4.10"
|
||||
discardCorruptObjects: "9.4.8"
|
||||
telemetry:
|
||||
enabled: False
|
||||
xpack:
|
||||
|
||||
@@ -403,11 +403,8 @@ logstash:
|
||||
custom8: *pipeline_settings
|
||||
custom9: *pipeline_settings
|
||||
settings:
|
||||
lsheap:
|
||||
description: Heap size to use for Logstash, as a number followed by m (megabytes) or g (gigabytes), such as 500m.
|
||||
forcedType: string
|
||||
regex: ^[1-9][0-9]*[mMgG]$
|
||||
regexFailureMessage: Must be a number followed by m or g, such as 500m.
|
||||
lsheap:
|
||||
description: Heap size to use for logstash
|
||||
helpLink: logstash
|
||||
global: False
|
||||
config:
|
||||
|
||||
@@ -16,11 +16,7 @@ For each intent file under /opt/so/state/push_pending/*.json whose last_touch
|
||||
is older than debounce_seconds, this script:
|
||||
* concatenates the actions lists from every ready intent
|
||||
* dedupes by (state or __highstate__, tgt, tgt_type)
|
||||
* narrows each target to minions that have completed a highstate
|
||||
* keeps the part of an action that would reach a node still in its first highstate in
|
||||
push_pending/pending_<id>.json, which drains like any other intent once that highstate completes
|
||||
* drops actions whose target matches no accepted minion (e.g. a role with no nodes yet)
|
||||
* holds everything for a later pass while salt-master has only just started
|
||||
* dispatches a single `salt-run state.orchestrate orch.push_batch --async`
|
||||
with the deduped actions list passed as pillar kwargs
|
||||
* deletes the contributed intent files on successful dispatch
|
||||
@@ -50,25 +46,11 @@ PENDING_DIR = '/opt/so/state/push_pending'
|
||||
LOCK_FILE = os.path.join(PENDING_DIR, '.lock')
|
||||
LOG_FILE = '/opt/so/log/salt/so-push-drainer.log'
|
||||
MASTER_CONFIG = '/etc/salt/master'
|
||||
MASTER_PIDFILE = '/var/run/salt-master.pid'
|
||||
MINION_KEYS_DIR = '/etc/salt/pki/master/minions'
|
||||
MAX_PATHS = 20
|
||||
|
||||
# Minions rejoin a restarted master's publisher up to ~22s after it returns (zmq reconnect interval
|
||||
# plus jitter, each up to recon_default + recon_max) and a job published before then reaches nobody.
|
||||
# Doubled to allow for a slow master start.
|
||||
MASTER_SETTLE_SECONDS = 45
|
||||
|
||||
DISPATCHED_DIR = '/opt/so/state/push_dispatched'
|
||||
|
||||
HIGHSTATE_SENTINEL = '__highstate__'
|
||||
|
||||
# Grain written by setup and removed by salt.lasthighstate at the end of the node's first highstate.
|
||||
PENDING_GRAIN = 'first_highstate_pending'
|
||||
|
||||
# Node ids from the master's cache go into kept intent file names and targets.
|
||||
ID_RE = re.compile(r'[A-Za-z0-9._-]{1,253}')
|
||||
|
||||
RESULT_CHECK_DELAY = 30
|
||||
RESULT_RECHECK_MAX = 300
|
||||
RESULT_MAX_AGE = 7200
|
||||
@@ -78,8 +60,6 @@ TEXT_LIMIT = 500
|
||||
# Lead-in salt puts on the comment of an orchestration step that raised.
|
||||
STEP_RAISED = 'An exception occurred in this state:'
|
||||
|
||||
NO_RETURN = 'no return received'
|
||||
|
||||
# salt-run --async reports the jid only in a log line (stderr by default).
|
||||
JID_RE = re.compile(r'salt/run/(\d{20})')
|
||||
|
||||
@@ -137,134 +117,27 @@ def _dedupe_actions(actions):
|
||||
return deduped
|
||||
|
||||
|
||||
def _skip_pending(action):
|
||||
"""Narrows a compound target to minions that have completed a highstate. A newly accepted node matches
|
||||
its role's targets before orch.deploy_newnode has highstated it, and a single state fails there."""
|
||||
if action.get('tgt_type', 'compound') != 'compound':
|
||||
return action
|
||||
return dict(action, tgt='( {} ) and not G@{}:True'.format(action.get('tgt'), PENDING_GRAIN))
|
||||
|
||||
|
||||
def _ckminions():
|
||||
return salt.utils.minions.CkMinions(salt.config.master_config(MASTER_CONFIG))
|
||||
|
||||
|
||||
def _pending_minions(ckminions, log):
|
||||
try:
|
||||
return set(ckminions.check_minions('G@{}:True'.format(PENDING_GRAIN), 'compound').get('minions') or [])
|
||||
except Exception as exc:
|
||||
log.warning('cannot list nodes still in their first highstate; keeping no pushes for them: %s', exc)
|
||||
return set()
|
||||
|
||||
|
||||
def _targeted(actions, log):
|
||||
"""Returns (targeted, kept). Drops actions whose target matches no accepted minion (e.g. a role with no
|
||||
nodes yet), which the orchestration would otherwise report as failed with 'No minions responded'. The part
|
||||
of a compound action that would reach a node still in its first highstate is returned in kept, by node id,
|
||||
narrowed to that node, so it can be applied once that highstate completes."""
|
||||
"""Drops actions whose target matches no accepted minion (e.g. a role with no nodes yet), which
|
||||
the orchestration would otherwise report as failed with 'No minions responded'."""
|
||||
try:
|
||||
ckminions = _ckminions()
|
||||
ckminions = salt.utils.minions.CkMinions(salt.config.master_config(MASTER_CONFIG))
|
||||
except Exception:
|
||||
log.exception('cannot load master config; dispatching without checking targets')
|
||||
return [_skip_pending(action) for action in actions], {}
|
||||
pending = _pending_minions(ckminions, log)
|
||||
return actions
|
||||
targeted = []
|
||||
kept = {}
|
||||
for action in actions:
|
||||
narrowed = _skip_pending(action)
|
||||
tgt_type = action.get('tgt_type', 'compound')
|
||||
name = 'highstate' if action.get('highstate') else action.get('state')
|
||||
try:
|
||||
matched = ckminions.check_minions(narrowed['tgt'], tgt_type).get('minions')
|
||||
unwrapped = []
|
||||
if pending and tgt_type == 'compound':
|
||||
unwrapped = ckminions.check_minions(action['tgt'], tgt_type).get('minions')
|
||||
matched = ckminions.check_minions(action['tgt'], action.get('tgt_type', 'compound')).get('minions')
|
||||
except Exception:
|
||||
log.exception('cannot resolve tgt=%s; dispatching it anyway', narrowed.get('tgt'))
|
||||
matched, unwrapped = True, []
|
||||
held = False
|
||||
for minion in sorted(pending.intersection(unwrapped or [])):
|
||||
if not ID_RE.fullmatch(minion):
|
||||
log.warning('not keeping %s for %r: not a valid node id', name, minion)
|
||||
continue
|
||||
kept.setdefault(minion, []).append(
|
||||
dict(action, tgt='L@{} and ( {} )'.format(minion, action['tgt']), tgt_type='compound'))
|
||||
held = True
|
||||
log.exception('cannot resolve tgt=%s; dispatching it anyway', action.get('tgt'))
|
||||
matched = True
|
||||
if matched:
|
||||
targeted.append(narrowed)
|
||||
elif not held:
|
||||
log.info('skipping %s: no minions match tgt=%s', name, action['tgt'])
|
||||
return targeted, kept
|
||||
|
||||
|
||||
def _kept_path(node):
|
||||
return os.path.join(PENDING_DIR, 'pending_{}.json'.format(node))
|
||||
|
||||
|
||||
def _keep_for_pending(kept, paths, log):
|
||||
"""Merges each node's kept actions into its pending_<id>.json. The caller already holds the lock, which
|
||||
flock would not grant a second time. Returns False if any write failed."""
|
||||
now = time.time()
|
||||
written = True
|
||||
for node, actions in kept.items():
|
||||
path = _kept_path(node)
|
||||
intent = _read_intent(path, log) if os.path.exists(path) else {}
|
||||
if not isinstance(intent, dict):
|
||||
intent = {}
|
||||
known = intent.get('paths') or []
|
||||
intent.update(
|
||||
actions=_dedupe_actions((intent.get('actions') or []) + actions),
|
||||
pending=node,
|
||||
last_touch=now,
|
||||
paths=(known + [p for p in paths if p not in known])[-MAX_PATHS:],
|
||||
)
|
||||
intent.setdefault('first_touch', now)
|
||||
try:
|
||||
tmp_path = path + '.tmp'
|
||||
with open(tmp_path, 'w') as f:
|
||||
json.dump(intent, f)
|
||||
os.rename(tmp_path, path)
|
||||
except (OSError, ValueError) as exc:
|
||||
log.error('cannot keep pushes for %s until its first highstate completes: %s', node, exc)
|
||||
written = False
|
||||
continue
|
||||
prefix = 'L@{} and ( '.format(node)
|
||||
for action in actions:
|
||||
tgt = action['tgt']
|
||||
if tgt.startswith(prefix) and tgt.endswith(' )'):
|
||||
tgt = tgt[len(prefix):-len(' )')]
|
||||
log.info('push kept for %s until its first highstate completes: %s tgt=%s', node,
|
||||
'highstate' if action.get('highstate') else action.get('state'), tgt)
|
||||
return written
|
||||
|
||||
|
||||
def _still_pending(ckminions, ids, log):
|
||||
"""Ids whose first highstate has not completed. A node with no cache entry has not compiled pillar yet."""
|
||||
pending = set()
|
||||
for node in ids:
|
||||
try:
|
||||
data = ckminions.cache.fetch('minions/{}'.format(node), 'data')
|
||||
except Exception as exc:
|
||||
log.warning('cannot read the cached grains of %s; holding its kept pushes: %s', node, exc)
|
||||
pending.add(node)
|
||||
continue
|
||||
grains = data.get('grains') if isinstance(data, dict) else None
|
||||
if not isinstance(grains, dict) or PENDING_GRAIN in grains:
|
||||
pending.add(node)
|
||||
return pending
|
||||
|
||||
|
||||
def _master_settling(now):
|
||||
"""True while salt-master started less than MASTER_SETTLE_SECONDS ago. salt-master writes its pidfile
|
||||
when it starts, so the file's mtime is the master's start time. Minions take up to ~22s to rejoin a
|
||||
restarted master's publisher and a job published before then reaches nobody, so dispatch is held;
|
||||
held intents stay in push_pending and are drained on a later pass. A missing or unreadable pidfile
|
||||
returns False: the master is then normally not running, so _dispatch fails and keeps the intents."""
|
||||
try:
|
||||
age = now - os.path.getmtime(MASTER_PIDFILE)
|
||||
except OSError:
|
||||
return False
|
||||
return 0 <= age < MASTER_SETTLE_SECONDS
|
||||
targeted.append(action)
|
||||
else:
|
||||
log.info('skipping %s: no minions match tgt=%s',
|
||||
'highstate' if action.get('highstate') else action.get('state'), action.get('tgt'))
|
||||
return targeted
|
||||
|
||||
|
||||
def _dispatch(actions, log):
|
||||
@@ -348,10 +221,6 @@ def _lookup_jid(jid, log):
|
||||
|
||||
|
||||
def _minion_failure(minion_ret):
|
||||
# What salt.state records for a minion it stopped waiting on: no reply to a saltutil.find_job
|
||||
# poll within gather_job_timeout, though the state run may still be queued or running.
|
||||
if minion_ret == {}:
|
||||
return NO_RETURN
|
||||
if isinstance(minion_ret, dict):
|
||||
return '; '.join(
|
||||
'{}: {}'.format(state.get('__id__', state_key), _trim(state.get('comment', '')))
|
||||
@@ -414,21 +283,11 @@ def _failed_steps(ret):
|
||||
return steps
|
||||
|
||||
|
||||
def _lost_track(step):
|
||||
changes = step.get('changes')
|
||||
minion_rets = changes.get('ret') if isinstance(changes, dict) else None
|
||||
if not isinstance(minion_rets, dict):
|
||||
return False
|
||||
failed = [text for text in map(_minion_failure, minion_rets.values()) if text]
|
||||
return bool(failed) and all(text == NO_RETURN for text in failed)
|
||||
|
||||
|
||||
def _result_unknown(ret):
|
||||
# A step that raised (e.g. salt-master restarted while it waited on a queued state run) or
|
||||
# stopped waiting never collected the minion's return, so the state run may still have completed.
|
||||
# A step that raised (e.g. salt-master restarted while it waited on a queued state run)
|
||||
# never collected the minion's return, so the state run may still have completed.
|
||||
steps = _failed_steps(ret)
|
||||
return bool(steps) and all(
|
||||
str(step.get('comment', '')).startswith(STEP_RAISED) or _lost_track(step) for step in steps)
|
||||
return bool(steps) and all(str(step.get('comment', '')).startswith(STEP_RAISED) for step in steps)
|
||||
|
||||
|
||||
def _recheck_delay(age):
|
||||
@@ -528,39 +387,18 @@ def main():
|
||||
now = time.time()
|
||||
ready = []
|
||||
skipped = 0
|
||||
held = 0
|
||||
broken = []
|
||||
for path in intent_files:
|
||||
intent = _read_intent(path, log)
|
||||
if not isinstance(intent, dict):
|
||||
broken.append(path)
|
||||
continue
|
||||
node = intent.get('pending')
|
||||
if node is not None and not (isinstance(node, str) and ID_RE.fullmatch(node)):
|
||||
log.warning('removing kept intent %s: %r is not a valid node id', path, node)
|
||||
broken.append(path)
|
||||
continue
|
||||
if node is not None and not os.path.exists(os.path.join(MINION_KEYS_DIR, node)):
|
||||
log.info('removing kept pushes for %s: its key is no longer accepted', node)
|
||||
broken.append(path)
|
||||
continue
|
||||
last_touch = intent.get('last_touch', 0)
|
||||
if now - last_touch < debounce_seconds:
|
||||
skipped += 1
|
||||
continue
|
||||
ready.append((path, intent))
|
||||
|
||||
kept_nodes = {intent['pending'] for _, intent in ready if intent.get('pending') is not None}
|
||||
if kept_nodes:
|
||||
try:
|
||||
still_pending = _still_pending(_ckminions(), kept_nodes, log)
|
||||
except Exception as exc:
|
||||
log.warning('cannot load master config; holding kept pushes: %s', exc)
|
||||
still_pending = kept_nodes
|
||||
waiting = {path for path, intent in ready if intent.get('pending') in still_pending}
|
||||
held = len(waiting)
|
||||
ready = [(path, intent) for path, intent in ready if path not in waiting]
|
||||
|
||||
for path in broken:
|
||||
try:
|
||||
os.unlink(path)
|
||||
@@ -568,13 +406,8 @@ def main():
|
||||
pass
|
||||
|
||||
if not ready:
|
||||
if skipped or held:
|
||||
log.debug('no ready intents (%d still in debounce window, %d for nodes still in their first highstate)',
|
||||
skipped, held)
|
||||
return 0
|
||||
|
||||
if _master_settling(now):
|
||||
log.info('salt-master just started; holding %d intent(s) until minions reconnect', len(ready))
|
||||
if skipped:
|
||||
log.debug('no ready intents (%d still in debounce window)', skipped)
|
||||
return 0
|
||||
|
||||
combined_actions = []
|
||||
@@ -602,32 +435,24 @@ def main():
|
||||
'draining %d intent(s): %d action(s) after dedupe (raw=%d), '
|
||||
'debounce_duration=%.1fs, paths=%s',
|
||||
len(ready), len(deduped), len(combined_actions),
|
||||
debounce_duration, all_paths[:MAX_PATHS],
|
||||
debounce_duration, all_paths[:20],
|
||||
)
|
||||
for action in deduped:
|
||||
log.info('action: %s tgt=%s', 'highstate' if action.get('highstate') else action.get('state'),
|
||||
action.get('tgt'))
|
||||
|
||||
targeted, kept = _targeted(deduped, log)
|
||||
if kept and not _keep_for_pending(kept, all_paths, log):
|
||||
log.warning('cannot keep pushes for nodes still in their first highstate; '
|
||||
'leaving intent files in place for retry')
|
||||
return 1
|
||||
written = {_kept_path(node) for node in kept}
|
||||
|
||||
targeted = _targeted(deduped, log)
|
||||
if targeted:
|
||||
jid = _dispatch(targeted, log)
|
||||
if jid is None:
|
||||
log.warning('dispatch failed; leaving intent files in place for retry')
|
||||
return 1
|
||||
if jid:
|
||||
_record_dispatch(jid, targeted, all_paths[:MAX_PATHS], log)
|
||||
elif not kept:
|
||||
_record_dispatch(jid, targeted, all_paths[:20], log)
|
||||
else:
|
||||
log.info('no action matches a minion; nothing to dispatch')
|
||||
|
||||
for path, _ in ready:
|
||||
if path in written:
|
||||
continue
|
||||
try:
|
||||
os.unlink(path)
|
||||
except OSError:
|
||||
|
||||
@@ -3,18 +3,14 @@
|
||||
# https://securityonion.net/license; you may not use this file except in compliance with the
|
||||
# Elastic License 2.0.
|
||||
|
||||
import errno
|
||||
import fcntl
|
||||
import importlib.util
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import unittest
|
||||
from importlib.machinery import SourceFileLoader
|
||||
@@ -38,8 +34,6 @@ JID = '20260930171554259426'
|
||||
ASYNC_STDERR = ('[WARNING ] Running in asynchronous mode. Results of this execution may be collected '
|
||||
'by attaching to the master event bus or by examining the master job cache, if '
|
||||
'configured. This execution is running under tag salt/run/{}\n'.format(JID))
|
||||
NOT_PENDING = ' and not G@first_highstate_pending:True'
|
||||
PENDING_TGT = 'G@first_highstate_pending:True'
|
||||
CONFLICT = ('The function "state.sls" is running as PID 372218 and was started at '
|
||||
'2026, Sep 30 17:15:40.466233 with jid 20260930171540466233')
|
||||
|
||||
@@ -94,22 +88,6 @@ RAISED_RET = _orch_ret(dict(REFRESH_STEP, **{
|
||||
},
|
||||
}), success=False)
|
||||
|
||||
LOST_RET = _orch_ret(dict(REFRESH_STEP, **{
|
||||
'salt_|-apply_soc_1_|-apply_soc_1_|-state': {
|
||||
'__id__': 'apply_soc_1', 'result': False,
|
||||
'changes': {'out': 'highstate', 'ret': {'manager_standalone': {}}},
|
||||
'comment': 'Run failed on minions: manager_standalone',
|
||||
},
|
||||
}), success=False)
|
||||
|
||||
LOST_AND_FAILED_RET = _orch_ret({
|
||||
'salt_|-apply_soc_1_|-apply_soc_1_|-state': {
|
||||
'__id__': 'apply_soc_1', 'result': False,
|
||||
'changes': {'out': 'highstate', 'ret': {'manager_standalone': {}, 'sensor1_sensor': [CONFLICT]}},
|
||||
'comment': 'Run failed on minions: manager_standalone, sensor1_sensor',
|
||||
},
|
||||
}, success=False)
|
||||
|
||||
SUCCESS_RET = _orch_ret(dict(REFRESH_STEP, **{
|
||||
'salt_|-apply_telegraf_1_|-apply_telegraf_1_|-state': {
|
||||
'__id__': 'apply_telegraf_1', 'result': True,
|
||||
@@ -221,17 +199,6 @@ class TestHelpers(DrainerTestCase):
|
||||
drainer._unlink(self.tmpdir, self.log)
|
||||
self.log.exception.assert_called_once()
|
||||
|
||||
def test_master_settling(self):
|
||||
pidfile = os.path.join(self.tmpdir, 'salt-master.pid')
|
||||
now = time.time()
|
||||
with patch.object(drainer, 'MASTER_PIDFILE', pidfile):
|
||||
self.assertFalse(drainer._master_settling(now))
|
||||
self.write_json(self.tmpdir, 'salt-master.pid', '1100')
|
||||
for age, settling in ((0, True), (drainer.MASTER_SETTLE_SECONDS - 1, True),
|
||||
(drainer.MASTER_SETTLE_SECONDS, False), (-60, False)):
|
||||
os.utime(pidfile, (now - age, now - age))
|
||||
self.assertIs(drainer._master_settling(now), settling, age)
|
||||
|
||||
|
||||
class TestDispatch(DrainerTestCase):
|
||||
|
||||
@@ -298,13 +265,6 @@ class TestResults(DrainerTestCase):
|
||||
self.assertEqual(drainer._minion_failure('Rendering SLS failed'), 'Rendering SLS failed')
|
||||
self.assertEqual(drainer._minion_failure(True), '')
|
||||
self.assertEqual(drainer._minion_failure({'a': {'result': True}}), '')
|
||||
self.assertEqual(drainer._minion_failure({}), drainer.NO_RETURN)
|
||||
|
||||
def test_orch_failures_lost(self):
|
||||
self.assertEqual(drainer._orch_failures(LOST_RET), [
|
||||
'apply_soc_1: Run failed on minions: manager_standalone',
|
||||
'manager_standalone: no return received',
|
||||
])
|
||||
|
||||
def test_orch_failures_conflict(self):
|
||||
failures = drainer._orch_failures(CONFLICT_RET)
|
||||
@@ -348,17 +308,7 @@ class TestResults(DrainerTestCase):
|
||||
|
||||
def test_result_unknown(self):
|
||||
self.assertTrue(drainer._result_unknown(RAISED_RET))
|
||||
self.assertTrue(drainer._result_unknown(LOST_RET))
|
||||
changed = json.loads(json.dumps(LOST_RET))
|
||||
changed[MASTER]['return']['data'][MASTER]['salt_|-apply_soc_1_|-apply_soc_1_|-state']['changes']['ret'][
|
||||
'sensor1_sensor'] = {'file_|-a_|-a_|-managed': {'result': True, 'changes': {'diff': 'x'}}}
|
||||
self.assertTrue(drainer._result_unknown(changed))
|
||||
odd = _orch_ret({'salt_|-apply_soc_1_|-apply_soc_1_|-state': {
|
||||
'__id__': 'apply_soc_1', 'result': False, 'changes': 'Run failed', 'comment': 'Run failed on minions',
|
||||
}}, success=False)
|
||||
self.assertFalse(drainer._result_unknown(odd))
|
||||
for ret in (CONFLICT_RET, STATE_FAIL_RET, SUCCESS_RET, LOST_AND_FAILED_RET, ['No minions matched'],
|
||||
{MASTER: 'odd'},
|
||||
for ret in (CONFLICT_RET, STATE_FAIL_RET, SUCCESS_RET, ['No minions matched'], {MASTER: 'odd'},
|
||||
{MASTER: {'return': {'data': {MASTER: ['Rendering SLS failed']}}, 'success': False}}):
|
||||
self.assertFalse(drainer._result_unknown(ret), ret)
|
||||
mixed = _orch_ret(dict(RAISED_RET[MASTER]['return']['data'][MASTER],
|
||||
@@ -400,21 +350,6 @@ class TestResults(DrainerTestCase):
|
||||
self.assertIn('AuthenticationError: Authentication error occurred.', self.logged('warning'))
|
||||
self.assertNotIn('6_unknown', self.logged('error'))
|
||||
|
||||
def test_check_dispatched_lost(self):
|
||||
now = time.time()
|
||||
results = {'1_lost': LOST_RET, '2_lost_and_failed': LOST_AND_FAILED_RET}
|
||||
paths = [self.record(jid, 60, now) for jid in results]
|
||||
with patch.object(drainer, '_lookup_jid', side_effect=lambda jid, log: results[jid]):
|
||||
drainer._check_dispatched(self.log, now)
|
||||
|
||||
for path in paths:
|
||||
self.assertFalse(os.path.exists(path), path)
|
||||
self.assertIn('push result unknown jid=1_lost', self.logged('warning'))
|
||||
self.assertIn('manager_standalone: no return received', self.logged('warning'))
|
||||
self.assertNotIn('1_lost', self.logged('error'))
|
||||
self.assertIn('push failed jid=2_lost_and_failed', self.logged('error'))
|
||||
self.assertIn('is running as PID 372218', self.logged('error'))
|
||||
|
||||
def test_check_dispatched_survives_bad_result(self):
|
||||
now = time.time()
|
||||
bad = self.record('1_bad', 60, now)
|
||||
@@ -496,19 +431,8 @@ class TestTargeted(DrainerTestCase):
|
||||
self.CkMinions = patcher.start()
|
||||
self.addCleanup(patcher.stop)
|
||||
|
||||
def test_skip_pending(self):
|
||||
self.assertEqual(drainer._skip_pending({'state': 'soc', 'tgt': 'G@role:so-eval or G@role:so-manager'}),
|
||||
{'state': 'soc', 'tgt': '( G@role:so-eval or G@role:so-manager )' + NOT_PENDING})
|
||||
self.assertEqual(drainer._skip_pending({'highstate': True, 'tgt': '*', 'tgt_type': 'compound'}),
|
||||
{'highstate': True, 'tgt': '( * )' + NOT_PENDING, 'tgt_type': 'compound'})
|
||||
listed = {'state': 'soc', 'tgt': 'manager_manager', 'tgt_type': 'list'}
|
||||
self.assertEqual(drainer._skip_pending(listed), listed)
|
||||
|
||||
def test_drops_unmatched(self):
|
||||
sensor = '( G@role:so-sensor )' + NOT_PENDING
|
||||
heavynode = '( G@role:so-heavynode )' + NOT_PENDING
|
||||
idh = '( G@role:so-idh )' + NOT_PENDING
|
||||
matches = {sensor: ['sensor_sensor'], 'manager_manager': ['manager_manager']}
|
||||
matches = {'G@role:so-sensor': ['sensor_sensor'], 'manager_manager': ['manager_manager']}
|
||||
self.ckminions.check_minions.side_effect = lambda tgt, tgt_type: {'minions': matches.get(tgt, [])}
|
||||
actions = [
|
||||
{'state': 'strelka', 'tgt': 'G@role:so-sensor'},
|
||||
@@ -516,503 +440,30 @@ class TestTargeted(DrainerTestCase):
|
||||
{'highstate': True, 'tgt': 'G@role:so-idh'},
|
||||
{'state': 'soc', 'tgt': 'manager_manager', 'tgt_type': 'list'},
|
||||
]
|
||||
self.assertEqual(drainer._targeted(actions, self.log), ([{'state': 'strelka', 'tgt': sensor}, actions[3]], {}))
|
||||
self.assertEqual(drainer._targeted(actions, self.log), [actions[0], actions[3]])
|
||||
self.CkMinions.assert_called_once()
|
||||
self.assertEqual([c.args for c in self.ckminions.check_minions.call_args_list], [
|
||||
(PENDING_TGT, 'compound'), (sensor, 'compound'), (heavynode, 'compound'), (idh, 'compound'),
|
||||
('manager_manager', 'list'),
|
||||
('G@role:so-sensor', 'compound'), ('G@role:so-heavynode', 'compound'),
|
||||
('G@role:so-idh', 'compound'), ('manager_manager', 'list'),
|
||||
])
|
||||
info = self.logged('info')
|
||||
self.assertIn('skipping suricata: no minions match tgt=G@role:so-heavynode', info)
|
||||
self.assertIn('skipping highstate: no minions match tgt=G@role:so-idh', info)
|
||||
self.assertNotIn('strelka', info)
|
||||
|
||||
def test_list_target_unmatched(self):
|
||||
self.ckminions.check_minions.return_value = {'minions': []}
|
||||
actions = [{'state': 'soc', 'tgt': 'gone_manager', 'tgt_type': 'list'}]
|
||||
self.assertEqual(drainer._targeted(actions, self.log), ([], {}))
|
||||
self.assertEqual([c.args for c in self.ckminions.check_minions.call_args_list], [
|
||||
(PENDING_TGT, 'compound'), ('gone_manager', 'list'),
|
||||
])
|
||||
info = self.logged('info')
|
||||
self.assertIn('skipping soc: no minions match tgt=gone_manager', info)
|
||||
self.assertNotIn('first highstate', info)
|
||||
|
||||
def test_narrowed_match_checks_once(self):
|
||||
narrowed = '( G@role:so-sensor )' + NOT_PENDING
|
||||
self.ckminions.check_minions.side_effect = lambda tgt, tgt_type: {
|
||||
'minions': [] if tgt == PENDING_TGT else ['sensor_sensor']}
|
||||
actions = [{'state': 'suricata', 'tgt': 'G@role:so-sensor'}]
|
||||
self.assertEqual(drainer._targeted(actions, self.log), ([{'state': 'suricata', 'tgt': narrowed}], {}))
|
||||
self.assertEqual([c.args for c in self.ckminions.check_minions.call_args_list], [
|
||||
(PENDING_TGT, 'compound'), (narrowed, 'compound'),
|
||||
])
|
||||
|
||||
def test_pending_set_empty_no_extra_calls(self):
|
||||
self.ckminions.check_minions.side_effect = lambda tgt, tgt_type: {
|
||||
'minions': [] if tgt == PENDING_TGT else ['sensor_sensor']}
|
||||
actions = [
|
||||
{'state': 'suricata', 'tgt': 'G@role:so-sensor'},
|
||||
{'highstate': True, 'tgt': '*'},
|
||||
{'state': 'soc', 'tgt': 'manager_manager', 'tgt_type': 'list'},
|
||||
]
|
||||
targeted, kept = drainer._targeted(actions, self.log)
|
||||
self.assertEqual(len(targeted), 3)
|
||||
self.assertEqual(kept, {})
|
||||
tgts = [c.args[0] for c in self.ckminions.check_minions.call_args_list]
|
||||
self.assertEqual(tgts.count(PENDING_TGT), 1)
|
||||
self.assertEqual(len(tgts), 1 + len(actions))
|
||||
self.assertNotIn('G@role:so-sensor', tgts)
|
||||
|
||||
def test_list_target_not_kept(self):
|
||||
self.ckminions.check_minions.side_effect = lambda tgt, tgt_type: {'minions': ['manager_manager']}
|
||||
actions = [{'state': 'soc', 'tgt': 'manager_manager', 'tgt_type': 'list'}]
|
||||
self.assertEqual(drainer._targeted(actions, self.log), (actions, {}))
|
||||
self.assertEqual([c.args for c in self.ckminions.check_minions.call_args_list], [
|
||||
(PENDING_TGT, 'compound'), ('manager_manager', 'list'),
|
||||
])
|
||||
|
||||
def test_original_check_error_keeps_action(self):
|
||||
narrowed = '( G@role:so-sensor )' + NOT_PENDING
|
||||
results = {PENDING_TGT: {'minions': ['sensor_new']}, narrowed: {'minions': []}}
|
||||
|
||||
def check(tgt, tgt_type):
|
||||
if tgt not in results:
|
||||
raise RuntimeError('boom')
|
||||
return results[tgt]
|
||||
self.ckminions.check_minions.side_effect = check
|
||||
actions = [{'state': 'suricata', 'tgt': 'G@role:so-sensor'}]
|
||||
self.assertEqual(drainer._targeted(actions, self.log), ([{'state': 'suricata', 'tgt': narrowed}], {}))
|
||||
self.log.exception.assert_called_once()
|
||||
|
||||
def test_master_config_error_keeps_actions(self):
|
||||
actions = [{'state': 'soc', 'tgt': '*'}]
|
||||
with patch.object(drainer.salt.config, 'master_config', side_effect=OSError('no config')):
|
||||
self.assertEqual(drainer._targeted(actions, self.log), ([{'state': 'soc', 'tgt': '( * )' + NOT_PENDING}], {}))
|
||||
self.assertEqual(drainer._targeted(actions, self.log), actions)
|
||||
self.log.exception.assert_called_once()
|
||||
self.CkMinions.assert_not_called()
|
||||
|
||||
def test_check_error_keeps_action(self):
|
||||
actions = [{'state': 'soc', 'tgt': 'G@role:'}]
|
||||
self.ckminions.check_minions.side_effect = RuntimeError('bad target')
|
||||
self.assertEqual(drainer._targeted(actions, self.log), ([{'state': 'soc', 'tgt': '( G@role: )' + NOT_PENDING}], {}))
|
||||
self.assertEqual(drainer._targeted(actions, self.log), actions)
|
||||
self.log.exception.assert_called_once()
|
||||
|
||||
def test_pending_minions_error(self):
|
||||
self.ckminions.check_minions.side_effect = RuntimeError('cache unavailable')
|
||||
self.assertEqual(drainer._pending_minions(self.ckminions, self.log), set())
|
||||
self.assertIn('cannot list nodes still in their first highstate', self.logged('warning'))
|
||||
self.assertIn('cache unavailable', self.logged('warning'))
|
||||
|
||||
def test_still_pending(self):
|
||||
cache = {'minions/a': {'grains': {drainer.PENDING_GRAIN: True}}, 'minions/b': {'grains': {'role': 'so-sensor'}},
|
||||
'minions/c': {}}
|
||||
self.ckminions.cache.fetch.side_effect = lambda bank, key: cache[bank]
|
||||
self.assertEqual(drainer._still_pending(self.ckminions, {'a', 'b', 'c'}, self.log), {'a', 'c'})
|
||||
self.assertEqual({c.args[1] for c in self.ckminions.cache.fetch.call_args_list}, {'data'})
|
||||
self.log.warning.assert_not_called()
|
||||
|
||||
def test_still_pending_lookup_error(self):
|
||||
self.ckminions.cache.fetch.side_effect = OSError('cache read failed')
|
||||
self.assertEqual(drainer._still_pending(self.ckminions, {'a'}, self.log), {'a'})
|
||||
self.assertIn('cannot read the cached grains of a', self.logged('warning'))
|
||||
|
||||
|
||||
class FakeCkMinions:
|
||||
"""Evaluates the compound targets the drainer builds against a fixed set of role targets."""
|
||||
|
||||
def __init__(self):
|
||||
self.targets = {}
|
||||
self.accepted = set()
|
||||
self.pending = set()
|
||||
self.grains = {}
|
||||
self.fetch_error = None
|
||||
self.cache = MagicMock()
|
||||
self.cache.fetch.side_effect = self.fetch
|
||||
|
||||
def fetch(self, bank, key):
|
||||
if self.fetch_error:
|
||||
raise self.fetch_error
|
||||
node = bank.split('/', 1)[1]
|
||||
return {'grains': self.grains[node]} if node in self.grains else {}
|
||||
|
||||
def match(self, tgt):
|
||||
# Salt's greedy matching: an accepted minion with no cached grains matches any grain target.
|
||||
greedy = self.accepted - set(self.grains) if tgt.startswith('G@') else set()
|
||||
if tgt == PENDING_TGT:
|
||||
return self.pending | greedy
|
||||
wrapped = re.fullmatch(r'\( (.*) \)' + re.escape(NOT_PENDING), tgt)
|
||||
if wrapped:
|
||||
return self.match(wrapped.group(1)) - self.match(PENDING_TGT)
|
||||
narrowed = re.fullmatch(r'L@(\S+) and \( (.*) \)', tgt)
|
||||
if narrowed:
|
||||
return {narrowed.group(1)} & self.match(narrowed.group(2))
|
||||
return set(self.targets.get(tgt, [])) | greedy
|
||||
|
||||
def check_minions(self, tgt, tgt_type='compound'):
|
||||
return {'minions': sorted(self.match(tgt))}
|
||||
|
||||
def pend(self, *nodes):
|
||||
for node in nodes:
|
||||
self.pending.add(node)
|
||||
self.grains[node] = {'role': 'so-sensor', drainer.PENDING_GRAIN: True}
|
||||
|
||||
def release(self, *nodes):
|
||||
for node in nodes:
|
||||
self.pending.discard(node)
|
||||
self.grains[node] = {'role': 'so-sensor'}
|
||||
|
||||
|
||||
SURICATA = {'state': 'suricata', 'tgt': 'G@role:so-sensor'}
|
||||
|
||||
|
||||
def _kept_copy(node, action):
|
||||
return dict(action, tgt='L@{} and ( {} )'.format(node, action['tgt']), tgt_type='compound')
|
||||
|
||||
|
||||
class TestKeptPushes(DrainerTestCase):
|
||||
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.ck = FakeCkMinions()
|
||||
self.ck.targets = {'G@role:so-sensor': ['a', 'b', 'c'], 'G@role:so-searchnode': ['s'], '*': ['a', 'b', 'c', 's']}
|
||||
self.ck.release('a', 'b', 'c', 's')
|
||||
self.keys = os.path.join(self.tmpdir, 'keys')
|
||||
os.makedirs(self.keys)
|
||||
for node in ('a', 'b', 'c', 's'):
|
||||
self.accept(node)
|
||||
self.cfg = {'enabled': True, 'debounce_seconds': 30}
|
||||
self.run = MagicMock(return_value=MagicMock(stdout='', stderr=ASYNC_STDERR))
|
||||
for target, name, kwargs in (
|
||||
(drainer.salt.utils.minions, 'CkMinions', {'return_value': self.ck}),
|
||||
(drainer.subprocess, 'run', {'new': self.run}),
|
||||
(drainer, 'MINION_KEYS_DIR', {'new': self.keys}),
|
||||
(drainer, '_make_logger', {'return_value': self.log}),
|
||||
(drainer, '_load_push_cfg', {'side_effect': lambda: self.cfg}),
|
||||
(drainer, '_check_dispatched', {}),
|
||||
(drainer, '_master_settling', {'return_value': False}),
|
||||
):
|
||||
patcher = patch.object(target, name, **kwargs)
|
||||
patcher.start()
|
||||
self.addCleanup(patcher.stop)
|
||||
|
||||
def accept(self, node):
|
||||
self.write_json(self.keys, node, '')
|
||||
self.ck.accepted.add(node)
|
||||
|
||||
def source(self, actions, name='pillar_suricata.json', paths=None):
|
||||
now = time.time()
|
||||
return self.write_json(self.pending, name, {
|
||||
'first_touch': now - 65, 'last_touch': now - 60, 'actions': actions,
|
||||
'paths': paths or ['audit:suricata.config'],
|
||||
})
|
||||
|
||||
def kept_path(self, node):
|
||||
return os.path.join(self.pending, 'pending_{}.json'.format(node))
|
||||
|
||||
def kept(self, node):
|
||||
with open(self.kept_path(node)) as f:
|
||||
return json.load(f)
|
||||
|
||||
def age(self, node, seconds=60):
|
||||
intent = self.kept(node)
|
||||
intent['last_touch'] -= seconds
|
||||
self.write_json(self.pending, 'pending_{}.json'.format(node), intent)
|
||||
|
||||
def dispatched_actions(self):
|
||||
return [json.loads(c.args[0][3][len('pillar='):])['actions'] for c in self.run.call_args_list]
|
||||
|
||||
def test_keeps_pending_only(self):
|
||||
self.ck.targets['G@role:so-sensor'] = ['a']
|
||||
self.ck.pend('a')
|
||||
source = self.source([SURICATA])
|
||||
self.assertEqual(drainer.main(), 0)
|
||||
self.run.assert_not_called()
|
||||
intent = self.kept('a')
|
||||
self.assertEqual(intent['actions'], [
|
||||
{'state': 'suricata', 'tgt': 'L@a and ( G@role:so-sensor )', 'tgt_type': 'compound'}])
|
||||
self.assertEqual(intent['pending'], 'a')
|
||||
self.assertEqual(intent['paths'], ['audit:suricata.config'])
|
||||
self.assertFalse(os.path.exists(source))
|
||||
info = self.logged('info')
|
||||
self.assertIn('push kept for a until its first highstate completes: suricata tgt=G@role:so-sensor', info)
|
||||
self.assertNotIn('L@a', info)
|
||||
self.assertNotIn('skipping', info)
|
||||
self.assertNotIn('nothing to dispatch', info)
|
||||
|
||||
def test_keeps_pending_only_highstate(self):
|
||||
self.ck.targets['*'] = ['a']
|
||||
self.ck.pend('a')
|
||||
self.source([{'highstate': True, 'tgt': '*'}], name='pillar_global.json')
|
||||
self.assertEqual(drainer.main(), 0)
|
||||
self.run.assert_not_called()
|
||||
self.assertEqual(self.kept('a')['actions'], [{'highstate': True, 'tgt': 'L@a and ( * )', 'tgt_type': 'compound'}])
|
||||
info = self.logged('info')
|
||||
self.assertIn('push kept for a until its first highstate completes: highstate tgt=*', info)
|
||||
self.assertNotIn('L@a', info)
|
||||
self.assertNotIn('error', info.lower())
|
||||
|
||||
def test_keeps_and_dispatches(self):
|
||||
self.ck.pend('a')
|
||||
source = self.source([SURICATA])
|
||||
self.assertEqual(drainer.main(), 0)
|
||||
self.assertEqual(self.dispatched_actions(), [[{'state': 'suricata', 'tgt': '( G@role:so-sensor )' + NOT_PENDING}]])
|
||||
self.assertEqual(self.kept('a')['actions'], [_kept_copy('a', SURICATA)])
|
||||
self.assertFalse(os.path.exists(source))
|
||||
self.assertIn('push kept for a until its first highstate completes: suricata', self.logged('info'))
|
||||
|
||||
def test_keeps_several_pending(self):
|
||||
self.ck.pend('a', 'b')
|
||||
self.source([SURICATA])
|
||||
self.assertEqual(drainer.main(), 0)
|
||||
self.assertEqual(self.kept('a')['actions'], [_kept_copy('a', SURICATA)])
|
||||
self.assertEqual(self.kept('b')['actions'], [_kept_copy('b', SURICATA)])
|
||||
self.assertEqual(self.dispatched_actions(), [[{'state': 'suricata', 'tgt': '( G@role:so-sensor )' + NOT_PENDING}]])
|
||||
|
||||
self.run.reset_mock()
|
||||
self.ck.release('a')
|
||||
self.age('a')
|
||||
self.age('b')
|
||||
self.assertEqual(drainer.main(), 0)
|
||||
self.assertEqual(self.dispatched_actions(), [[
|
||||
{'state': 'suricata', 'tgt': '( L@a and ( G@role:so-sensor ) )' + NOT_PENDING, 'tgt_type': 'compound'}]])
|
||||
self.assertFalse(os.path.exists(self.kept_path('a')))
|
||||
self.assertTrue(os.path.exists(self.kept_path('b')))
|
||||
|
||||
def test_keep_merge(self):
|
||||
strelka = {'state': 'strelka', 'tgt': 'G@role:so-sensor'}
|
||||
paths = ['audit:p{}'.format(i) for i in range(30)]
|
||||
self.assertTrue(drainer._keep_for_pending({'a': [_kept_copy('a', SURICATA)]}, paths[:15], self.log))
|
||||
first_touch = self.kept('a')['first_touch']
|
||||
with patch.object(drainer.time, 'time', return_value=first_touch + 100):
|
||||
self.assertTrue(drainer._keep_for_pending(
|
||||
{'a': [_kept_copy('a', strelka), _kept_copy('a', SURICATA)]}, paths[10:], self.log))
|
||||
intent = self.kept('a')
|
||||
self.assertEqual(intent['actions'], [_kept_copy('a', SURICATA), _kept_copy('a', strelka)])
|
||||
self.assertEqual(intent['first_touch'], first_touch)
|
||||
self.assertEqual(intent['last_touch'], first_touch + 100)
|
||||
self.assertEqual(intent['paths'], paths[-drainer.MAX_PATHS:])
|
||||
self.assertEqual(intent['pending'], 'a')
|
||||
|
||||
def test_keep_corrupt_file(self):
|
||||
self.write_json(self.pending, 'pending_a.json', '{nope')
|
||||
self.assertTrue(drainer._keep_for_pending({'a': [_kept_copy('a', SURICATA)]}, [], self.log))
|
||||
self.assertIn('cannot read intent', self.logged('warning'))
|
||||
self.assertEqual(self.kept('a')['actions'], [_kept_copy('a', SURICATA)])
|
||||
|
||||
def test_keep_logs_other_tgt_unchanged(self):
|
||||
action = dict(SURICATA, tgt='L@b and ( G@role:so-sensor )')
|
||||
self.assertTrue(drainer._keep_for_pending({'a': [action]}, [], self.log))
|
||||
self.assertIn('push kept for a until its first highstate completes: suricata tgt=L@b and ( G@role:so-sensor )',
|
||||
self.logged('info'))
|
||||
self.assertEqual(self.kept('a')['actions'], [action])
|
||||
|
||||
def test_keep_logs_nested_parens_tgt(self):
|
||||
original = '( G@role:so-sensor or G@role:so-heavynode )'
|
||||
action = _kept_copy('a', dict(SURICATA, tgt=original))
|
||||
self.assertTrue(drainer._keep_for_pending({'a': [action]}, [], self.log))
|
||||
self.assertIn('suricata tgt={}\n'.format(original), self.logged('info') + '\n')
|
||||
self.assertEqual(self.kept('a')['actions'], [action])
|
||||
|
||||
def test_keep_logs_prefix_node_tgt_unchanged(self):
|
||||
action = dict(SURICATA, tgt='L@ab and ( G@role:so-sensor )')
|
||||
self.assertTrue(drainer._keep_for_pending({'a': [action]}, [], self.log))
|
||||
self.assertIn('suricata tgt=L@ab and ( G@role:so-sensor )', self.logged('info'))
|
||||
|
||||
def test_keep_logs_unterminated_tgt_unchanged(self):
|
||||
action = dict(SURICATA, tgt='L@a and ( G@role:so-sensor')
|
||||
self.assertTrue(drainer._keep_for_pending({'a': [action]}, [], self.log))
|
||||
self.assertIn('suricata tgt=L@a and ( G@role:so-sensor', self.logged('info'))
|
||||
|
||||
def test_keep_write_fails(self):
|
||||
self.ck.targets['G@role:so-sensor'] = ['a', 'c']
|
||||
self.ck.pend('a')
|
||||
source = self.source([SURICATA])
|
||||
real_open = open
|
||||
|
||||
def full_disk(path, *args, **kwargs):
|
||||
if str(path).endswith('pending_a.json.tmp'):
|
||||
raise OSError(errno.ENOSPC, 'No space left on device')
|
||||
return real_open(path, *args, **kwargs)
|
||||
|
||||
with patch('builtins.open', side_effect=full_disk):
|
||||
self.assertEqual(drainer.main(), 1)
|
||||
self.run.assert_not_called()
|
||||
self.assertTrue(os.path.exists(source))
|
||||
self.assertFalse(os.path.exists(self.kept_path('a')))
|
||||
self.assertIn('cannot keep pushes for a until its first highstate completes', self.logged('error'))
|
||||
self.assertIn('No space left on device', self.logged('error'))
|
||||
|
||||
self.assertEqual(drainer.main(), 0)
|
||||
self.run.assert_called_once()
|
||||
self.assertFalse(os.path.exists(source))
|
||||
self.assertEqual(self.kept('a')['actions'], [_kept_copy('a', SURICATA)])
|
||||
|
||||
def test_dispatch_fails_keep_once(self):
|
||||
self.ck.pend('a')
|
||||
source = self.source([SURICATA])
|
||||
self.run.side_effect = subprocess.CalledProcessError(1, 'salt-run', '', 'master down')
|
||||
self.assertEqual(drainer.main(), 1)
|
||||
self.assertTrue(os.path.exists(source))
|
||||
self.assertEqual(self.kept('a')['actions'], [_kept_copy('a', SURICATA)])
|
||||
|
||||
self.run.side_effect = None
|
||||
self.assertEqual(drainer.main(), 0)
|
||||
self.assertFalse(os.path.exists(source))
|
||||
self.assertEqual(self.kept('a')['actions'], [_kept_copy('a', SURICATA)])
|
||||
self.assertEqual(len(self.run.call_args_list), 2)
|
||||
|
||||
def test_keep_no_relock(self):
|
||||
lock_fd = os.open(drainer.LOCK_FILE, os.O_CREAT | os.O_RDWR, 0o644)
|
||||
self.addCleanup(os.close, lock_fd)
|
||||
fcntl.flock(lock_fd, fcntl.LOCK_EX)
|
||||
self.addCleanup(fcntl.flock, lock_fd, fcntl.LOCK_UN)
|
||||
result = []
|
||||
worker = threading.Thread(
|
||||
target=lambda: result.append(drainer._keep_for_pending({'a': [_kept_copy('a', SURICATA)]}, [], self.log)),
|
||||
daemon=True)
|
||||
worker.start()
|
||||
worker.join(timeout=5)
|
||||
self.assertFalse(worker.is_alive())
|
||||
self.assertEqual(result, [True])
|
||||
self.assertTrue(os.path.exists(self.kept_path('a')))
|
||||
|
||||
def test_kept_not_ready_while_pending(self):
|
||||
self.ck.pend('a')
|
||||
drainer._keep_for_pending({'a': [_kept_copy('a', SURICATA)]}, [], self.log)
|
||||
self.age('a')
|
||||
self.assertEqual(drainer.main(), 0)
|
||||
self.run.assert_not_called()
|
||||
self.assertTrue(os.path.exists(self.kept_path('a')))
|
||||
self.assertEqual([c.args for c in self.ck.cache.fetch.call_args_list], [('minions/a', 'data')])
|
||||
self.assertIn('no ready intents (0 still in debounce window, 1 for nodes still in their first highstate)',
|
||||
self.logged('debug'))
|
||||
|
||||
def test_kept_drains_after_release(self):
|
||||
drainer._keep_for_pending({'a': [_kept_copy('a', SURICATA)]}, ['audit:suricata.config'], self.log)
|
||||
self.age('a')
|
||||
self.ck.release('a')
|
||||
self.assertEqual(drainer.main(), 0)
|
||||
self.assertEqual(self.dispatched_actions(), [[
|
||||
{'state': 'suricata', 'tgt': '( L@a and ( G@role:so-sensor ) )' + NOT_PENDING, 'tgt_type': 'compound'}]])
|
||||
self.assertFalse(os.path.exists(self.kept_path('a')))
|
||||
self.assertEqual(len(os.listdir(self.dispatched)), 1)
|
||||
|
||||
def test_kept_waits_for_debounce(self):
|
||||
drainer._keep_for_pending({'a': [_kept_copy('a', SURICATA)]}, [], self.log)
|
||||
self.ck.release('a')
|
||||
self.assertEqual(drainer.main(), 0)
|
||||
self.run.assert_not_called()
|
||||
self.ck.cache.fetch.assert_not_called()
|
||||
self.assertTrue(os.path.exists(self.kept_path('a')))
|
||||
|
||||
def test_kept_master_config_error(self):
|
||||
drainer._keep_for_pending({'a': [_kept_copy('a', SURICATA)]}, [], self.log)
|
||||
self.age('a')
|
||||
self.ck.release('a')
|
||||
with patch.object(drainer.salt.config, 'master_config', side_effect=OSError('no config')):
|
||||
self.assertEqual(drainer.main(), 0)
|
||||
self.run.assert_not_called()
|
||||
self.assertTrue(os.path.exists(self.kept_path('a')))
|
||||
self.assertIn('holding kept pushes', self.logged('warning'))
|
||||
|
||||
def test_kept_removed_node(self):
|
||||
drainer._keep_for_pending({'a': [_kept_copy('a', SURICATA)]}, [], self.log)
|
||||
os.unlink(os.path.join(self.keys, 'a'))
|
||||
self.assertEqual(drainer.main(), 0)
|
||||
self.run.assert_not_called()
|
||||
self.assertFalse(os.path.exists(self.kept_path('a')))
|
||||
self.assertIn('removing kept pushes for a: its key is no longer accepted', self.logged('info'))
|
||||
|
||||
def test_kept_no_match_dropped(self):
|
||||
search = {'state': 'elasticsearch', 'tgt': 'G@role:so-searchnode'}
|
||||
drainer._keep_for_pending({'a': [_kept_copy('a', search)]}, [], self.log)
|
||||
self.age('a')
|
||||
self.ck.release('a')
|
||||
self.assertEqual(drainer.main(), 0)
|
||||
self.run.assert_not_called()
|
||||
self.assertFalse(os.path.exists(self.kept_path('a')))
|
||||
self.assertIn('skipping elasticsearch: no minions match tgt=L@a and ( G@role:so-searchnode )', self.logged('info'))
|
||||
|
||||
def test_kept_uncached_node_greedy(self):
|
||||
self.accept('m')
|
||||
manager = {'state': 'nginx', 'tgt': 'G@role:so-manager'}
|
||||
source = self.source([manager])
|
||||
self.assertEqual(drainer.main(), 0)
|
||||
self.run.assert_not_called()
|
||||
self.assertFalse(os.path.exists(source))
|
||||
self.assertEqual(self.kept('m')['actions'], [_kept_copy('m', manager)])
|
||||
|
||||
self.ck.release('m')
|
||||
self.age('m')
|
||||
self.log.reset_mock()
|
||||
self.assertEqual(drainer.main(), 0)
|
||||
self.run.assert_not_called()
|
||||
self.assertFalse(os.path.exists(self.kept_path('m')))
|
||||
self.assertEqual([c.args[0] % c.args[1:] for c in self.log.info.call_args_list if 'skipping' in c.args[0]],
|
||||
['skipping nginx: no minions match tgt=L@m and ( G@role:so-manager )'])
|
||||
|
||||
self.log.reset_mock()
|
||||
self.assertEqual(drainer.main(), 0)
|
||||
self.log.info.assert_not_called()
|
||||
|
||||
def test_kept_partial_match_consumed(self):
|
||||
search = {'state': 'elasticsearch', 'tgt': 'G@role:so-searchnode'}
|
||||
drainer._keep_for_pending({'a': [_kept_copy('a', SURICATA), _kept_copy('a', search)]}, [], self.log)
|
||||
self.age('a')
|
||||
self.ck.release('a')
|
||||
self.assertEqual(drainer.main(), 0)
|
||||
self.assertEqual(self.dispatched_actions(), [[
|
||||
{'state': 'suricata', 'tgt': '( L@a and ( G@role:so-sensor ) )' + NOT_PENDING, 'tgt_type': 'compound'}]])
|
||||
self.assertFalse(os.path.exists(self.kept_path('a')))
|
||||
|
||||
def test_kept_cache_error_held(self):
|
||||
search = {'state': 'elasticsearch', 'tgt': 'G@role:so-searchnode'}
|
||||
drainer._keep_for_pending({'a': [_kept_copy('a', search)]}, [], self.log)
|
||||
self.age('a')
|
||||
self.ck.release('a')
|
||||
self.ck.fetch_error = OSError('cache read failed')
|
||||
self.assertEqual(drainer.main(), 0)
|
||||
self.run.assert_not_called()
|
||||
self.assertTrue(os.path.exists(self.kept_path('a')))
|
||||
self.assertIn('cannot read the cached grains of a', self.logged('warning'))
|
||||
self.assertNotIn('skipping', self.logged('info'))
|
||||
|
||||
def test_no_unlink_written_this_pass(self):
|
||||
drainer._keep_for_pending({'a': [_kept_copy('a', SURICATA)]}, ['audit:suricata.config'], self.log)
|
||||
self.age('a')
|
||||
first_touch = self.kept('a')['first_touch']
|
||||
self.ck.release('a')
|
||||
self.ck.pending.add('a')
|
||||
self.assertEqual(drainer.main(), 0)
|
||||
self.run.assert_not_called()
|
||||
intent = self.kept('a')
|
||||
self.assertEqual(intent['actions'][0], _kept_copy('a', SURICATA))
|
||||
self.assertIn('push kept for a', self.logged('info'))
|
||||
self.assertEqual(intent['first_touch'], first_touch)
|
||||
self.assertGreater(intent['last_touch'], first_touch)
|
||||
self.assertEqual(intent['paths'], ['audit:suricata.config'])
|
||||
|
||||
def test_bad_id(self):
|
||||
self.ck.targets['*'] = ['bad\n', 'a/../b', 'c']
|
||||
self.ck.pending = {'bad\n', 'a/../b'}
|
||||
self.source([{'highstate': True, 'tgt': '*'}], name='pillar_global.json')
|
||||
for name, node in (('pending_x.json', '../etc'), ('pending_y.json', 5), ('pending_z.json', 'z\n')):
|
||||
self.write_json(self.pending, name, {'pending': node, 'last_touch': 0, 'actions': [SURICATA]})
|
||||
self.assertEqual(drainer.main(), 0)
|
||||
self.assertEqual(os.listdir(self.pending), ['.lock'])
|
||||
self.assertEqual(self.dispatched_actions(), [[{'highstate': True, 'tgt': '( * )' + NOT_PENDING}]])
|
||||
for call in self.run.call_args_list:
|
||||
self.assertNotIn('bad', call.args[0][3])
|
||||
self.assertNotIn('a/../b', call.args[0][3])
|
||||
warning = self.logged('warning')
|
||||
self.assertIn("not keeping highstate for 'bad\\n': not a valid node id", warning)
|
||||
self.assertIn("not keeping highstate for 'a/../b'", warning)
|
||||
self.assertIn("'../etc' is not a valid node id", warning)
|
||||
self.assertIn('5 is not a valid node id', warning)
|
||||
self.assertIn("'z\\n' is not a valid node id", warning)
|
||||
self.assertNotIn('push kept', self.logged('info'))
|
||||
|
||||
|
||||
class TestMain(DrainerTestCase):
|
||||
|
||||
@@ -1023,8 +474,7 @@ class TestMain(DrainerTestCase):
|
||||
('_make_logger', {'return_value': self.log}),
|
||||
('_load_push_cfg', {'side_effect': lambda: self.cfg}),
|
||||
('_check_dispatched', {}),
|
||||
('_targeted', {'side_effect': lambda actions, log: (actions, {})}),
|
||||
('_master_settling', {'return_value': False}),
|
||||
('_targeted', {'side_effect': lambda actions, log: actions}),
|
||||
):
|
||||
patcher = patch.object(drainer, name, **kwargs)
|
||||
setattr(self, name, patcher.start())
|
||||
@@ -1078,16 +528,6 @@ class TestMain(DrainerTestCase):
|
||||
with patch.object(drainer.os, 'unlink', side_effect=OSError('busy')):
|
||||
self.assertEqual(drainer.main(), 0)
|
||||
|
||||
def test_holds_while_master_settling(self):
|
||||
path = self.intent('pillar_soc.json')
|
||||
self._master_settling.return_value = True
|
||||
with patch.object(drainer, '_dispatch') as dispatch:
|
||||
self.assertEqual(drainer.main(), 0)
|
||||
dispatch.assert_not_called()
|
||||
self._check_dispatched.assert_called_once()
|
||||
self.assertTrue(os.path.exists(path))
|
||||
self.assertIn('holding 1 intent(s)', self.logged('info'))
|
||||
|
||||
def test_dispatch_failure_keeps_intents(self):
|
||||
path = self.intent('pillar_soc.json')
|
||||
with patch.object(drainer, '_dispatch', return_value=None):
|
||||
@@ -1120,7 +560,7 @@ class TestMain(DrainerTestCase):
|
||||
def test_untargeted_not_dispatched(self):
|
||||
path = self.intent('strelka.json', actions=[{'state': 'strelka', 'tgt': 'G@role:so-sensor'}])
|
||||
self._targeted.side_effect = None
|
||||
self._targeted.return_value = ([], {})
|
||||
self._targeted.return_value = []
|
||||
with patch.object(drainer, '_dispatch') as dispatch, \
|
||||
patch.object(drainer, '_record_dispatch') as record:
|
||||
self.assertEqual(drainer.main(), 0)
|
||||
@@ -1130,15 +570,15 @@ class TestMain(DrainerTestCase):
|
||||
self.assertIn('no action matches a minion; nothing to dispatch', self.logged('info'))
|
||||
|
||||
def test_dispatches_only_targeted(self):
|
||||
matched = {'state': 'soc', 'tgt': '*'}
|
||||
self.intent('mixed.json', actions=[matched, {'state': 'strelka', 'tgt': 'G@role:so-sensor'}])
|
||||
kept = {'state': 'soc', 'tgt': '*'}
|
||||
self.intent('mixed.json', actions=[kept, {'state': 'strelka', 'tgt': 'G@role:so-sensor'}])
|
||||
self._targeted.side_effect = None
|
||||
self._targeted.return_value = ([matched], {})
|
||||
self._targeted.return_value = [kept]
|
||||
with patch.object(drainer, '_dispatch', return_value=JID) as dispatch, \
|
||||
patch.object(drainer, '_record_dispatch') as record:
|
||||
self.assertEqual(drainer.main(), 0)
|
||||
self.assertEqual(dispatch.call_args[0][0], [matched])
|
||||
self.assertEqual(record.call_args[0][1], [matched])
|
||||
self.assertEqual(dispatch.call_args[0][0], [kept])
|
||||
self.assertEqual(record.call_args[0][1], [kept])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
@@ -39,8 +39,8 @@ SETTLE_STABLE_CHECKS=3
|
||||
SETTLE_INITIAL_WAIT=${GRID_HIGHSTATE_SETTLE_INITIAL_WAIT:-45}
|
||||
|
||||
BATCH=""
|
||||
BATCH_WAIT=""
|
||||
SALT_UPGRADED=false
|
||||
IGNORED_BATCH_WAIT=false
|
||||
REASON="manual"
|
||||
|
||||
log() {
|
||||
@@ -48,14 +48,14 @@ log() {
|
||||
}
|
||||
|
||||
usage() {
|
||||
echo "Usage: so-soup-grid-highstate [--batch <spec>] [--salt-upgraded] [--reason <text>]"
|
||||
echo "Usage: so-soup-grid-highstate [--batch <spec>] [--batch-wait <sec>] [--salt-upgraded] [--reason <text>]"
|
||||
exit 1
|
||||
}
|
||||
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
--batch) BATCH="$2"; shift 2 ;;
|
||||
--batch-wait) IGNORED_BATCH_WAIT=true; shift 2 ;;
|
||||
--batch-wait) BATCH_WAIT="$2"; shift 2 ;;
|
||||
--salt-upgraded) SALT_UPGRADED=true; shift ;;
|
||||
--reason) REASON="$2"; shift 2 ;;
|
||||
-h|--help) usage ;;
|
||||
@@ -64,7 +64,6 @@ while [ $# -gt 0 ]; do
|
||||
done
|
||||
|
||||
mkdir -p "$(dirname "$LOG_FILE")" "$(dirname "$LOCK_FILE")"
|
||||
[ "$IGNORED_BATCH_WAIT" = "true" ] && log "--batch-wait is no longer supported and is ignored"
|
||||
|
||||
# Serialize: a second invocation (e.g. two soups, or a manual run overlapping soup's)
|
||||
# should not dispatch a competing set of batches.
|
||||
@@ -80,6 +79,10 @@ if [ -z "$BATCH" ]; then
|
||||
BATCH=$(salt-call --out=newline_values_only pillar.get salt:auto_apply:batch 2>/dev/null)
|
||||
[ -z "$BATCH" ] && BATCH='10%'
|
||||
fi
|
||||
if [ -z "$BATCH_WAIT" ]; then
|
||||
BATCH_WAIT=$(salt-call --out=newline_values_only pillar.get salt:auto_apply:batch_wait 2>/dev/null)
|
||||
[ -z "$BATCH_WAIT" ] && BATCH_WAIT=15
|
||||
fi
|
||||
|
||||
MINIONID=$(salt-call --local --out=newline_values_only grains.get id 2>/dev/null)
|
||||
[ -z "$MINIONID" ] && MINIONID=$(cat /etc/salt/minion_id 2>/dev/null)
|
||||
@@ -97,7 +100,7 @@ if [ "$NUM_ACCEPTED" -le 1 ]; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
log "starting grid highstate: reason=$REASON minion=$MINIONID accepted=$NUM_ACCEPTED batch=$BATCH salt_upgraded=$SALT_UPGRADED"
|
||||
log "starting grid highstate: reason=$REASON minion=$MINIONID accepted=$NUM_ACCEPTED batch=$BATCH batch_wait=$BATCH_WAIT salt_upgraded=$SALT_UPGRADED"
|
||||
|
||||
# Count minions currently responsive on the bus (includes this manager).
|
||||
count_up() {
|
||||
@@ -168,7 +171,7 @@ if [ "$SALT_UPGRADED" = "true" ]; then
|
||||
PRE_UP=$(count_up); PRE_UP=${PRE_UP:-1}
|
||||
log "pre-upgrade reachable minions (incl. this manager): $PRE_UP"
|
||||
dispatch "salt-upgrade pass (all remote minions)" \
|
||||
"[{\"highstate\": true, \"tgt\": \"not $MINIONID\", \"tgt_type\": \"compound\", \"batch\": \"$BATCH\"}]" \
|
||||
"[{\"highstate\": true, \"tgt\": \"not $MINIONID\", \"tgt_type\": \"compound\", \"batch\": \"$BATCH\", \"batch_wait\": $BATCH_WAIT}]" \
|
||||
true
|
||||
log "waiting for minions to reconnect on the new salt version"
|
||||
wait_for_settle "$PRE_UP"
|
||||
@@ -199,7 +202,7 @@ for tgt in "${TIER_TGTS[@]}"; do
|
||||
n=$(tier_count "$tgt"); n=${n:-0}
|
||||
if [ "$n" -ge 1 ]; then
|
||||
[ -n "$actions" ] && actions="$actions, "
|
||||
actions="$actions{\"highstate\": true, \"tgt\": \"$tgt\", \"tgt_type\": \"compound\", \"batch\": \"$BATCH\"}"
|
||||
actions="$actions{\"highstate\": true, \"tgt\": \"$tgt\", \"tgt_type\": \"compound\", \"batch\": \"$BATCH\", \"batch_wait\": $BATCH_WAIT}"
|
||||
log "tier matched $n minion(s): $tgt"
|
||||
else
|
||||
log "tier matched 0 minions, skipping: $tgt"
|
||||
|
||||
@@ -1108,6 +1108,9 @@ post_to_3.3.0() {
|
||||
|
||||
### 3.4.0 Scripts ###
|
||||
up_to_3.4.0() {
|
||||
# download 9.4.8 elastic agent packages
|
||||
determine_elastic_agent_upgrade
|
||||
|
||||
set_soauth_range
|
||||
|
||||
echo "Removing so-kratos, so-hydra and so-soc so they are recreated on the soauth network."
|
||||
@@ -1185,6 +1188,10 @@ valid_soauth_range() {
|
||||
}
|
||||
|
||||
post_to_3.4.0() {
|
||||
# Generate 9.4.8 elastic agent installers
|
||||
echo "Regenerating Elastic Agent Installers"
|
||||
/sbin/so-elastic-agent-gen-installers
|
||||
|
||||
for idx in "metrics-logstash.node-default" "metrics-logstash.stack_monitoring.node-default"; do
|
||||
rollover_index "$idx"
|
||||
done
|
||||
@@ -1214,11 +1221,7 @@ add_detection_runtime_fields() {
|
||||
|
||||
### 3.5.0 Scripts ###
|
||||
up_to_3.5.0() {
|
||||
# download 9.4.10 elastic agent packages
|
||||
determine_elastic_agent_upgrade
|
||||
|
||||
remove_localrules_portgroup
|
||||
remove_auto_apply_batch_wait
|
||||
|
||||
INSTALLEDVERSION=3.5.0
|
||||
}
|
||||
@@ -1235,32 +1238,8 @@ remove_localrules_portgroup() {
|
||||
done
|
||||
}
|
||||
|
||||
remove_auto_apply_batch_wait() {
|
||||
local pillar_file
|
||||
|
||||
for pillar_file in /opt/so/saltstack/local/pillar/salt/{soc,adv}_salt.sls; do
|
||||
grep -qs batch_wait "$pillar_file" || continue
|
||||
so-yaml.py get -r "$pillar_file" salt.auto_apply.batch_wait >/dev/null 2>&1 || continue
|
||||
echo "Removing salt.auto_apply.batch_wait from $pillar_file."
|
||||
if ! so-yaml.py remove "$pillar_file" salt.auto_apply.batch_wait; then
|
||||
FINAL_MESSAGE_QUEUE+=("WARNING: Unable to remove the unused salt.auto_apply.batch_wait setting from $pillar_file. It has no effect and can be removed manually:")
|
||||
FINAL_MESSAGE_QUEUE+=(" - sudo so-yaml.py remove $pillar_file salt.auto_apply.batch_wait")
|
||||
fi
|
||||
done
|
||||
}
|
||||
|
||||
post_to_3.5.0() {
|
||||
# Generate 9.4.10 elastic agent installers
|
||||
echo "Regenerating Elastic Agent Installers"
|
||||
/sbin/so-elastic-agent-gen-installers
|
||||
|
||||
telegraf_repair
|
||||
# ensure manager has new version of socloud.conf
|
||||
if [[ $SALT_CLOUD_CONFIGURED == true ]]; then
|
||||
salt-call state.apply salt.cloud.config concurrent=True || FINAL_MESSAGE_QUEUE+=("WARNING: Unable to update the salt-cloud profile. Run: sudo salt-call state.apply salt.cloud.config")
|
||||
fi
|
||||
|
||||
rollover_index "logs-detections.alerts-so"
|
||||
|
||||
set_postversion 3.5.0
|
||||
}
|
||||
@@ -1538,11 +1517,10 @@ verify_es_version_compatibility() {
|
||||
["8.18.4"]="8.18.6 8.18.8 9.0.8"
|
||||
["8.18.6"]="8.18.8 9.0.8"
|
||||
["8.18.8"]="9.0.8"
|
||||
["9.0.8"]="9.3.3 9.3.7 9.4.5 9.4.8 9.4.10"
|
||||
["9.3.3"]="9.3.7 9.4.5 9.4.8 9.4.10"
|
||||
["9.3.7"]="9.4.5 9.4.8 9.4.10"
|
||||
["9.4.5"]="9.4.8 9.4.10"
|
||||
["9.4.8"]="9.4.10"
|
||||
["9.0.8"]="9.3.3 9.3.7 9.4.5 9.4.8"
|
||||
["9.3.3"]="9.3.7 9.4.5 9.4.8"
|
||||
["9.3.7"]="9.4.5 9.4.8"
|
||||
["9.4.5"]="9.4.8"
|
||||
)
|
||||
|
||||
# Elasticsearch MUST upgrade through these versions
|
||||
@@ -2436,7 +2414,7 @@ while getopts ":b:f:y" opt; do
|
||||
b )
|
||||
BATCHSIZE="$OPTARG"
|
||||
# Accept either a plain count (e.g. 5) or a percentage (e.g. 25%); passed through
|
||||
# to so-soup-grid-highstate --batch, which salt's batch accepts in both forms.
|
||||
# to so-soup-grid-highstate --batch, which salt's batch/batch_wait accepts in both forms.
|
||||
if ! [[ "$BATCHSIZE" =~ ^[1-9][0-9]*%?$ ]]; then
|
||||
echo "Batch size must be a number greater than 0, optionally with a trailing % (e.g. 5 or 25%)."
|
||||
exit 1
|
||||
|
||||
@@ -1,50 +1,26 @@
|
||||
{% from 'salt/auto_apply.map.jinja' import AUTOAPPLY %}
|
||||
{% set actions = salt['pillar.get']('actions', []) %}
|
||||
{% set BATCH = AUTOAPPLY.batch %}
|
||||
{# Must exceed gather_job_timeout (10s): at the 5s default, one saltutil.find_job reply slower than that abandons
|
||||
a queued state run, and a master slow to accept the publish gets it a second time. #}
|
||||
{% set STATE_TIMEOUT = 60 %}
|
||||
{% set BATCH_WAIT = AUTOAPPLY.batch_wait %}
|
||||
|
||||
{# queue must be a top-level salt.state arg (kwarg is ignored); an int is max_queue and still fails on conflict #}
|
||||
{# The first step of each action checks that its target is reachable: minions take up to ~22s to rejoin a
|
||||
restarted master's publisher, and each failed attempt takes ~15s to time out. salt.function does not count
|
||||
non-responders as failures, so the check passes as soon as any one minion answers. The drainer's 45s hold
|
||||
covers a restart before dispatch; the retry covers a restart during a running orchestration. expect_minions
|
||||
is not set on purpose: one offline node would then block the push to every node.
|
||||
A highstate checks with test.ping: it renders pillar itself, and the global and salt pillar actions push a
|
||||
highstate to '*', where an unbatched refresh_pillar would make every minion render pillar at once. A single
|
||||
state needs fresh pillar, so it checks with refresh_pillar. #}
|
||||
|
||||
{% for action in actions %}
|
||||
{% if action.get('highstate') %}
|
||||
ping_{{ loop.index }}:
|
||||
salt.function:
|
||||
- name: test.ping
|
||||
- tgt: '{{ action.tgt }}'
|
||||
- tgt_type: {{ action.get('tgt_type', 'compound') }}
|
||||
- retry:
|
||||
attempts: 3
|
||||
interval: 10
|
||||
|
||||
apply_highstate_{{ loop.index }}:
|
||||
salt.state:
|
||||
- tgt: '{{ action.tgt }}'
|
||||
- tgt_type: {{ action.get('tgt_type', 'compound') }}
|
||||
- highstate: True
|
||||
- batch: {{ action.get('batch', BATCH) }}
|
||||
- batch_wait: {{ action.get('batch_wait', BATCH_WAIT) }}
|
||||
- queue: True
|
||||
- timeout: {{ STATE_TIMEOUT }}
|
||||
- require:
|
||||
- salt: ping_{{ loop.index }}
|
||||
{% else %}
|
||||
refresh_pillar_{{ loop.index }}:
|
||||
salt.function:
|
||||
- name: saltutil.refresh_pillar
|
||||
- tgt: '{{ action.tgt }}'
|
||||
- tgt_type: {{ action.get('tgt_type', 'compound') }}
|
||||
- retry:
|
||||
attempts: 3
|
||||
interval: 10
|
||||
|
||||
apply_{{ action.state | replace('.', '_') }}_{{ loop.index }}:
|
||||
salt.state:
|
||||
@@ -53,8 +29,8 @@ apply_{{ action.state | replace('.', '_') }}_{{ loop.index }}:
|
||||
- sls:
|
||||
- {{ action.state }}
|
||||
- batch: {{ action.get('batch', BATCH) }}
|
||||
- batch_wait: {{ action.get('batch_wait', BATCH_WAIT) }}
|
||||
- queue: True
|
||||
- timeout: {{ STATE_TIMEOUT }}
|
||||
- require:
|
||||
- salt: refresh_pillar_{{ loop.index }}
|
||||
{% endif %}
|
||||
|
||||
@@ -3,8 +3,7 @@
|
||||
#
|
||||
# One pillar directory can map to multiple (state, tgt) actions.
|
||||
# tgt is a raw salt compound expression. tgt_type is always "compound".
|
||||
# so-push-drainer keeps pushes for nodes still in their first highstate and applies them after it completes.
|
||||
# Per-action `batch` overrides the orch default (10%).
|
||||
# Per-action `batch` / `batch_wait` override the orch defaults (10% / 15s).
|
||||
# An action with `highstate: True` triggers state.highstate instead of
|
||||
# state.apply -- see salt/orch/push_batch.sls.
|
||||
#
|
||||
@@ -99,7 +98,7 @@ elasticfleet:
|
||||
# global: fanout to a fleetwide highstate. The global pillar (soc_global.sls)
|
||||
# carries cross-cutting settings (pipeline, url_base, imagerepo, mdengine, ...)
|
||||
# that are consumed by virtually every state, so a targeted re-apply isn't
|
||||
# meaningful. The drainer's batch throttling controls blast radius.
|
||||
# meaningful. The drainer's batch/batch_wait throttling controls blast radius.
|
||||
global:
|
||||
- highstate: True
|
||||
tgt: '*'
|
||||
|
||||
@@ -117,7 +117,7 @@ def _app_from_setting(setting_id):
|
||||
|
||||
def _node_actions(entry, node_id):
|
||||
# Copy the app's mapped actions but narrow each one to the single node.
|
||||
# Preserves the state/highstate selection and any batch override.
|
||||
# Preserves the state/highstate selection and any batch/batch_wait overrides.
|
||||
# The app's own target is kept so the state is not applied to a node that does not
|
||||
# run the app (e.g. an elasticsearch setting saved for a sensor fails to render there).
|
||||
actions = []
|
||||
|
||||
@@ -18,7 +18,7 @@ include:
|
||||
# Install the registry container
|
||||
so-dockerregistry:
|
||||
docker_container.running:
|
||||
- image: ghcr.io/security-onion-solutions/registry:3.1.2
|
||||
- image: ghcr.io/security-onion-solutions/registry:3.1.1
|
||||
# Intentionally `always`-- registry is critical and must
|
||||
# come back up even if it was manually stopped.
|
||||
- restart_policy: always
|
||||
|
||||
@@ -28,8 +28,6 @@ sool9_{{host}}:
|
||||
grains:
|
||||
hypervisor_host: {{host ~ "_" ~ role}}
|
||||
sosmodel: HVGUEST
|
||||
# so-push-drainer leaves the VM alone until its first highstate removes this
|
||||
first_highstate_pending: True
|
||||
preflight_cmds:
|
||||
- |
|
||||
{%- set hostnames = [MANAGERHOSTNAME] %}
|
||||
|
||||
@@ -4,5 +4,6 @@ salt:
|
||||
debounce_seconds: 30
|
||||
drain_interval: 15
|
||||
batch: '10%'
|
||||
batch_wait: 15
|
||||
schedule:
|
||||
highstate_interval_minutes: 120
|
||||
@@ -2,12 +2,3 @@ lasthighstate:
|
||||
file.touch:
|
||||
- name: /opt/so/log/salt/lasthighstate
|
||||
- order: 9001
|
||||
|
||||
# Set by setup and the hypervisor VM cloud profile; so-push-drainer does not target a node that still has it.
|
||||
# Auto-ordered states start at 10000, and a negative order runs after all of them, just before the
|
||||
# order: last states, so the grain goes only once the highstate has run every state. The touch above stays
|
||||
# at 9001 because so-status and so-salt-minion-check read it.
|
||||
first_highstate_pending:
|
||||
grains.absent:
|
||||
- destructive: True
|
||||
- order: -1
|
||||
+11
-5
@@ -3,32 +3,38 @@ salt:
|
||||
enabled:
|
||||
description: Master kill-switch for the active push feature. When disabled, rule and pillar changes are picked up at the next scheduled highstate instead of being pushed immediately.
|
||||
forcedType: bool
|
||||
helpLink: salt
|
||||
helpLink: push
|
||||
global: True
|
||||
debounce_seconds:
|
||||
description: Trailing-edge debounce window in seconds. A push intent must be quiet for this long before the drainer dispatches. Rapid bursts of edits within this window coalesce into one dispatch.
|
||||
forcedType: int
|
||||
helpLink: salt
|
||||
helpLink: push
|
||||
global: True
|
||||
advanced: True
|
||||
drain_interval:
|
||||
description: How often the push drainer checks for ready intents, in seconds. Small values lower dispatch latency at the cost of more background work on the manager.
|
||||
forcedType: int
|
||||
helpLink: salt
|
||||
helpLink: push
|
||||
global: True
|
||||
advanced: True
|
||||
batch:
|
||||
description: "Host batch size for push orchestrations. A number (e.g. '10') or a percentage (e.g. '25%'). Limits how many minions run the push state at once so large fleets don't thundering-herd."
|
||||
helpLink: salt
|
||||
helpLink: push
|
||||
global: True
|
||||
advanced: True
|
||||
regex: '^([0-9]+%?)$'
|
||||
regexFailureMessage: Enter a whole number or a whole-number percentage (e.g. 10 or 25%).
|
||||
batch_wait:
|
||||
description: Seconds to wait between host batches in a push orchestration. Gives the fleet time to breathe between waves.
|
||||
forcedType: int
|
||||
helpLink: push
|
||||
global: True
|
||||
advanced: True
|
||||
schedule:
|
||||
highstate_interval_minutes:
|
||||
description: How often every minion in the grid runs a scheduled state.highstate, in minutes. Minimum 15 minutes. Lower values keep minions closer in sync at the cost of more load; higher values reduce load but increase worst-case latency for non-pushed changes. If Auto Apply is disabled, set this to the 15-minute minimum so changes are still picked up promptly. The salt-minion health check restarts a minion if its last state apply is older than this value plus one hour.
|
||||
forcedType: int
|
||||
helpLink: salt
|
||||
helpLink: push
|
||||
global: True
|
||||
advanced: True
|
||||
regex: '^(1[5-9]|[2-9][0-9]|[1-9][0-9]{2,4})$'
|
||||
|
||||
@@ -1638,12 +1638,6 @@ soc:
|
||||
- "user.effective.name"
|
||||
- "weird.name"
|
||||
- "tags"
|
||||
queryNotifications:
|
||||
defaultLimit: 10
|
||||
maxLimit: 50
|
||||
summaryMaxLength: 1000
|
||||
fieldValueMaxLength: 200
|
||||
maxEntries: 25
|
||||
onionconfig:
|
||||
saltstackDir: /opt/so/saltstack
|
||||
bypassEnabled: false
|
||||
@@ -2557,61 +2551,6 @@ soc:
|
||||
grid:
|
||||
maxUploadSize: 26214400
|
||||
staleMetricsMs: 120000
|
||||
recommendedAlarms:
|
||||
- name: Root Disk Usage
|
||||
metric: disk
|
||||
metricKey: disk_used_root
|
||||
operator: gt
|
||||
threshold: '95'
|
||||
durationSeconds: 300
|
||||
severity: critical
|
||||
clearedSeverity: info
|
||||
enabled: true
|
||||
- name: NSM Disk Usage
|
||||
metric: disk
|
||||
metricKey: disk_used_nsm
|
||||
operator: gt
|
||||
threshold: '95'
|
||||
durationSeconds: 300
|
||||
severity: critical
|
||||
clearedSeverity: info
|
||||
enabled: true
|
||||
- name: Low PCAP Retention
|
||||
metric: pcap_retention
|
||||
metricKey: pcap_retention
|
||||
operator: lt
|
||||
threshold: '1'
|
||||
durationSeconds: 300
|
||||
severity: critical
|
||||
clearedSeverity: info
|
||||
enabled: true
|
||||
- name: Suricata Packet Loss
|
||||
metric: loss
|
||||
metricKey: suricata_loss
|
||||
operator: gt
|
||||
threshold: '5'
|
||||
durationSeconds: 300
|
||||
severity: critical
|
||||
clearedSeverity: info
|
||||
enabled: true
|
||||
- name: Zeek Packet Loss
|
||||
metric: loss
|
||||
metricKey: zeek_loss
|
||||
operator: gt
|
||||
threshold: '5'
|
||||
durationSeconds: 300
|
||||
severity: critical
|
||||
clearedSeverity: info
|
||||
enabled: true
|
||||
- name: Low Monitor Traffic
|
||||
metric: net
|
||||
metricKey: traffic_mon_in
|
||||
operator: lt
|
||||
threshold: '5'
|
||||
durationSeconds: 300
|
||||
severity: critical
|
||||
clearedSeverity: info
|
||||
enabled: true
|
||||
cases:
|
||||
advanced: false
|
||||
aggregationActionsEnabled: false
|
||||
|
||||
@@ -1112,32 +1112,6 @@ soc:
|
||||
description: A whitelist of fields to return when OnionAI uses the query_events tool. All other fields are removed. One field per line.
|
||||
global: True
|
||||
multiline: True
|
||||
queryNotifications:
|
||||
defaultLimit:
|
||||
description: Number of notifications Onion AI reads with the query_notifications tool when it doesn't ask for a specific number. Must be greater than 0. Values above maxLimit use maxLimit.
|
||||
global: True
|
||||
advanced: True
|
||||
forcedType: int
|
||||
maxLimit:
|
||||
description: Maximum number of notifications Onion AI may read with one query_notifications call. Must be greater than 0. Higher values put more notification text into the model's context.
|
||||
global: True
|
||||
advanced: True
|
||||
forcedType: int
|
||||
summaryMaxLength:
|
||||
description: Maximum number of characters of each notification summary that query_notifications returns to Onion AI. Must be greater than 0. Longer summaries are shortened.
|
||||
global: True
|
||||
advanced: True
|
||||
forcedType: int
|
||||
fieldValueMaxLength:
|
||||
description: Maximum number of characters of each notification field value that query_notifications returns to Onion AI. Must be greater than 0. Longer values are shortened. Link values are never shortened.
|
||||
global: True
|
||||
advanced: True
|
||||
forcedType: int
|
||||
maxEntries:
|
||||
description: Maximum number of fields, of links, and of attachment names, each counted separately, per notification that query_notifications returns to Onion AI. Must be greater than 0. The result tells Onion AI how many were left out.
|
||||
global: True
|
||||
advanced: True
|
||||
forcedType: int
|
||||
client:
|
||||
assistant:
|
||||
enabled:
|
||||
@@ -1343,69 +1317,6 @@ soc:
|
||||
staleMetricsMs:
|
||||
description: The age in milliseconds of node metrics when they are considered stale. Stale metrics have a faded appearance on the Grid screen.
|
||||
global: True
|
||||
recommendedAlarms:
|
||||
description: Recommended alarms offered on the Grid page's Alarms tab and Options dialog.
|
||||
global: True
|
||||
advanced: True
|
||||
forcedType: "[]{}"
|
||||
syntax: json
|
||||
helpLink: grid
|
||||
uiElements:
|
||||
- field: name
|
||||
label: Name
|
||||
required: True
|
||||
- field: metric
|
||||
label: Metric
|
||||
required: True
|
||||
- field: metricKey
|
||||
label: Metric Key
|
||||
required: False
|
||||
- field: operator
|
||||
label: Operator
|
||||
required: True
|
||||
options:
|
||||
- gt
|
||||
- gte
|
||||
- lt
|
||||
- lte
|
||||
- eq
|
||||
- ne
|
||||
- contains
|
||||
- field: threshold
|
||||
label: Threshold
|
||||
required: True
|
||||
forcedType: string
|
||||
- field: durationSeconds
|
||||
label: Duration Seconds
|
||||
required: False
|
||||
forcedType: int
|
||||
- field: severity
|
||||
label: Severity
|
||||
required: True
|
||||
options:
|
||||
- critical
|
||||
- high
|
||||
- medium
|
||||
- low
|
||||
- info
|
||||
- field: clearedSeverity
|
||||
label: Cleared Severity
|
||||
required: False
|
||||
options:
|
||||
- none
|
||||
- critical
|
||||
- high
|
||||
- medium
|
||||
- low
|
||||
- info
|
||||
- field: enabled
|
||||
label: Enabled
|
||||
required: False
|
||||
forcedType: bool
|
||||
- field: note
|
||||
label: Note
|
||||
required: False
|
||||
multiline: True
|
||||
case:
|
||||
analyzerNodeId:
|
||||
description: The node ID on which analyzers will be executed.
|
||||
|
||||
@@ -24,8 +24,6 @@ so-telegraf:
|
||||
- environment:
|
||||
- HOST_ETC=/host/etc
|
||||
- HOST_SYS=/host/sys
|
||||
- HOST_PROC=/host/proc
|
||||
- HOST_PROC_MOUNTINFO=/proc/1
|
||||
- HOST_MOUNT_PREFIX=/host
|
||||
- GODEBUG=x509ignoreCN=0
|
||||
{% if DOCKERMERGED.containers['so-telegraf'].extra_env %}
|
||||
|
||||
@@ -519,8 +519,6 @@ configure_minion() {
|
||||
info "Configuring minion type as $minion_type"
|
||||
logCmd "mkdir -p /etc/salt/minion.d"
|
||||
echo "role: so-$minion_type" > /etc/salt/grains
|
||||
# so-push-drainer leaves the node alone until salt.lasthighstate removes this
|
||||
echo "first_highstate_pending: True" >> /etc/salt/grains
|
||||
|
||||
local minion_config=/etc/salt/minion
|
||||
|
||||
|
||||
Reference in new issue
Block a user