...
1#!/usr/bin/env bash
2
3# Copyright 2021 The Kubernetes Authors.
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17# Serves a collection of scrape files up to Prometheus scraping.
18
19# Usage: $0 port_num scrapes-dir
20#
21# Where scrapes-dir has descendant files whose name is of the form
22# <timestamp>.scrape
23# where <timestamp> is seconds since Jan 1, 1970 UTC.
24# Each such file is taken to be a scrape that lacks timestamps,
25# and the timestamp from the filename is multiplied by the necessary 1000
26# and added to the data in that file.
27
28# This requires an `nc` command that this script knows how to wrangle.
29
30if (( $# != 2 )); then
31 echo "Usage: $0 port_num scrapes_dir" >&2
32 exit 1
33fi
34
35port_num="$1"
36scrapes_dir="$2"
37response_file="/tmp/$(cd /tmp && mktemp response.XXXXXX)"
38
39cleanup_serve() {
40 rm -rf "$response_file"
41}
42
43trap cleanup_serve EXIT
44
45chmod +r "$response_file"
46
47transform() {
48 path="$1"
49 base="$(basename "$path")"
50 seconds="${base%.scrape}"
51 sed 's/^\([^#].*\)$/\1 '"${seconds}000/" "$path"
52}
53
54find_and_transform() {
55 echo -n $'HTTP/1.0 200 OK\r\nContent-Type: text/plain\r\n\r\n' > "$response_file"
56 find "$scrapes_dir" -name "*.scrape" -print0 | sort -z | while read -d '' -r scrapename; do transform "$scrapename" >> "$response_file"; done
57}
58
59find_and_transform
60
61if man nc | grep -wq -e -N
62then dashen=-N
63else dashen=
64fi
65
66# shellcheck disable=SC2086
67while true; do nc -l $dashen 0.0.0.0 "$port_num" < "$response_file" > /dev/null; sleep 10; done
View as plain text