aboutsummaryrefslogtreecommitdiff
path: root/tools/influxdb-monitoring.sh
blob: 612900f2161d2cd754579ba0b2e25dbe8d7d751a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#!/usr/bin/env bash
# Generate access tokens for InfluxDB to submit monitoring and other
# telemetries.
set -eu

if ! command -v influx >/dev/null || ! command -v jq >/dev/null || ! command -v pass >/dev/null; then
	exec nix shell 'nixpkgs#influxdb2' 'nixpkgs#jq' 'nixpkgs#pass' -c "$0" "$@"
fi

cd "${0%/*}/.."

influx_args=(
	# Warning: you might want to modify this when you move the InfluxDB host
	"--host" "http://errol:8086"
	"--token" "$(pass 'nixos-secrets/influxdb/token/cynerd')"
)


monitoring_enabled() {
	local hostname="$1"
	[ "$(nix eval ".#nixosConfigurations.$hostname.config.cynerd.monitoring.enable")" = "true" ]
}

token_is_valid() {
	[ "$(influx auth list "${influx_args[@]}" --json | jq "map(.token) | any(. == \"$1\")")" = "true" ]
}

ensure_token() {
	local hostname="$1"
	local token
	pass_path="nixos-secrets/influxdb/token/$hostname"
	if ! token="$(pass "$pass_path" 2>/dev/null)" \
		|| ! token_is_valid "$token"; then
			influx auth create "${influx_args[@]}" -o "personal" -d "monitoring-$hostname" --write-buckets --json \
				| jq -r '.token' \
				| sed 's/^\(.*\)$/\1\n\1/' \
				| pass insert -f "$pass_path"
	fi
}

nix eval --json --apply 'builtins.attrNames' .#nixosConfigurations \
	| jq -r '.[]' \
	| while read -r hostname; do
		if monitoring_enabled "$hostname"; then
			ensure_token "$hostname"
		fi
	done;