-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathpacemaker
executable file
·461 lines (380 loc) · 13.4 KB
/
pacemaker
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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2012, Michael DeHaan <[email protected]>, and others
#
# 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/>.
import re
import crmsh.parse
from crmsh.xmlutil import xml_equals
from crmsh.cibconfig import cib_factory
from lxml.etree import tostring as xmltostring
from lxml import etree
DOCUMENTATION = '''
---
module: command
version_added: historical
short_description: Executes a command on a remote node
description:
- The M(command) module takes the command name followed by a list of
space-delimited arguments.
- The given command will be executed on all selected nodes. It will not be
processed through the shell, so variables like C($HOME) and operations
like C("<"), C(">"), C("|"), and C("&") will not work (use the M(shell)
module if you need these features).
options:
free_form:
description:
- the command module takes a free form command to run
required: true
default: null
aliases: []
notes:
- If you want to run a command through the shell (say you are using C(<),
C(>), C(|), etc), you actually want the M(shell) module instead. The
M(command) module is much more secure as it's not affected by the user's
environment.
author: Michael DeHaan
'''
EXAMPLES = '''
# Example from Ansible Playbooks
- command: /sbin/shutdown -t now
# Run the command if the specified file does not exist
- command: /usr/bin/make_database.sh arg1 arg2
'''
REX = re.compile(
r"""([^ ]+)(=(['"])((?:\\.|(?!\3).)*)\3|)""",
re.DOTALL | re.VERBOSE)
cmd_xmlres_map = {
"location": "rsc_location",
}
debug = []
class BaseParser(object):
id_name = None
id = None
partial_compare = False
module = None
no_delete = False
crmsh = False
resource = True
def __init__(self, args, module=None):
if module:
self.module = module
if self.crmsh:
#debug.append("crmsh prim: %s" % args[0])
# See https://github.com/ClusterLabs/crmsh/commit/5b11db312101b2b798017fef9e7539fd5fb8585a
if hasattr(crmsh.parse,'CliParser'):
clip = crmsh.parse.CliParser()
else:
clip = crmsh.parse
# initialize cib
cib_factory.get_cib()
self.cib = clip.parse(' '.join(args))
self.command = args[0]
self.args = args
self.id = self.cib.get('id')
#debug.append("id: %s" % self.id)
else:
self.cib = self.parse(args)
self.command = self.cib["command"]
self.args = args
if self.id_name:
self.id = self.cib[self.id_name]
def parse(self, args):
raise NotImplementedError()
def is_same(self, cib):
if self.crmsh:
return xml_equals(self.cib, cib)
obj_key = list(cib)
for key, value in self.cib.items():
if key not in obj_key:
return False
if value != cib.get(key):
return False
obj_key.remove(key)
if len(obj_key) and not self.partial_compare:
return False
return True
class PrimitiveParser(BaseParser):
id_name = "rsc"
crmsh = True
class MonitorParser(BaseParser):
id_name = "rsc"
def parse(self, args):
ret = dict(
command=args.pop(0),
rsc=args.pop(0),
interval=args.pop(0),
)
return ret
class GroupParser(BaseParser):
id_name = "name"
crmsh = True
class CloneParser(BaseParser):
id_name = "name"
crmsh = True
class MsParser(CloneParser):
id_name = "name"
class RscTemplateParser(PrimitiveParser):
id_name = "name"
class LocationParser(BaseParser):
id_name = "id"
crmsh = True
resource = False
class ColocationParser(BaseParser):
id_name = "id"
resource = False
def parse(self, args):
ret = dict(
command=args.pop(0),
id=args.pop(0),
score=args.pop(0),
rsc=args[:],
)
return ret
class OrderParser(BaseParser):
id_name = "id"
resource = False
def parse(self, args):
ret = dict(
command=args.pop(0),
id=args.pop(0),
kind_or_score=args.pop(0),
rsc=args[:],
)
return ret
class PropertyParser(BaseParser):
partial_compare = True
no_delete = True
def parse(self, args):
ret = dict(
command=args.pop(0),
)
if args[0].startswith("$id"):
args.pop(0)
if args[0].startswith("cib-bootstrap-options:"):
args.pop(0)
while (args):
arg = args.pop(0)
if '=' not in arg:
self.module.fail_json(
rc=258,
msg="no key-value :%s" % arg)
key, value = arg.split("=")
if key == "":
self.module.fail_json(
rc=258,
msg="no key in key=value option")
if value == "":
self.module.fail_json(
rc=258,
msg="no value in key=value option (key=%s)" % key)
ret[key] = value
return ret
class RscDefaultsParser(PropertyParser):
partial_compare = True
no_delete = True
def parse(self, args):
return {
"command": args.pop(0)
}
class FencingTopologyParser(BaseParser):
partial_compare = True
no_delete = True
def parse(self, args):
ret = dict(
command=args.pop(0),
)
if not args[0].endswith(":"):
ret["stonith_resources"] = args
return ret
newnode = None
newfence = None
while(args):
arg = args.pop(0)
if arg.endswith(":"):
if newnode:
ret[newnode] = newfence
newnode = arg
newfence = []
else:
newfence.append(arg)
if newnode:
ret[newnode] = newfence
return ret
def splitter(args):
ret = []
for a, b, c, d in REX.findall(args):
if len(b) == 0:
ret.append(a)
else:
ret.append(a+b)
return ret
class CIBParser(object):
cib_parser_class = {
'primitive': PrimitiveParser,
'monitor': MonitorParser,
'group': GroupParser,
'clone': CloneParser,
'ms': MsParser,
'rsc_template': RscTemplateParser,
'location': LocationParser,
'colocation': ColocationParser,
'order': OrderParser,
'property': PropertyParser,
'rsc_defaults': RscDefaultsParser,
'fencing_topology': FencingTopologyParser,
}
def __init__(self, module):
self.module = module
def parse_cib(self, args):
if args[0] in self.cib_parser_class:
return self.cib_parser_class[args[0]](args[:], module=self.module)
return None
def parse_cibs(self, lines):
cibs = []
#debug.append("all lines: \n%s" % "\n".join(lines))
new_line = ""
for line in lines:
new_line += line.strip()
if new_line.endswith('\\'):
new_line = new_line.rstrip('\\')
else:
if len(new_line) == 0:
continue
args = splitter(new_line)
#debug.append("new cib to parse: %s" % args[0])
cib = self.parse_cib(args)
if cib:
cibs.append(cib)
new_line = ""
return cibs
def main():
module = AnsibleModule(
argument_spec={
'resource': dict(default=None),
'state': dict(default='present', choices=['present', 'absent']),
'action': dict(default='resource', choices=['prepare', 'resource', 'commit']),
'shadow': dict(default=None),
'ignore_target_role': dict(default=True, type='bool'),
'ignore_is_managed': dict(default=True, type='bool'),
},
supports_check_mode=True
)
state = module.params['state']
action = module.params['action']
shadow = module.params['shadow']
resource = module.params['resource']
ignore_target_role = module.params['ignore_target_role']
ignore_is_managed = module.params['ignore_is_managed']
# Action 'prepare': Create a new shadow copy of the running config
if action == "prepare":
if shadow == None:
module.fail_json(rc=256, msg="parameter 'shadow' is required for action 'prepare'")
rc, out, err = module.run_command(["crm", "cib", "new", shadow, "--force"])
if rc:
module.fail_json(rc=256, msg="crm command failed", out=out,
err=err)
module.exit_json(changed=False)
# Action 'commit': Apply shadow copy as new config
if action == "commit":
if shadow == None:
module.fail_json(rc=256, msg="parameter 'shadow' is required for action 'commit'")
rc, out, err = module.run_command(["crm", "cib", "commit", shadow])
if rc:
module.fail_json(rc=256, msg="crm command 'crm cib commit %s' failed" % shadow, out=out,
err=err)
rc, out, err = module.run_command(["crm", "cib", "delete", shadow])
if rc:
module.exit_json(changed=False, warnings=["Could not delete shadow config '%s'" % shadow])
module.exit_json(changed=False)
if action != "resource":
module.fail_json(rc=256, msg="unexpected action: '%s'" % action)
if resource == None:
module.fail_json(rc=256, msg="parameter 'resource' is required for action 'prepare'")
args = splitter(module.params['resource'].rstrip())
parser = CIBParser(module)
new = parser.parse_cib(args)
crm_base = [ "crm" ]
# if shadow is set, we do all operations on the given shadow copy of the config
if shadow != None:
crm_base = crm_base + [ "-c", shadow ]
crm_args = crm_base + [ "configure", "show"]
rc, out, err = module.run_command(crm_args)
if rc:
module.fail_json(rc=256, msg="crm configure show failed", out=out,
err=err)
is_same = None
old_cib = None
for cur in parser.parse_cibs(out.splitlines()):
#debug.append("old command: %s, id: %s" % (cur.command, cur.id))
if new.command != cur.command:
continue
if new.id != cur.id:
continue
old_cib = cur.cib
if cur.crmsh and (ignore_target_role or ignore_is_managed):
if ignore_target_role:
for target in old_cib.xpath("//meta_attributes/nvpair[@name='target-role']"):
target.getparent().remove(target)
if ignore_is_managed:
for managed in old_cib.xpath("//meta_attributes/nvpair[@name='is-managed']"):
managed.getparent().remove(managed)
for meta in old_cib.xpath("//meta_attributes"):
if len(meta.getchildren()) == 0:
meta.getparent().remove(meta)
is_same = new.is_same(old_cib)
break
need_delete = False
need_append = False
if state == 'absent':
if is_same is None:
module.exit_json(args=" ".join(args), changed=False)
elif is_same:
if new.id is None:
module.fail_json(rc=256, msg="can't delete %s" % new.command)
need_delete = True
else:
if is_same:
module.exit_json(args=" ".join(args), debug=debug, changed=False)
elif is_same is False and not new.no_delete:
need_delete = True
need_append = True
crm_config_commands = []
if need_delete:
debug.append("deleting %s" % new.id)
if new.resource:
crm_config_commands.append(["resource", "stop", new.id])
crm_config_commands.append(["configure", "delete", new.id])
if need_append:
crm_config_commands.append(["configure"] + args)
if not module.check_mode:
for command in crm_config_commands:
#debug.append("running crm -F -w %s" % command)
rc, out, err = module.run_command(crm_base + ["-F", "-w"] + command)
if rc:
module.fail_json(rc=256, msg="crm -F -w %s failed" %
' '.join(command), out=out, err=err)
if new.crmsh:
module.exit_json(
args=" ".join(args), cur=" ".join(cur.args),
old=xmltostring(old_cib, pretty_print=True) if old_cib is not None else None,
new=xmltostring(new.cib, pretty_print=True), debug=debug, changed=True)
else:
module.exit_json(args=" ".join(args), old=old_cib, new=new.cib, debug=debug,
changed=True)
# import module snippets
from ansible.module_utils.basic import * # noqa
main()