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
   | 
 
 
  __author__ = 'whyvv blog'
  import consul import sys import getopt
 
 
  consul_address = '127.0.0.1' consul_port = '8500' consul_dc = '' usage = '''Usage: purge_unhealth_service.py -h <host> -p <port> -d <datacenter> help:     -H,--host           consul host address(default:127.0.0.1)     -p,--port           consul port(default:8500)     -d,--datacenter     consul datacenter(default:null)     -h,--help           Usage help'''
 
 
  def purge_unhealth_service(server=consul_address, server_port=consul_port, consul_dc=consul_dc):     consul_obj = consul.Consul(host=server, port=server_port, scheme='http', dc=consul_dc)     all_services = consul_obj.health.state('any')     for service in all_services[1]:         if service['Status'] != 'passing':             print('purge %s "%s" Service with ServiceID: "%s" on Node %s' % (service['Status'], service['ServiceName'], service['ServiceID'], service['Node']))             p_consul_obj = consul.Consul(host=service['Node'], port=server_port, scheme='http', dc=consul_dc)             pruge_rc = p_consul_obj.agent.service.deregister(service['ServiceID'])             if pruge_rc:                 print('purge successful!')             else:                 print('purge failed!')             
  if __name__ == '__main__':          if sys.argv[1:]:         opts, args = getopt.getopt(sys.argv[1:], 'hH:p:d:', ['help', 'host=', 'port=', 'datacenter='])         for opt, arg in opts:             if opt in ('-H', '--host'):                 consul_address = arg             elif opt in ('-p', '--port'):                 consul_port = int(arg)             elif opt in ('-d', '--datacenter'):                 consul_dc = arg             else:                 print(usage)                 exit()     purge_unhealth_service()
 
  |