<s> from __future__ import print_function <EOL> import sys <EOL> import json <EOL> import base64 <EOL> from time import sleep <EOL> import urllib2 <EOL> import ssl <EOL> import subprocess <EOL> def get_credentials ( ) : <EOL> """<STR_LIT>""" <EOL> yaml_key = "<STR_LIT>" <EOL> try : <EOL> with open ( '<STR_LIT>' ) as f : <EOL> for line in f : <EOL> if yaml_key in line : <EOL> password = line [ len ( yaml_key ) : ] . strip ( ) <EOL> return "<STR_LIT>" + password <EOL> except IOError : <EOL> return "<STR_LIT>" <EOL> def get_hosts_from_json ( json_str , role = "<STR_LIT>" ) : <EOL> """<STR_LIT>""" <EOL> ips = [ ] <EOL> json_dic = json . loads ( json_str ) <EOL> host_data = json_dic [ "<STR_LIT>" ] [ "<STR_LIT>" ] <EOL> for key , dic in host_data . iteritems ( ) : <EOL> if dic . get ( "<STR_LIT>" , "<STR_LIT>" ) . lower ( ) == role : <EOL> ips . append ( dic [ "<STR_LIT>" ] ) <EOL> return ips <EOL> def get_hosts_from_dynamic_inventory ( cmd , role = "<STR_LIT>" ) : <EOL> """<STR_LIT>""" <EOL> proc = subprocess . Popen ( cmd , stdout = subprocess . PIPE ) <EOL> rc = proc . wait ( ) <EOL> if rc != <NUM_LIT:0> : <EOL> print ( "<STR_LIT>" , rc ) <EOL> return [ ] <EOL> else : <EOL> return get_hosts_from_json ( proc . stdout . read ( ) ) <EOL> def node_health_check ( node_address ) : <EOL> """<STR_LIT>""" <EOL> ctx = ssl . create_default_context ( ) <EOL> ctx . check_hostname = False <EOL> ctx . verify_mode = ssl . CERT_NONE <EOL> url = "<STR_LIT>" + node_address + "<STR_LIT>" <EOL> request = urllib2 . Request ( url ) <EOL> auth = b'<STR_LIT>' + base64 . b64encode ( get_credentials ( ) ) <EOL> request . add_header ( "<STR_LIT>" , auth ) <EOL> try : <EOL> f = urllib2 . urlopen ( request , None , <NUM_LIT:30> , context = ctx ) <EOL> health_checks = json . loads ( f . read ( ) . decode ( '<STR_LIT:utf8>' ) ) <EOL> for check in health_checks : <EOL> if check [ '<STR_LIT>' ] != "<STR_LIT>" : <EOL> print ( check [ '<STR_LIT:Name>' ] , "<STR_LIT::>" , check [ '<STR_LIT>' ] , "<STR_LIT:\n>" , check [ '<STR_LIT>' ] ) <EOL> return False <EOL> except Exception as e : <EOL> print ( "<STR_LIT>" , node_address , "<STR_LIT>" , e ) <EOL> return False <EOL> return True <EOL> def cluster_health_check ( ip_addresses ) : <EOL> """<STR_LIT>""" <EOL> failed = <NUM_LIT:0> <EOL> for ip in ip_addresses : <EOL> passed = node_health_check ( ip ) <EOL> print ( "<STR_LIT>" , ip , "<STR_LIT:U+0020>" , "<STR_LIT>" if passed else "<STR_LIT>" ) <EOL> failed += <NUM_LIT:0> if passed else <NUM_LIT:1> <EOL> return failed <EOL> if __name__ == "<STR_LIT:__main__>" : <EOL> print ( "<STR_LIT>" ) <EOL> sleep ( <NUM_LIT> * <NUM_LIT:2> ) <EOL> cmd = [ "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" ] <EOL> address_list = get_hosts_from_dynamic_inventory ( cmd ) <EOL> if len ( address_list ) == <NUM_LIT:0> : <EOL> print ( "<STR_LIT>" ) <EOL> sys . exit ( <NUM_LIT:1> ) <EOL> failed = cluster_health_check ( address_list ) <EOL> sys . exit ( <NUM_LIT:0> if failed == <NUM_LIT:0> else <NUM_LIT:1> ) </s>
