k8s.io/kubernetes@v1.31.0-alpha.0.0.20240520171757-56147500dadc/hack/serve-prom-scrapes.sh (about)

     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  
    30  if (( $# != 2 )); then
    31      echo "Usage: $0 port_num scrapes_dir" >&2
    32      exit 1
    33  fi
    34  
    35  port_num="$1"
    36  scrapes_dir="$2"
    37  response_file="/tmp/$(cd /tmp && mktemp  response.XXXXXX)"
    38  
    39  cleanup_serve() {
    40      rm -rf "$response_file"
    41  }
    42  
    43  trap cleanup_serve EXIT
    44  
    45  chmod +r "$response_file"
    46  
    47  transform() {
    48      path="$1"
    49      base="$(basename "$path")"
    50      seconds="${base%.scrape}"
    51      sed 's/^\([^#].*\)$/\1 '"${seconds}000/" "$path"
    52  }
    53  
    54  find_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  
    59  find_and_transform
    60  
    61  if man nc | grep -wq -e -N
    62  then dashen=-N
    63  else dashen=
    64  fi
    65  
    66  # shellcheck disable=SC2086
    67  while true; do nc -l $dashen 0.0.0.0 "$port_num" < "$response_file" > /dev/null; sleep 10; done