forked from yosshy/ansible-pacemaker
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpacemaker
executable file
·521 lines (429 loc) · 14.1 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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
#!/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 sys
import datetime
import traceback
import re
import shlex
import os
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)
class BaseParser(object):
id_name = None
id = None
partial_compare = False
module = None
no_delete = False
def __init__(self, args, module=None):
if module:
self.module = module
self.cib = self.parse(args)
self.command = self.cib["command"]
if self.id_name:
self.id = self.cib[self.id_name]
def parse(self, args):
raise NotImplementedError()
def is_same(self, obj):
obj_key = obj.cib.keys()
for key, value in self.cib.iteritems():
if key not in obj_key:
return False
if value != obj.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"
def parse(self, args):
ret = dict(
command=args.pop(0),
rsc=args.pop(0),
type=args.pop(0),
)
if ':' not in ret['type']:
ret['type'] = 'ocf:heartbeat:' + ret['type']
mode = None
while (len(args) > 0):
arg = args.pop(0)
if (arg in ["params", "meta", "utilization",
"operations", "op"]):
mode = arg
if (arg == "op"):
op_type = args.pop(0)
continue
if '=' not in arg:
raise Exception("no key=value option: %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)
if value.startswith('"') and value.endswith('"'):
value = value[1:-1]
if mode not in ret:
ret[mode] = {}
if (mode == "op"):
if op_type not in ret[mode]:
ret[mode][op_type] = {}
ret[mode][op_type][key] = value
else:
if mode not in ret:
ret[mode] = {}
ret[mode][key] = value
return ret
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"
def parse(self, args):
ret = dict(
command=args.pop(0),
name=args.pop(0),
rsc=[],
)
mode = None
while (args):
arg = args.pop(0)
if (arg in ["params", "meta"]):
mode = arg
continue
if mode is None:
rsc.append(arg)
continue
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)
if mode not in ret:
ret[mode] = {}
ret[mode][key] = value
return ret
class CloneParser(BaseParser):
id_name = "name"
def parse(self, args):
ret = dict(
command=args.pop(0),
name=args.pop(0),
rsc=args.pop(0),
)
mode = None
while (args):
arg = args.pop(0)
if (arg in ["params", "meta"]):
mode = arg
continue
if mode is None:
self.module.fail_json(rc=258, msg="no params or meta")
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)
if mode not in ret:
ret[mode] = {}
ret[mode][key] = value
return ret
class MsParser(CloneParser):
id_name = "name"
class RscTemplateParser(PrimitiveParser):
id_name = "name"
class LocationParser(BaseParser):
id_name = "id"
def parse(self, args):
argscopy = list(args)
ret = dict(
command=args.pop(0),
id=args.pop(0),
rsc=args.pop(0),
)
ret["rules"] = []
newrule = None
while (args):
arg = args.pop(0)
if arg == "rule":
if newrule:
ret["rules"].append(newrule)
newrule = dict(expression=[])
arg = args.pop(0)
while arg.startswith("$"):
key, value = arg.split("=")
if value == "":
self.module.fail_json(
rc=258,
msg="no value in key=value option (key=%s)" % key)
newrule[key] = value
arg = args.pop(0)
if arg.endswith(":"):
newrule["score"] = arg
else:
self.module.fail_json(
rc=258,
msg="no score in rule for location (id=%s)" % ret["id"])
elif newrule is not None:
newrule["expression"].append(arg)
else:
self.module.fail_json(
rc=258,
msg="no rule for location (id=%s)" % ret["id"],
args=argscopy)
if newrule:
ret["rules"].append(newrule)
return ret
class ColocationParser(BaseParser):
id_name = "id"
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"
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
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 = []
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)
cib = self.parse_cib(args)
if cib:
cibs.append(cib)
new_line = ""
return cibs
def main():
module = AnsibleModule(
argument_spec={
'resource': dict(required=True),
'state': dict(default='present', choices=['present', 'absent']),
'commit': dict(default=True, type='bool', choices=BOOLEANS),
},
supports_check_mode=True
)
state = module.params['state']
need_commit = module.params['commit']
args = splitter(module.params['resource'])
changed = False
if len(args) == 0:
module.fail_json(rc=256, msg="no command given")
if args[0] == "commit":
rc, out, err = module.run_command(["crm", "configure", "commit"])
if rc:
module.fail_json(rc=256, msg="crm command failed", out=out, err=err)
module.exit_json(args=args, changed=True)
parser = CIBParser(module)
new = parser.parse_cib(args)
crm_args = ["crm", "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()):
if new.command != cur.command:
continue
if new.id != cur.id:
continue
old_cib = cur.cib
is_same = new.is_same(cur)
break
need_delete = False
need_append = False
if state == 'absent':
if is_same is None:
module.exit_json(args=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=args, changed=False)
elif is_same is False and not new.no_delete:
need_delete = True
need_append = True
crm_config_commands = []
if need_delete:
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 need_commit:
crm_config_commands.append(["configure", "commit"])
if not module.check_mode:
for command in crm_config_commands:
rc, out, err = module.run_command(["crm", "-F", "-w"] + command)
if rc:
module.fail_json(rc=256, msg="crm -F -w %s failed" % ' '.join(command), out=out, err=err)
module.exit_json(args=args, old=old_cib, new=new.cib, changed=True)
# import module snippets
from ansible.module_utils.basic import *
main()