consul在使用或测试中过程中,可能会产生不少垃圾数据(不健康的服务,没有完成注销动作而遗留在consul内),手动清理比较麻烦,然后自己写了个python脚本来一键清理这些脏数据,分享给大家。

脚本:consul_purge.py

环境依赖:python2、3

包依赖:pip install python-consul

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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# consul unhealth service purge script

__author__ = 'whyvv blog'

import consul
import sys
import getopt


# define variables
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'''


# purge unhealth service for consul
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__':
# get args
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()

使用帮助:./purge_unhealth_service.py --help

注:此脚本会清理所有非passing(健康)状态的服务,请谨慎使用!