Skip to content

Instantly share code, notes, and snippets.

@yuuki
Created March 19, 2018 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yuuki/22bb2b099419a5ac423d45c0b776b94c to your computer and use it in GitHub Desktop.
Save yuuki/22bb2b099419a5ac423d45c0b776b94c to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
# vim: fileencoding=utf-8
import base64
import json
import os.path
import subprocess
import sys
import urllib.request
import urllib.error
SABA_DEV_ENDPOINT = 'https://saba.dev.hatena.ne.jp'
SSH_TIMEOUT = 3
def run_cmd(*cmds):
cmd = ' '.join(cmds)
res = subprocess.run(cmd, shell=True,
check=True, stdout=subprocess.PIPE)
return res.stdout.rstrip().decode('utf-8')
def print_error(msg):
print(msg, file=sys.stderr)
def find_host_by_hostname(hostname):
basic = base64.b64encode(
'hatena:iwashi'.encode('utf-8'))[:-1].decode("utf-8")
req = urllib.request.Request(
f'{SABA_DEV_ENDPOINT}/api/hosts2?name={hostname}',
headers={"Authorization": f"Basic {basic}"},
)
try:
with urllib.request.urlopen(req) as res:
return json.loads(res.read())['models'][0]
except urllib.error.HTTPError as err:
print_error(f'status {err.code}: {hostname}')
return None
def do_vrrp_instance(block):
for stmt in block['stmts']:
if stmt is None:
continue
if stmt['name'] == 'virtual_ipaddress':
for val in stmt['values']:
vip = val.split('/')[0]
try:
hostname = run_cmd(
f'ssh -o ConnectTimeout={SSH_TIMEOUT} {vip} hostname -s')
except subprocess.CalledProcessError as err:
print_error(f"ssh error: {vip} '{err.cmd}'")
continue
host = find_host_by_hostname(hostname)
roles = [
f"{role['service']['name']}:{role['name']}" for role in host['roles']]
print(f"vip: {vip}\troles:{','.join(roles)}")
def main():
conf_files = run_cmd('find', './vrrp', '-name',
"'*.*.master.conf'").split()
for f in conf_files:
if not os.path.exists(f):
continue
if f.find('lvs0') != -1: # LVSホストは除く
continue
conf = json.loads(run_cmd('gokc', '--json', '-f', f))
for block in conf['blocks']:
if block['name'] == 'vrrp_instance':
do_vrrp_instance(block)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment