| 1 |
#!/usr/bin/env python |
| 2 |
# @package update_storage_schemas.py |
| 3 |
# Correct/Update storage schemas\n |
| 4 |
# @code |
| 5 |
# # Usage example for update_storage_schemas.py |
| 6 |
# sudo ./update_storage_schemas.py --path /opt/graphite/whisper --cfg /opt/graphite/conf/schemas |
| 7 |
# @endcode |
| 8 |
|
| 9 |
import sys |
| 10 |
import os |
| 11 |
import logging |
| 12 |
import subprocess |
| 13 |
import argparse |
| 14 |
import re |
| 15 |
import time |
| 16 |
from multiprocessing import Pool, cpu_count |
| 17 |
from configobj import ConfigObj |
| 18 |
# Assuming Python 2, we'll want scandir if possible, it's much faster |
| 19 |
try: |
| 20 |
from scandir import scandir |
| 21 |
except ImportError: |
| 22 |
from os import listdir as scandir |
| 23 |
|
| 24 |
LOG = logging.getLogger() |
| 25 |
LOG.setLevel(logging.INFO) |
| 26 |
SCHEMA_LIST = {} |
| 27 |
# The very basic default retentions |
| 28 |
DEFAULT_SCHEMA = {'match': re.compile('.*'), |
| 29 |
'retentions': '1m:7d'} |
| 30 |
DEBUG = False |
| 31 |
DRY_RUN = False |
| 32 |
ROOT_PATH = "" |
| 33 |
|
| 34 |
|
| 35 |
def config_schemas(cfg): |
| 36 |
schema_conf = ConfigObj(cfg) |
| 37 |
|
| 38 |
for schema in schema_conf.items(): |
| 39 |
item = schema[1]['pattern'] |
| 40 |
if item == '.*': |
| 41 |
DEFAULT_SCHEMA['retentions'] = schema[1]['retentions'] |
| 42 |
else: |
| 43 |
if item[0] == '^': |
| 44 |
item = item[1:] |
| 45 |
SCHEMA_LIST[item] = {'retentions': schema[1]['retentions'], |
| 46 |
'match': re.compile(item)} |
| 47 |
|
| 48 |
|
| 49 |
def _convert_seconds(time): |
| 50 |
seconds_dict = {'s': 1, 'm': 60, 'h': 3600, 'min': 60, |
| 51 |
'd': 86400, 'w': 604800, 'y': 31536000} |
| 52 |
(points, time) = time.split(':') |
| 53 |
if str.isalpha(time[-1]): |
| 54 |
time = int(time[:-1]) * seconds_dict[time[-1]] |
| 55 |
return time |
| 56 |
|
| 57 |
|
| 58 |
def _compare_retention(retention, tmp_path): |
| 59 |
# Get the new retention as [(secondsPerPoint, numPoints), ...] |
| 60 |
new_retention = [_convert_seconds(item) for item in list(retention)] |
| 61 |
info_string = [INFO_BIN, tmp_path] |
| 62 |
cur_ret_list = subprocess.Popen(info_string, stdout=subprocess.PIPE) |
| 63 |
cur_ret_list = cur_ret_list.communicate()[0].split('\n') |
| 64 |
cur_retention = [int(line.split(':')[1]) for line in cur_ret_list |
| 65 |
if 'retention' in line] |
| 66 |
return cur_retention == new_retention |
| 67 |
|
| 68 |
|
| 69 |
def _find_metrics(path): |
| 70 |
for f in scandir(path): |
| 71 |
if f.is_dir(follow_symlinks=False): |
| 72 |
for sf in _find_metrics(f.path): |
| 73 |
yield sf |
| 74 |
else: |
| 75 |
if not f.is_file(follow_symlinks=False) or \ |
| 76 |
not f.name.endswith('.wsp'): |
| 77 |
continue |
| 78 |
yield f.path |
| 79 |
|
| 80 |
|
| 81 |
def fix_metric(metric): |
| 82 |
if not SCHEMA_LIST: |
| 83 |
LOG.error("Didn't initialize schemas!") |
| 84 |
return [] |
| 85 |
|
| 86 |
if DEBUG: |
| 87 |
LOG.info("Testing %s for modification" % metric) |
| 88 |
devnull = open(os.devnull, 'w') |
| 89 |
command_string = list(BASE_COMMAND) + [metric] |
| 90 |
|
| 91 |
retention = DEFAULT_SCHEMA['retentions'] |
| 92 |
matching = metric[len(ROOT_PATH):].replace('/', '.') |
| 93 |
for schema, info in SCHEMA_LIST.iteritems(): |
| 94 |
if info['match'].search(matching): |
| 95 |
retention = info['retentions'] |
| 96 |
break |
| 97 |
command_string.extend(list(retention)) |
| 98 |
if DEBUG: |
| 99 |
LOG.info("Created command: %s" % command_string) |
| 100 |
|
| 101 |
if _compare_retention(retention, metric): |
| 102 |
LOG.debug('%s has the same retention as before!' % metric) |
| 103 |
return [(False, metric)] |
| 104 |
|
| 105 |
if DRY_RUN: |
| 106 |
res = 0 |
| 107 |
else: |
| 108 |
LOG.debug('Retention will be %s' % retention) |
| 109 |
# record file owner/group and perms to set properly after whisper-resize.py is complete |
| 110 |
st = os.stat(metric) |
| 111 |
if DEBUG: |
| 112 |
res = subprocess.check_call(command_string) |
| 113 |
else: |
| 114 |
res = subprocess.check_call(command_string, |
| 115 |
stdout=devnull) |
| 116 |
os.chmod(metric, st.st_mode) |
| 117 |
os.chown(metric, st.st_uid, st.st_gid) |
| 118 |
|
| 119 |
devnull.close() |
| 120 |
# wait for a second, so we don't kill I/O on the host |
| 121 |
time.sleep(SLEEP) |
| 122 |
""" |
| 123 |
We have manual commands for every failed file from these |
| 124 |
errors, so we can just go through each of these errors |
| 125 |
after a completed run. There shouldn't be many |
| 126 |
""" |
| 127 |
if res != 0: |
| 128 |
LOG.error('Failed to update schemas for %s' % metric) |
| 129 |
LOG.error('Attempted retention: %s' % retention) |
| 130 |
LOG.error('Attempted command string: %s' % command_string) |
| 131 |
return [(False, metric)] |
| 132 |
else: |
| 133 |
return [(True, metric)] |
| 134 |
|
| 135 |
|
| 136 |
def search_and_fix(subdir): |
| 137 |
if not SCHEMA_LIST: |
| 138 |
LOG.error("Didn't initialize schemas!") |
| 139 |
return |
| 140 |
|
| 141 |
fpath = os.path.join(ROOT_PATH, subdir) |
| 142 |
pool = Pool(cpu_count()) |
| 143 |
LOG.info('Creating new storage schemas for metrics under %s ...' % fpath) |
| 144 |
|
| 145 |
results = pool.map(fix_metric, _find_metrics(fpath), 100) |
| 146 |
pool.close() |
| 147 |
pool.join() |
| 148 |
return results |
| 149 |
|
| 150 |
|
| 151 |
# Parse command line options sent to the script |
| 152 |
def cli_opts(): |
| 153 |
parser = argparse.ArgumentParser("Correct storage settings on multiple whisper files") |
| 154 |
parser.add_argument('--cfg', action='store', dest='cfg', |
| 155 |
help='The storage-schemas.conf file path', |
| 156 |
required=True) |
| 157 |
parser.add_argument('--path', action='store', dest='path', |
| 158 |
help='The root path to find metrics in', |
| 159 |
required=True) |
| 160 |
parser.add_argument('--debug', action='store_true', dest='debug', |
| 161 |
help='Display debug information', |
| 162 |
default=False) |
| 163 |
parser.add_argument('--dry-run', action='store_true', dest='dry_run', |
| 164 |
help="Don't actually do anything", |
| 165 |
default=False) |
| 166 |
parser.add_argument('--subdir', action='store', dest='subdir', |
| 167 |
help="If you only want to process a particular subdir", |
| 168 |
default='') |
| 169 |
parser.add_argument('--nobackup', action='store_true', dest='nobackup', |
| 170 |
help="Passed through to whisper-resize.py, don't create a backup", |
| 171 |
default=False) |
| 172 |
parser.add_argument('--aggregate', action='store_true', dest='aggregate', |
| 173 |
help="Passed through to whisper-resize.py, roll up values", |
| 174 |
default=False) |
| 175 |
parser.add_argument('--bindir', action='store', dest='bindir', |
| 176 |
help="The root path to whisper-resize.py and whisper-info.py", |
| 177 |
default='/opt/graphite/bin') |
| 178 |
parser.add_argument('--sleep', action='store', type=float, dest='sleep', |
| 179 |
help="Sleep this amount of time in seconds between metric comparisons", |
| 180 |
default=0.3) |
| 181 |
return parser.parse_args() |
| 182 |
|
| 183 |
|
| 184 |
if __name__ == '__main__': |
| 185 |
i_args = cli_opts() |
| 186 |
if os.getenv('USER') != 'root': |
| 187 |
print("You must run this script as root!") |
| 188 |
sys.exit(1) |
| 189 |
|
| 190 |
if i_args.debug: |
| 191 |
LOG.setLevel(logging.DEBUG) |
| 192 |
soh = logging.StreamHandler(sys.stdout) |
| 193 |
LOG.addHandler(soh) |
| 194 |
|
| 195 |
ROOT_PATH = i_args.path |
| 196 |
DEBUG = i_args.debug |
| 197 |
DRY_RUN = i_args.dry_run |
| 198 |
BINDIR = i_args.bindir |
| 199 |
SLEEP = i_args.sleep |
| 200 |
RESIZE_BIN = BINDIR + "/whisper-resize.py" |
| 201 |
INFO_BIN = BINDIR + "/whisper-info.py" |
| 202 |
BASE_COMMAND = [RESIZE_BIN] |
| 203 |
|
| 204 |
if i_args.nobackup: |
| 205 |
BASE_COMMAND.append('--nobackup') |
| 206 |
if i_args.aggregate: |
| 207 |
BASE_COMMAND.append('--aggregate') |
| 208 |
|
| 209 |
config_schemas(i_args.cfg) |
| 210 |
search_and_fix(i_args.subdir) |