forked from ansible/ansible
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathriak
289 lines (242 loc) · 8.34 KB
/
riak
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2013, James Martin <[email protected]>, Drew Kerrigan <[email protected]>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
#
DOCUMENTATION = '''
---
module: riak
short_description: This module handles some common Riak operations
description:
- This module can be used to join nodes to a cluster, check
the status of the cluster.
version_added: "1.2"
options:
command:
description:
- The command you would like to perform against the cluster.
required: false
default: null
aliases: []
choices: ['ping', 'kv_test', 'join', 'plan', 'commit']
config_dir:
description:
- The path to the riak configuration directory
required: false
default: /etc/riak
aliases: []
http_conn:
description:
- The ip address and port that is listening for Riak HTTP queries
required: false
default: 127.0.0.1:8098
aliases: []
target_node:
description:
- The target node for certain operations (join, ping)
required: false
default: [email protected]
aliases: []
wait_for_handoffs:
description:
- Waits for handoffs to complete before continuing. This can take awhile and should generally be used with async mode.
required: false
default: null
aliases: []
type: 'bool'
wait_for_ring:
description:
- Waits for all nodes to agreee on the status of the ring
required: false
default: null
aliases: []
type: 'bool'
wait_for_service:
description:
- Waits for a riak service to come online before continuing.
required: false
default: kv
aliases: []
choices: ['kv']
examples:
- code: "riak: command=join [email protected]"
description: "Join's a Riak node to another node"
- code: "riak: wait_for_handoffs=true"
description: "Wait for handoffs to finish. Use with async and poll."
- code: "riak: wait_for_service=kv"
description: "Wait for riak_kv service to startup"
'''
import re
import os.path
import urllib2
import json
import time
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
def ring_check():
rc, out, err = module.run_command('riak-admin ringready 2> /dev/null')
if rc == 0 and out.find('TRUE All nodes agree on the ring') != -1:
return True
else:
return False
def status_to_json():
# remove all unnecessary symbols and whitespace
rc, out, err = module.run_command("riak-admin status 2> /dev/null")
if rc == 0:
raw_stats = out
else:
module.fail_json(msg="Could not properly gather stats")
for line in raw_stats.splitlines():
stats += line.strip() + '\n'
stats = stats.replace('<<', '').replace('>>', '')
stats = stats.replace('\\n', '').replace(',\n', ',')
stats = stats.replace(": '", ': ').replace("'\n", "\n")
stats = stats.replace(': "[', ': [').replace(']"\n', "]\n")
stats = stats.replace('"', "'")
matchObj = re.compile(r"^(.*) : (.*)", re.M | re.I)
json_stats = '{'
for match in matchObj.finditer(stats):
key, value = match.groups()
if (value[0] == "'"):
value = value[1:-1]
if not is_number(value):
value = '"' + value + '"'
json_stats += '"' + key + '":' + value + ','
json_stats = json_stats[0:-1]
json_stats += '}'
return json_stats
def main():
ansible_facts = {}
arg_spec = dict(
command=dict(required=False, default=None, choices=[
'ping', 'kv_test', 'join', 'plan', 'commit']),
config_dir=dict(default='/etc/riak'),
http_conn=dict(required=False, default='127.0.0.1:8098'),
target_node=dict(default='[email protected]', required=False),
wait_for_handoffs=dict(default=False, type='bool'),
wait_for_ring=dict(default=False, type='bool'),
wait_for_service=dict(
required=False, default=None, choices=['kv'])
)
global module
module = AnsibleModule(argument_spec=arg_spec)
command = module.params.get('command')
config_dir = module.params.get('config_dir')
http_conn = module.params.get('http_conn')
target_node = module.params.get('target_node')
wait_for_handoffs = module.params.get('wait_for_handoffs')
wait_for_ring = module.params.get('wait_for_ring')
wait_for_service = module.params.get('wait_for_service')
rc = 0
err = ''
out = ''
#make sure riak commands are on the path
for item in ['riak', 'riak-admin']:
rc, out, err = module.run_command('which %s' % item)
if rc == 1:
module.fail_json(msg='Could not find path to %s executable' % item)
rc, out, err = module.run_command(
"riak version 2> /dev/null |grep ^riak|cut -f2 -d' '|tr -d '('")
if rc == 0:
version = out.strip()
else:
module.fail_json(msg='Could not determine Riak version')
try:
stats_raw = urllib2.urlopen(
'http://%s/stats' % (http_conn), None, 5).read()
except urllib2.HTTPError, e:
stats_raw = status_to_json()
except urllib2.URLError, e:
stats_raw = status_to_json()
except Exception, e:
stats_raw = status_to_json()
stats = json.loads(stats_raw)
node_name = stats['nodename']
nodes = stats['ring_members']
ring_size = stats['ring_creation_size']
result = {'node_name': node_name,
'nodes': nodes,
'ring_size': ring_size,
'version': version}
if command == 'ping':
rc, out, err = module.run_command('riak ping %s' % target_node)
if rc == 0:
result['ping'] = out
else:
module.fail_json(msg=out)
elif command == 'kv_test':
rc, out, err = module.run_command('riak-admin test')
if rc == 0:
result['kv_test'] = out
else:
module.fail_json(msg=out)
elif command == 'join':
if nodes.count(node_name) == 1 and len(nodes) > 1:
result['join'] = 'Node is already in cluster or staged to be in cluster.'
else:
rc, out, err = module.run_command('riak-admin cluster join %s' % target_node)
if rc == 0:
result['join'] = out
result['changed'] = True
else:
module.fail_json(msg=out)
elif command == 'plan':
rc, out, err = module.run_command('riak-admin cluster plan %s' % target_node)
if rc == 0:
result['plan'] = out
if out.find('Staged Changes') != -1:
result['changed'] = True
else:
module.fail_json(msg=out)
elif command == 'commit':
rc, out, err = module.run_command('riak-admin cluster commit %s' % target_node)
if rc == 0:
result['commit'] = out
changed = True
else:
module.fail_json(msg=out)
rc = 0
err = ''
out = ''
wait = 0
# this could take a while, recommend to run in async mode
if wait_for_handoffs:
while wait == 0:
rc, out, err = module.run_command('riak-admin transfers 2> /dev/null')
if out.find('No transfers active') != -1:
result['handoffs'] = 'No transfers active.'
break
time.sleep(10)
# this could take a while, recommend to run in async mode
if wait_for_service:
rc, out, err = module.run_command('riak-admin wait_for_service riak_%s %s' % (
wait_for_service, node_name))
result['service'] = out
if wait_for_ring:
while wait == 0:
if ring_check():
break
time.sleep(10)
result['ring_ready'] = ring_check()
module.exit_json(**result)
# this is magic, see lib/ansible/module_common.py
#<<INCLUDE_ANSIBLE_MODULE_COMMON>>
main()