health_check
2.93 KB
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# ansible module for http health checking
ANSIBLE_METADATA = {
'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'chunhua.zhang'
}
DOCUMENTATION = '''
---
module: health_check
short_description: 检查有货java的服务健康状态
'''
EXAMPLES = '''
# order
- hosts: java-order
tasks:
- health_check:
name: 获取商品详情
url: "http://127.0.0.1:8084/order/orderInfo/getOrderList"
content-type: json
params: '{"param":439486}'
'''
from ansible.module_utils.basic import *
import requests
import json
import jsonschema
'''
检查http服务的状态
'''
def check_http_status(url, content_type, params, schema, headers = {}):
ret = {}
if content_type == 'json':
r = requests.post(url, json = json.loads(params))
else:
r = requests.get(url, headers = headers)
# check http status code
ret['http_code'] = r.status_code
#ret['message'] = r.text
if r.status_code == requests.codes.ok:
# json validate
if schema :
try:
jsonschema.validate(r.json(), json.loads(schema))
ret["code"] = 200
except jsonschema.exceptions.ValidationError :
ret["code"] = 500
ret['err'] = r.text
else:
ret["code"] = 200
else:
ret["code"] = r.status_code
ret["err"] = "http status error: %i" % r.status_code
return ret
def run_module():
# 定义参数
module_args = dict(
name=dict(type='str', required=True),
url=dict(type='str', required=True),
content_type=dict(type='str', required=False),
params=dict(type='str', required=False)
)
# seed the result dict in the object
# we primarily care about changed and state
# change is if this module effectively modified the target
# state will include any data that you want your module to pass back
# for consumption, for example, in a subsequent task
result = dict(
changed=False,
original_message='',
message=''
)
module = AnsibleModule(
argument_spec=module_args,
supports_check_mode=True
)
if module.check_mode:
return result
url = module.params['url']
name = module.params['name']
content_type = module.params['content_type']
params = module.params['params']
schema = module.params['params']
result['check_name'] = module.params['name']
result['url'] = module.params['url']
result['changed'] = False
# check result
ret = check_http_status(url, content_type, schema, params)
if ret['code'] != 200:
module.fail_json(msg='Check Failed: http code:%i, json code: %i, err: %s' % (ret['http_code'], ret['code'], ret['err']), **result)
result['response'] = ret
module.exit_json(**result)
def main():
run_module()
if __name__ == '__main__':
main()