-
Notifications
You must be signed in to change notification settings - Fork 61
/
import.py
executable file
·153 lines (131 loc) · 4.17 KB
/
import.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
#!/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import argparse
import json
import logging
import os
import random
import string
import subprocess
import tempfile
import time
from collections import namedtuple
from enum import Enum
from pathlib import Path
DOCKER_BIN = os.environ.get("DOCKER", "docker")
METRICS = [
"cgroup",
"disk",
"iface",
"network",
"process",
"system",
"transport",
]
def get_below_bin(snapshot):
"""Get the below "binary" to run"""
env = os.environ.get("BELOW")
if env:
return env.split()
else:
# Always use the latest docker image
subprocess.run(["docker", "pull", "below/below:latest"], check=True)
volume_args = []
if snapshot:
volume_args += ["-v", f"{snapshot}:{snapshot}"]
else:
# Else we are importing from localhost
store_dir = "/var/log/below/"
volume_args += ["-v", f"{store_dir}:{store_dir}"]
return [
"docker",
"run",
"--rm",
*volume_args,
"below/below:latest",
]
def dump(source, category, begin, end, outfile):
"""Gets below to dump openmetrics data to given outfile"""
if source.lower() == "host":
below_source = None
below_source_args = []
else:
below_source = str(Path(source).absolute())
below_source_args = ["--snapshot", below_source]
cmd = [
*get_below_bin(below_source),
"dump",
*below_source_args,
category,
"--begin",
begin,
"--end",
end,
"--everything",
"--output-format",
"openmetrics",
]
cmd_str = " ".join(cmd)
logging.info(f"Dumping {category} data with cmd='{cmd_str}'")
process = subprocess.run(
cmd, stdout=outfile, stderr=subprocess.PIPE, encoding="utf-8"
)
if process.returncode != 0:
logging.error(f"process stderr={process.stderr}")
raise RuntimeError(f"Failed to dump {category} data: {process.stderr}")
def ingest(metrics_file):
"""Ingest metrics into prometheus"""
subprocess.run(
[DOCKER_BIN, "compose", "cp", metrics_file, "prometheus:/import.txt"],
check=True,
)
subprocess.run(
[
DOCKER_BIN,
"compose",
"exec",
"prometheus",
"promtool",
"tsdb",
"create-blocks-from",
"openmetrics",
"/import.txt",
"/prometheus",
],
check=True,
)
def restart_prometheus():
subprocess.run([DOCKER_BIN, "compose", "restart", "prometheus"], check=True)
def do_import(begin, end, source):
logging.info(f"Importing {source} from '{begin}' to '{end}'")
for category in METRICS:
with tempfile.NamedTemporaryFile(mode="w") as f:
data = dump(source, category, begin, end, f)
# Need to chmod b/c there's a uid/gid mismatch when copying into container
os.chmod(f.name, 0o644)
ingest(f.name)
restart_prometheus()
def main():
parser = argparse.ArgumentParser(description="Imports below data into prometheus")
parser.add_argument("--begin", "-b", default="99 years ago", help="Import start")
parser.add_argument("--end", "-e", default="now", help="Import end")
parser.add_argument("source", help="Path to snapshot or `host`, for local host")
args = parser.parse_args()
start = time.time()
do_import(args.begin, args.end, args.source)
logging.info(f"Done in {time.time() - start}s")
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
main()