summaryrefslogtreecommitdiffstats
path: root/crmsh/xmlutil.py
blob: ee3f96a4e7938656c9c5fbb51131287a48bdbe2a (plain)
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
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
# Copyright (C) 2008-2011 Dejan Muhamedagic <dmuhamedagic@suse.de>
# Copyright (C) 2016 Kristoffer Gronlund <kgronlund@suse.com>
# See COPYING for license information.

import os
import subprocess
from lxml import etree, doctestcompare
import copy
import bz2
from collections import defaultdict
from tempfile import mktemp

from . import config, sh
from . import options
from . import schema
from . import constants
from . import userdir
from .sh import ShellUtils
from .utils import add_sudo, str2file, str2tmp, get_boolean, handle_role_for_ocf_1_1, copy_local_file, rmfile
from .utils import stdout2list, crm_msec, crm_time_cmp
from .utils import olist, get_cib_in_use, get_tempdir, to_ascii, is_boolean_true
from . import log


logger = log.setup_logger(__name__)
logger_utils = log.LoggerUtils(logger)


def xmlparse(f):
    try:
        cib_elem = etree.parse(f).getroot()
    except Exception as msg:
        logger.error("cannot parse xml: %s", msg)
        return None
    return cib_elem


def file2cib_elem(s):
    cib_tmp_copy = ''
    try:
        f = open(s, 'r')
    except IOError as msg:
        logger.debug("{} tried to read cib.xml, but : {}".format(userdir.getuser(), msg))
        cib_tmp_copy = mktemp(suffix=".cib.xml")

    if cib_tmp_copy != '':
        logger.debug("{} gonna try it with sudo".format(userdir.getuser()))
        # Actually it's not trying to open the file with sudo,
        # but copying the file with sudo. We do copy,
        # because xmlparse function requires the function descriptor not the plain text
        # and this would be so much work to redo it.
        # It's not too bad, but it's still a workaround and better be refactored, so FIXME!
        copy_local_file(s, cib_tmp_copy)
        f = open(cib_tmp_copy, 'r')
        logger.debug("{} successfully read the cib.xml".format(userdir.getuser()))

    cib_elem = xmlparse(f)
    f.close()
    if cib_tmp_copy != '':
        rmfile(cib_tmp_copy)
    if options.regression_tests and cib_elem is None:
        print("Failed to read CIB from file: %s" % (s))
    return cib_elem


def compressed_file_to_cib(s):
    try:
        if s.endswith('.bz2'):
            f = bz2.BZ2File(s)
        elif s.endswith('.gz'):
            import gzip
            f = gzip.open(s)
        else:
            f = open(s)
    except IOError as msg:
        logger.error(msg)
        return None
    cib_elem = xmlparse(f)
    if options.regression_tests and cib_elem is None:
        print("Failed to read CIB from file %s" % (s))
        f.seek(0)
        print(f.read())
    f.close()
    return cib_elem


cib_dump = "cibadmin -Ql"


def sudocall(cmd):
    cmd = add_sudo(cmd)
    if options.regression_tests:
        print(".EXT", cmd)
    p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    try:
        outp, errp = p.communicate()
        p.wait()
        return p.returncode, to_ascii(outp), to_ascii(errp)
    except IOError as msg:
        logger.error("running %s: %s", cmd, msg)
        return None, None, None


def cibdump2file(fname):
    _, outp, _ = sudocall(cib_dump)
    if outp is not None:
        return str2file(outp, fname)
    return None


def cibdump2tmp():
    try:
        _, outp, _ = sudocall(cib_dump)
        if outp is not None:
            return str2tmp(outp)
    except IOError as msg:
        logger.error(msg)
    return None


def text2elem(text):
    """
    Convert a text format CIB to
    an XML tree.
    """
    try:
        return etree.fromstring(text)
    except Exception as err:
        logger_utils.text_xml_parse_err(err, text)
        return None


def cibdump2elem(section=None):
    if section:
        cmd = "%s -o %s" % (cib_dump, section)
    else:
        cmd = cib_dump
    rc, outp, errp = sudocall(cmd)
    if rc == 0:
        return text2elem(outp)
    else:
        logger.error("running %s: %s", cmd, errp)
    return None


def read_cib(fun, params=None):
    cib_elem = fun(params)
    if cib_elem is None or cib_elem.tag != "cib":
        return None
    return cib_elem


def sanity_check_nvpairs(ident, node, attr_list):
    rc = 0
    for nvpair in node.iterchildren("nvpair"):
        n = nvpair.get("name")
        if n and n not in attr_list:
            logger.warning("%s: unknown attribute '%s'", ident, n)
            rc |= 1
    return rc


def sanity_check_meta(ident, node, attr_list):
    rc = 0
    if node is None or not attr_list:
        return rc
    for c in node.iterchildren():
        if c.tag == "meta_attributes":
            rc |= sanity_check_nvpairs(ident, c, attr_list)
    return rc


def get_interesting_nodes(node, nodes_l):
    '''
    All nodes which can be represented as CIB objects.
    '''
    for c in node.iterchildren():
        if is_cib_element(c):
            nodes_l.append(c)
        get_interesting_nodes(c, nodes_l)
    return nodes_l


def get_top_cib_nodes(node, nodes_l):
    '''
    All nodes which can be represented as CIB objects, but not
    nodes which are children of other CIB objects.
    '''
    for c in node.iterchildren():
        if is_cib_element(c):
            nodes_l.append(c)
        else:
            get_top_cib_nodes(c, nodes_l)
    return nodes_l


class RscState(object):
    '''
    Get the resource status and some other relevant bits.
    In particular, this class should allow for a bit of caching
    of cibadmin -Q -o resources output in case we need to check
    more than one resource in a row.
    '''

    rsc_status = "crm_resource -W -r '%s'"

    def __init__(self):
        self.current_cib = None
        self.rsc_elem = None
        self.prop_elem = None
        self.rsc_dflt_elem = None

    def _init_cib(self):
        cib = cibdump2elem("configuration")
        self.current_cib = cib
        self.rsc_elem = get_first_conf_elem(cib, "resources")
        self.prop_elem = get_first_conf_elem(cib, "crm_config/cluster_property_set")
        self.rsc_dflt_elem = get_first_conf_elem(cib, "rsc_defaults/meta_attributes")

    def rsc2node(self, ident):
        '''
        Get a resource XML element given the id.
        NB: this is called from almost all other methods.
        Hence we initialize the cib here. CIB reading is
        expensive.
        '''
        if self.rsc_elem is None:
            self._init_cib()
        if self.rsc_elem is None:
            return None
        # does this need to be optimized?
        expr = './/*[@id="%s"]' % ident
        try:
            return self.rsc_elem.xpath(expr)[0]
        except (IndexError, AttributeError):
            return None

    def is_ms_or_promotable_clone(self, ident):
        '''
        Test if the resource is master-slave.
        '''
        rsc_node = self.rsc2node(ident)
        if rsc_node is None:
            return False
        return is_ms_or_promotable_clone(rsc_node)

    def rsc_clone(self, ident):
        '''
        Return id of the clone/ms containing this resource
        or None if it's not cloned.
        '''
        rsc_node = self.rsc2node(ident)
        if rsc_node is None:
            return None
        pnode = rsc_node.getparent()
        if pnode is None:
            return None
        if is_group(pnode):
            pnode = pnode.getparent()
        if is_clonems(pnode):
            return pnode.get("id")
        return None

    def is_managed(self, ident):
        '''
        Is this resource managed?
        '''
        rsc_node = self.rsc2node(ident)
        if rsc_node is None:
            return False
        # maintenance-mode, if true, overrides all
        attr = get_attr_value(self.prop_elem, "maintenance-mode")
        if attr and is_xs_boolean_true(attr):
            return False
        # then check the rsc is-managed meta attribute
        rsc_meta_node = get_rsc_meta_node(rsc_node)
        attr = get_attr_value(rsc_meta_node, "is-managed")
        if attr:
            return is_xs_boolean_true(attr)
        # then rsc_defaults is-managed attribute
        attr = get_attr_value(self.rsc_dflt_elem, "is-managed")
        if attr:
            return is_xs_boolean_true(attr)
        # finally the is-managed-default property
        attr = get_attr_value(self.prop_elem, "is-managed-default")
        if attr:
            return is_xs_boolean_true(attr)
        return True

    def is_running(self, ident):
        '''
        Is this resource running?
        '''
        if not is_live_cib():
            return False
        test_id = self.rsc_clone(ident) or ident
        rc, outp = ShellUtils().get_stdout(self.rsc_status % test_id, stderr_on=False)
        return outp.find("running") > 0 and outp.find("NOT") == -1

    def is_group(self, ident):
        '''
        Test if the resource is a group
        '''
        rsc_node = self.rsc2node(ident)
        if rsc_node is None:
            return False
        return is_group(rsc_node)

    def can_delete(self, ident):
        '''
        Can a resource be deleted?
        The order below is important!
        '''
        return not (self.is_running(ident) and not self.is_group(ident) and self.is_managed(ident))


def resources_xml():
    return cibdump2elem("resources")


def is_normal_node(n):
    return n.tag == "node" and (n.get("type") in (None, "normal", "member", ""))


def unique_ra(typ, klass, provider):
    """
    Unique:
    * it's explicitly ocf:heartbeat:
    * no explicit class or provider
    * only one provider (heartbeat counts as one provider)
    Not unique:
    * class is not ocf
    * multiple providers
    """
    if klass is None and provider is None:
        return True
    return klass == 'ocf' and provider is None or provider == 'heartbeat'


def mk_rsc_type(n):
    """
    Returns prefixless for unique RAs
    """
    ra_type = n.get("type")
    ra_class = n.get("class")
    ra_provider = n.get("provider")
    if unique_ra(ra_type, ra_class, ra_provider):
        ra_class = None
        ra_provider = None
    s1 = s2 = ''
    if ra_class:
        s1 = "%s:" % ra_class
    if ra_provider:
        s2 = "%s:" % ra_provider
    return ''.join((s1, s2, ra_type))


def listnodes(include_remote_nodes=True):
    cib = cibdump2elem()
    if cib is None:
        return []
    local_nodes = cib.xpath('/cib/configuration/nodes/node/@uname')
    if include_remote_nodes:
        remote_nodes = cib.xpath('/cib/status/node_state[@remote_node="true"]/@uname')
    else:
        remote_nodes = []
    return list(set([n for n in local_nodes + remote_nodes if n]))


def is_our_node(s):
    '''
    Check if s is in a list of our nodes (ignore case).
    This is not fast, perhaps should be cached.

    Includes remote nodes as well
    '''
    for n in listnodes():
        if n.lower() == s.lower():
            return True
    return False


def is_remote_node(n):
    cib = cibdump2elem()
    if cib is None:
        return False
    remote_nodes = cib.xpath('/cib/status/node_state[@remote_node="true"]/@uname')
    return any(n == r for r in remote_nodes if r)


def is_live_cib():
    '''We working with the live cluster?'''
    return not get_cib_in_use() and not os.getenv("CIB_file")


def is_crmuser():
    crmusers = ("root", config.path.crm_daemon_user)
    return config.core.user in crmusers or userdir.getuser() in crmusers


def cib_shadow_dir():
    if os.getenv("CIB_shadow_dir"):
        return os.getenv("CIB_shadow_dir")
    if is_crmuser():
        return config.path.crm_config
    home = userdir.gethomedir(config.core.user)
    if home and home.startswith(os.path.sep):
        return os.path.join(home, ".cib")
    return get_tempdir()


def listshadows():
    d = cib_shadow_dir()
    if not os.path.isdir(d):
        return []
    rc, l = stdout2list("ls %s | fgrep shadow. | sed 's/^shadow\\.//'" % d)
    return l


def shadowfile(name):
    return "%s/shadow.%s" % (cib_shadow_dir(), name)


def pe2shadow(pe_file, name):
    '''Copy a PE file (or any CIB file) to a shadow.'''
    try:
        bits = open(pe_file, 'rb').read()
    except IOError as msg:
        logger.error("open: %s", msg)
        return False
    # decompresed if it ends with .bz2
    if pe_file.endswith(".bz2"):
        bits = bz2.decompress(bits)
    # copy input to the shadow
    try:
        open(shadowfile(name), "wb").write(bits)
    except IOError as msg:
        logger.error("open: %s", msg)
        return False
    return True


def is_xs_boolean_true(b):
    return b.lower() in ("true", "1")


def cloned_el(node):
    for c in node.iterchildren():
        if is_resource(c):
            return c.tag


def get_topmost_rsc(node):
    '''
    Return a topmost node which is a resource and contains this resource
    '''
    if is_container(node.getparent()):
        return get_topmost_rsc(node.getparent())
    return node


attr_defaults = {
    "rule": (("boolean-op", "and"),),
    "expression": (("type", "string"),),
}


def drop_attr_defaults(node, ts=0):
    try:
        for defaults in attr_defaults[node.tag]:
            if node.get(defaults[0]) == defaults[1]:
                del node.attrib[defaults[0]]
    except:
        pass


def nameandid(e, level):
    if e.tag:
        print(level*' ', e.tag, e.get("id"), e.get("name"))


def xmltraverse(e, fun, ts=0):
    for c in e.iterchildren():
        fun(c, ts)
        xmltraverse(c, fun, ts+1)


def xmltraverse_thin(e, fun, ts=0):
    '''
    Skip elements which may be resources themselves.
    NB: Call this only on resource (or constraint) nodes, but
    never on cib or configuration!
    '''
    for c in e.iterchildren():
        if c.tag not in ('primitive', 'group'):
            xmltraverse_thin(c, fun, ts+1)
    fun(e, ts)


def xml_processnodes(e, node_filter, proc):
    '''
    Process with proc all nodes that match filter.
    '''
    node_list = []
    for child in e.iterchildren():
        if node_filter(child):
            node_list.append(child)
        if len(child) > 0:
            xml_processnodes(child, node_filter, proc)
    if node_list:
        proc(node_list)


# filter the cib
def true(e):
    'Just return True.'
    return True


def is_entity(e):
    return e.tag == etree.Entity


def is_comment(e):
    return e.tag == etree.Comment


def is_status_node(e):
    return e.tag == "status"


def is_emptyelem(node, tag_l):
    if node.tag in tag_l:
        for a in constants.precious_attrs:
            if node.get(a):
                return False
        for n in node.iterchildren():
            return False
        return True
    else:
        return False


def is_emptynvpairs(node):
    return is_emptyelem(node, constants.nvpairs_tags)


def is_emptyops(node):
    return is_emptyelem(node, ("operations",))


def is_cib_element(node):
    return node.tag in constants.cib_cli_map


def is_group(node):
    return node.tag == "group"


def is_attr_set(node, attr):
    return get_attr_value(get_child_nvset_node(node), attr) is not None


def is_ms_or_promotable_clone(node):
    is_promotable_type = is_boolean_true(is_attr_set(node, "promotable"))
    is_ms_type = node.tag in ("master", "ms")
    return is_ms_type or is_promotable_type


def is_clone(node):
    return node.tag == "clone"


def is_clonems(node):
    return node.tag in constants.clonems_tags


def is_cloned(node):
    return (node.getparent().tag in constants.clonems_tags or
            (node.getparent().tag == "group" and
             node.getparent().getparent().tag in constants.clonems_tags))


def is_container(node):
    return node.tag in constants.container_tags


def is_primitive(node):
    return node.tag == "primitive"


def is_resource(node):
    return node.tag in constants.resource_tags


def is_template(node):
    return node.tag == "template"


def is_child_rsc(node):
    return node.tag in constants.children_tags


def is_constraint(node):
    return node.tag in constants.constraint_tags


def is_defaults(node):
    return node.tag in constants.defaults_tags


def rsc_constraint(rsc_id, con_elem):
    for attr in list(con_elem.keys()):
        if attr in constants.constraint_rsc_refs \
                and rsc_id == con_elem.get(attr):
            return True
    for rref in con_elem.xpath("resource_set/resource_ref"):
        if rsc_id == rref.get("id"):
            return True
    return False


def is_related(rsc_id, node):
    """
    checks if the given node is an element
    that has a direct relation to rsc_id. That is,
    if it contains it, if it references it...
    """
    if is_constraint(node) and rsc_constraint(rsc_id, node):
        return True
    if node.tag == 'tag':
        if len(node.xpath('.//obj_ref[@id="%s"]' % (rsc_id))) > 0:
            return True
        return False
    if is_container(node):
        for tag in ('primitive', 'group', 'clone', 'master'):
            if len(node.xpath('.//%s[@id="%s"]' % (tag, rsc_id))) > 0:
                return True
        return False
    return False


def sort_container_children(e_list):
    '''
    Make sure that attributes's nodes are first, followed by the
    elements (primitive/group). The order of elements is not
    disturbed, they are just shifted to end!
    '''
    for node in e_list:
        children = [x for x in node.iterchildren()
                    if x.tag in constants.children_tags]
        for c in children:
            node.remove(c)
        for c in children:
            node.append(c)


def rmnode(e):
    if e is not None and e.getparent() is not None:
        e.getparent().remove(e)


def rmnodes(e_list):
    for e in e_list:
        rmnode(e)


def printid(e_list):
    for e in e_list:
        ident = e.get("id")
        if ident:
            print("element id:", ident)


def remove_dflt_attrs(e_list):
    '''
    Drop optional attributes which are already set to default
    '''
    for e in e_list:
        try:
            d = constants.attr_defaults[e.tag]
            for a in list(d.keys()):
                if e.get(a) == d[a]:
                    del e.attrib[a]
        except:
            pass


def remove_text(e_list):
    for e in e_list:
        if not is_comment(e):
            e.text = None
            e.tail = None


def sanitize_cib(doc):
    xml_processnodes(doc, is_status_node, rmnodes)
    # xml_processnodes(doc, true, printid)
    # xml_processnodes(doc, is_emptynvpairs, rmnodes)
    # xml_processnodes(doc, is_emptyops, rmnodes)
    xml_processnodes(doc, is_entity, rmnodes)
    # xml_processnodes(doc, is_comment, rmnodes)
    xml_processnodes(doc, is_container, sort_container_children)
    xml_processnodes(doc, true, remove_dflt_attrs)
    xml_processnodes(doc, true, remove_text)
    xmltraverse(doc, drop_attr_defaults)

def sanitize_cib_for_patching(doc):
    """
    Custom version of sanitize_cib which
    doesn't sort container children, to use
    for processing the original CIB when
    generating a patch to apply using crm_diff.
    """
    xml_processnodes(doc, is_status_node, rmnodes)
    xml_processnodes(doc, is_entity, rmnodes)
    xml_processnodes(doc, true, remove_dflt_attrs)
    xml_processnodes(doc, true, remove_text)

def is_simpleconstraint(node):
    return len(node.xpath("resource_set/resource_ref")) == 0


match_list = defaultdict(tuple,
                         {"node": ("uname",),
                          "nvpair": ("name",),
                          "op": ("name", "interval"),
                          "rule": ("score", "score-attribute", "role"),
                          "expression": ("attribute", "operation", "value"),
                          "fencing-level": ("target", "devices"),
                          "alert": ("path",),
                          "recipient": ("value",)})


def add_comment(e, s):
    '''
    Add comment s to e from doc.
    '''
    if e is None or not s:
        return
    comm_elem = etree.Comment(s)
    firstelem_idx = 0
    for c in e.iterchildren():
        firstelem_idx = e.index(c)
        break
    e.insert(firstelem_idx, comm_elem)


def stuff_comments(node, comments):
    if not comments:
        return
    for s in reversed(comments):
        add_comment(node, s)


def fix_comments(e):
    'Make sure that comments start with #'
    celems = [x for x in e.iterchildren() if is_comment(x)]
    for c in celems:
        c.text = c.text.strip()
        if not c.text.startswith("#"):
            c.text = "# %s" % c.text


def set_id_used_attr(e):
    e.set("__id_used", "Yes")


def is_id_used_attr(e):
    return e.get("__id_used") == "Yes"


def remove_id_used_attr(e, lvl):
    if is_id_used_attr(e):
        del e.attrib["__id_used"]


def remove_id_used_attributes(e):
    if e is not None:
        xmltraverse(e, remove_id_used_attr)


def lookup_node(node, oldnode, location_only=False, ignore_id=False):
    '''
    Find a child of oldnode which matches node.
    This is used to "harvest" existing ids in order to prevent
    irrelevant changes to the XML code.
    The list of attributes to match is in the dictionary
    match_list.
    The "id" attribute is treated differently. In case the new node
    (the first parameter here) contains the id, then the "id"
    attribute is added to the match list.
    '''
    if oldnode is None:
        return None
    attr_list = list(match_list[node.tag])
    if not ignore_id and node.get("id"):
        attr_list.append("id")
    for c in oldnode.iterchildren():
        if not location_only and is_id_used_attr(c):
            continue
        if node.tag == c.tag:
            for a in attr_list:
                if node.get(a) != c.get(a):
                    break
            else:
                return c
    return None


def find_operation(rsc_node, name, interval=None):
    '''
    Setting interval to "non-0" means get the first op with interval
    different from 0.
    Not setting interval at all means get the only matching op, or the
    0 op (if any)
    '''
    matching_name = []
    for ops in rsc_node.findall("operations"):
        matching_name.extend([op for op in ops.iterchildren("op")
                              if op.get("name") == name])
    if interval is None and len(matching_name) == 1:
        return matching_name[0]
    interval = interval or "0"
    for op in matching_name:
        opint = op.get("interval")
        if interval == "non-0" and crm_msec(opint) > 0:
            return op
        if crm_time_cmp(opint, interval) == 0:
            return op
    return None


def get_op_timeout(rsc_node, op, default_timeout):
    interval = (op == "monitor" and "non-0" or "0")
    op_n = find_operation(rsc_node, op == "probe" and "monitor" or op, interval)
    timeout = op_n is not None and op_n.get("timeout") or default_timeout
    return crm_msec(timeout)


def op2list(node):
    pl = []
    action = ""
    for name in list(node.keys()):
        if name == "name":
            action = node.get(name)
        elif name != "id":  # skip the id
            pl.append([name, node.get(name)])
    if not action:
        logger.error("op is invalid (no name)")
    return action, pl


def get_rsc_operations(rsc_node):
    actions = [op2list(op) for op in rsc_node.xpath('.//operations/op')]
    actions = [[op, pl] for op, pl in actions if op]
    return actions


# lower score = earlier sort
def make_sort_map(*order):
    m = {}
    for i, o in enumerate(order):
        if isinstance(o, str):
            m[o] = i
        else:
            for k in o:
                m[k] = i
    return m


_sort_xml_order = make_sort_map('node',
                                'template', 'primitive', 'bundle', 'group', 'master', 'clone', 'op',
                                'tag',
                                ['rsc_location', 'rsc_colocation', 'rsc_order'],
                                ['rsc_ticket', 'fencing-topology'],
                                'cluster_property_set', 'rsc_defaults', 'op_defaults',
                                'acl_role', ['acl_target', 'acl_group', 'acl_user'],
                                'alert')

_sort_cli_order = make_sort_map('node',
                                'rsc_template', 'primitive', 'bundle', 'group',
                                ['ms', 'master'], 'clone', 'op',
                                'tag',
                                ['location', 'colocation', 'collocation', 'order'],
                                ['rsc_ticket', 'fencing_topology'],
                                'property', 'rsc_defaults', 'op_defaults',
                                'role', ['acl_target', 'acl_group', 'user'],
                                'alert')

_SORT_LAST = 1000


def processing_sort(nl):
    '''
    It's usually important to process cib objects in this order,
    i.e. simple objects first.

    TODO: if sort_elements is disabled, only sort to resolve inter-dependencies.
    '''
    def sort_elements(k):
        return _sort_xml_order.get(k.tag, _SORT_LAST)

    def sort_type(k):
        return _sort_xml_order.get(k.tag, _SORT_LAST)

    return sorted(nl, key=sort_elements if config.core.sort_elements else sort_type)


def processing_sort_cli(nl):
    '''
    nl: list of objects (CibObject)
    Returns the given list in order

    TODO: if sort_elements is disabled, only sort to resolve inter-dependencies.
    '''
    def sort_elements(k):
        return _sort_cli_order.get(k.obj_type, _SORT_LAST), k.obj_id

    def sort_type(k):
        return _sort_cli_order.get(k.obj_type, _SORT_LAST)

    return sorted(nl, key=sort_elements if config.core.sort_elements else sort_type)


def is_resource_cli(s):
    return s in olist(constants.resource_cli_names)


def is_constraint_cli(s):
    return s in olist(constants.constraint_cli_names)


def referenced_resources(node):
    if not is_constraint(node):
        return []
    xml_obj_type = node.tag
    rsc_list = []
    if xml_obj_type == "rsc_location" and node.get("rsc"):
        rsc_list = [node.get("rsc")]
    elif node.xpath("resource_set/resource_ref"):
        # resource sets
        rsc_list = [x.get("id")
                    for x in node.xpath("resource_set/resource_ref")]
    elif xml_obj_type == "rsc_colocation":
        rsc_list = [node.get("rsc"), node.get("with-rsc")]
    elif xml_obj_type == "rsc_order":
        rsc_list = [node.get("first"), node.get("then")]
    elif xml_obj_type == "rsc_ticket":
        rsc_list = [node.get("rsc")]
    return [rsc for rsc in rsc_list if rsc is not None]


def rename_id(node, old_id, new_id):
    if node.get("id") == old_id:
        node.set("id", new_id)


def rename_rscref_simple(c_obj, old_id, new_id):
    c_modified = False
    for attr in list(c_obj.node.keys()):
        if attr in constants.constraint_rsc_refs and \
                c_obj.node.get(attr) == old_id:
            c_obj.node.set(attr, new_id)
            c_obj.updated = True
            c_modified = True
    return c_modified


def delete_rscref_simple(c_obj, rsc_id):
    c_modified = False
    for attr in list(c_obj.node.keys()):
        if attr in constants.constraint_rsc_refs and \
                c_obj.node.get(attr) == rsc_id:
            del c_obj.node.attrib[attr]
            c_obj.updated = True
            c_modified = True
    return c_modified


def rset_uniq(c_obj, d):
    '''
    Drop duplicate resource references.
    '''
    l = []
    for rref in c_obj.node.xpath("resource_set/resource_ref"):
        rsc_id = rref.get("id")
        if d[rsc_id] > 1:
            # drop one
            l.append(rref)
            d[rsc_id] -= 1
    rmnodes(l)


def delete_rscref_rset(c_obj, rsc_id):
    '''
    Drop all reference to rsc_id.
    '''
    c_modified = False
    l = []
    for rref in c_obj.node.xpath("resource_set/resource_ref"):
        if rsc_id == rref.get("id"):
            l.append(rref)
            c_obj.updated = True
            c_modified = True
    rmnodes(l)
    l = []
    cnt = 0
    nonseq_rset = False
    for rset in c_obj.node.findall("resource_set"):
        rref_cnt = len(rset.findall("resource_ref"))
        if rref_cnt == 0:
            l.append(rset)
            c_obj.updated = True
            c_modified = True
        elif not get_boolean(rset.get("sequential"), True) and rref_cnt > 1:
            nonseq_rset = True
        cnt += rref_cnt
    rmnodes(l)
    if not nonseq_rset and cnt == 2:
        rset_convert(c_obj)
    return c_modified


def rset_convert(c_obj):
    l = c_obj.node.xpath("resource_set/resource_ref")
    if len(l) != 2:
        return  # eh?
    rsetcnt = 0
    for rset in c_obj.node.findall("resource_set"):
        # in case there are multiple non-sequential sets
        if rset.get("sequential"):
            del rset.attrib["sequential"]
        rsetcnt += 1
    c_obj.modified = True
    cli = c_obj.repr_cli(format_mode=-1)
    cli = cli.replace("_rsc_set_ ", "")
    newnode = c_obj.cli2node(cli)
    if newnode is not None:
        c_obj.node.getparent().replace(c_obj.node, newnode)
        c_obj.node = newnode
        if rsetcnt == 1 and c_obj.obj_type == "colocation":
            # exchange the elements in colocations
            rsc = newnode.get("rsc")
            with_rsc = newnode.get("with-rsc")
            if with_rsc is not None:
                newnode.set("rsc", with_rsc)
            if rsc is not None:
                newnode.set("with-rsc", rsc)


def rename_rscref_rset(c_obj, old_id, new_id):
    c_modified = False
    d = {}
    for rref in c_obj.node.xpath("resource_set/resource_ref"):
        rsc_id = rref.get("id")
        if rsc_id == old_id:
            rref.set("id", new_id)
            rsc_id = new_id
            c_obj.updated = True
            c_modified = True
        if rsc_id not in d:
            d[rsc_id] = 1
        else:
            d[rsc_id] += 1
    rset_uniq(c_obj, d)
    # if only two resource references remained then, to preserve
    # sanity, convert it to a simple constraint (sigh)
    cnt = 0
    for key in d:
        cnt += d[key]
    if cnt == 2:
        rset_convert(c_obj)
    return c_modified


def rename_rscref(c_obj, old_id, new_id):
    if rename_rscref_simple(c_obj, old_id, new_id) or \
            rename_rscref_rset(c_obj, old_id, new_id):
        logger.info("modified %s from %s to %s", str(c_obj), old_id, new_id)


def delete_rscref(c_obj, rsc_id):
    return delete_rscref_simple(c_obj, rsc_id) or \
        delete_rscref_rset(c_obj, rsc_id)


def silly_constraint(c_node, rsc_id):
    '''
    Remove a constraint from rsc_id to rsc_id.
    Or an invalid one.
    '''
    if c_node.xpath("resource_set/resource_ref"):
        # it's a resource set
        # the resource sets have already been uniq-ed
        cnt = len(c_node.xpath("resource_set/resource_ref"))
        if c_node.tag in ("rsc_location", "rsc_ticket"):  # locations and tickets are never silly
            return cnt < 1
        return cnt <= 1
    cnt = 0  # total count of referenced resources have to be at least two
    rsc_cnt = 0
    for attr in list(c_node.keys()):
        if attr in constants.constraint_rsc_refs:
            cnt += 1
            if c_node.get(attr) == rsc_id:
                rsc_cnt += 1
    if c_node.tag in ("rsc_location", "rsc_ticket"):  # locations and tickets are never silly
        return cnt < 1
    else:
        return rsc_cnt == 2 or cnt < 2


def is_climove_location(node):
    'Figure out if the location was created by crm resource move.'
    rule_l = node.findall("rule")
    expr_l = node.xpath(".//expression")
    return len(rule_l) == 1 and len(expr_l) == 1 and \
        node.get("id").startswith("cli-") and \
        expr_l[0].get("attribute") == "#uname" and \
        expr_l[0].get("operation") == "eq"


def is_pref_location(node):
    'Figure out if the location is a node preference.'
    rule_l = node.findall("rule")
    expr_l = node.xpath(".//expression")
    return len(rule_l) == 1 and len(expr_l) == 1 and \
        expr_l[0].get("attribute") == "#uname" and \
        expr_l[0].get("operation") == "eq"


def get_rsc_ref_ids(node):
    return [x.get("id")
            for x in node.xpath("./resource_ref")]


def get_rsc_children_ids(node):
    return [x.get("id")
            for x in node.iterchildren() if is_child_rsc(x)]


def get_prim_children_ids(node):
    l = [x for x in node.iterchildren() if is_child_rsc(x)]
    if len(l) and l[0].tag == "group":
        l = [x for x in l[0].iterchildren() if is_child_rsc(x)]
    return [x.get("id") for x in l]


def get_child_nvset_node(node, attr_set="meta_attributes"):
    if node is None:
        return None
    for c in node.iterchildren():
        if c.tag != attr_set:
            continue
        return c
    return None


def get_rscop_defaults_meta_node(node):
    return get_child_nvset_node(node)


def get_rsc_meta_node(node):
    return get_child_nvset_node(node)


def get_properties_node(node):
    return get_child_nvset_node(node, attr_set="cluster_property_set")


def new_cib():
    cib_elem = etree.Element("cib")
    conf_elem = etree.SubElement(cib_elem, "configuration")
    for name in schema.get('sub', "configuration", 'r'):
        etree.SubElement(conf_elem, name)
    return cib_elem


def get_conf_elems(cib_elem, path):
    '''
    Get a list of configuration elements. All elements are within
    /configuration
    '''
    if cib_elem is None:
        return None
    return cib_elem.xpath("//configuration/%s" % path)


def get_first_conf_elem(cib_elem, path):
    try:
        elems = get_conf_elems(cib_elem, path)
        return elems[0] if elems else None
    except IndexError:
        return None


def get_topnode(cib_elem, tag):
    "Get configuration element or create/append if there's none."
    conf_elem = cib_elem.find("configuration")
    if conf_elem is None:
        logger.error("no configuration element found!")
        return None
    if tag == "configuration":
        return conf_elem
    e = cib_elem.find("configuration/%s" % tag)
    if e is None:
        logger.debug("create configuration section %s", tag)
        e = etree.SubElement(conf_elem, tag)
    return e


def get_attr_in_set(e, attr):
    if e is None:
        return None
    for c in e.iterchildren("nvpair"):
        if c.get("name") == attr:
            return c
    return None


def get_attr_value(e, attr):
    try:
        return get_attr_in_set(e, attr).get("value")
    except:
        return None


def set_attr(e, attr, value):
    '''
    Set an attribute in the attribute set.
    '''
    nvp = get_attr_in_set(e, attr)
    if nvp is None:
        from . import idmgmt
        nvp = etree.SubElement(e, "nvpair", id="", name=attr, value=value)
        nvp.set("id", idmgmt.new(nvp, e.get("id")))
    else:
        nvp.set("name", attr)
        nvp.set("value", value)


def get_set_nodes(e, setname, create=False):
    """Return the attributes set nodes (create one if requested)
    setname can for example be meta_attributes
    """
    l = [c for c in e.iterchildren(setname)]
    if l:
        return l
    if create:
        from . import idmgmt
        elem = etree.SubElement(e, setname, id="")
        elem.set("id", idmgmt.new(elem, e.get("id")))
        l.append(elem)
    return l

def get_set_instace_attributes(e, create=False):
    '''
    Return instance attributes set nodes (create one if requested)
    '''
    l = [c for c in e.iterchildren("instance_attributes")]
    if l:
        return l
    if create:
        from . import idmgmt
        elem = etree.SubElement(e, "instance_attributes", id="")
        elem.set("id", "nodes-"+e.attrib["id"])
        l.append(elem)
    return l


_checker = doctestcompare.LXMLOutputChecker()


def xml_equals_unordered(a, b):
    """
    used by xml_equals to compare xml trees without ordering.
    NOTE: resource_set children SHOULD be compared with ordering.
    """
    def fail(msg):
        logger.debug("%s!=%s: %s", a.tag, b.tag, msg)
        return False

    def tagflat(x):
        return isinstance(x.tag, str) and x.tag or x.text

    def sortby(v):
        if v.tag == 'primitive':
            return v.tag
        return tagflat(v) + ''.join(sorted(list(v.attrib.keys()) + list(v.attrib.values())))

    def safe_strip(text):
        return text is not None and text.strip() or ''

    if a.tag != b.tag:
        return fail("tags differ: %s != %s" % (a.tag, b.tag))
    elif a.attrib != b.attrib:
        return fail("attributes differ: %s != %s" % (a.attrib, b.attrib))
    elif safe_strip(a.text) != safe_strip(b.text):
        return fail("text differ %s != %s" % (repr(a.text), repr(b.text)))
    elif safe_strip(a.tail) != safe_strip(b.tail):
        return fail("tails differ: %s != %s" % (a.tail, b.tail))
    elif len(a) != len(b):
        return fail("number of children differ")
    elif len(a) == 0:
        return True

    # order matters here, but in a strange way:
    # all primitive tags should sort the same..
    if a.tag == 'resource_set':
        return all(xml_equals_unordered(a, b) for a, b in zip(a, b))
    else:
        sorted_children = list(zip(sorted(a, key=sortby), sorted(b, key=sortby)))
        return all(xml_equals_unordered(a, b) for a, b in sorted_children)


def xml_equals(n, m, show=False):
    rc = xml_equals_unordered(n, m)
    if not rc and show and config.core.debug:
        # somewhat strange, but that's how this works
        from doctest import Example
        example = Example("etree.tostring(n)", xml_tostring(n))
        got = xml_tostring(m)
        print(_checker.output_difference(example, got, 0))
    return rc


def xml_tostring(*args, **kwargs):
    """
    Python 2/3 conversion utility:
    etree.tostring returns a bytestring, but
    we need actual Python strings.
    """
    return etree.tostring(*args, **kwargs).decode('utf-8')


def merge_attributes(dnode, snode, tag):
    rc = False
    add_children = []
    for sc in snode.iterchildren(tag):
        dc = lookup_node(sc, dnode, ignore_id=True)
        if dc is not None:
            for a, v in list(sc.items()):
                if a == "id":
                    continue
                if v != dc.get(a):
                    dc.set(a, v)
                    rc = True
        else:
            add_children.append(sc)
            rc = True
    for c in add_children:
        dnode.append(copy.deepcopy(c))
    return rc


def merge_nodes(dnode, snode):
    '''
    Import elements from snode into dnode.
    If an element is attributes set (constants.nvpairs_tags) or
    "operations", then merge attributes in the children.
    Otherwise, replace the whole element. (TBD)
    '''
    rc = False  # any changes done?
    if dnode is None or snode is None:
        return rc
    add_children = []
    for sc in snode.iterchildren():
        dc = lookup_node(sc, dnode, ignore_id=True)
        if dc is None:
            if sc.tag in constants.nvpairs_tags or sc.tag == "operations":
                add_children.append(sc)
                rc = True
        elif dc.tag in constants.nvpairs_tags:
            rc = merge_attributes(dc, sc, "nvpair") or rc
        elif dc.tag == "operations":
            rc = merge_attributes(dc, sc, "op") or rc
    for c in add_children:
        dnode.append(copy.deepcopy(c))
    return rc


def merge_tmpl_into_prim(prim_node, tmpl_node):
    '''
    Create a new primitive element which is a merge of a
    rsc_template and a primitive which references it.
    '''
    dnode = etree.Element(prim_node.tag)
    merge_nodes(dnode, tmpl_node)
    merge_nodes(dnode, prim_node)
    # the resulting node should inherit all primitives attributes
    for a, v in list(prim_node.items()):
        dnode.set(a, v)
    # but class/provider/type are coming from the template
    # savannah#41410: stonith resources do not have the provider
    # attribute
    for a in ("class", "provider", "type"):
        v = tmpl_node.get(a)
        if v is not None:
            dnode.set(a, v)
    return dnode


def check_id_ref(elem, id_ref):
    target = elem.xpath('.//*[@id="%s"]' % (id_ref))
    if len(target) == 0:
        logger.error("Reference not found: %s", id_ref)
    elif len(target) > 1:
        logger.error("Ambiguous reference to %s", id_ref)


def new(tag, **attributes):
    """
    <tag/>
    """
    return etree.Element(tag, **attributes)


def child(parent, tag, **attributes):
    """append new tag to parent.
    Use append() in case parent is a list and not an element.
    """
    e = etree.Element(tag, **attributes)
    parent.append(e)
    return e


def tostring(n):
    return etree.tostring(n, pretty_print=True)


def maybe_set(node, key, value):
    if value:
        node.set(key, value)
    return node


def nvpair(name, value):
    """
    <nvpair name="" value="" />
    """
    value = handle_role_for_ocf_1_1(value, name=name)
    return new("nvpair", name=name, value=value)


def nvpair_id(nvpairid, name, value):
    """
    <nvpair id="" name="" value="" />
    """
    if name is None:
        name = nvpairid
    return new("nvpair", id=nvpairid, name=name, value=value)


def nvpair_ref(idref, name=None):
    """
    <nvpair id-ref=<idref> [name=<name>]/>
    """
    nvp = new("nvpair")
    nvp.set('id-ref', idref)
    if name is not None:
        nvp.set('name', name)
    return nvp


def set_date_expression(expr, tag, values):
    """
    Fill in date_expression tag for date_spec/in_range operations
    expr: <date_expression/>
    values: [nvpair...]
    """
    if set(nvp.get('name') for nvp in values) == set(constants.in_range_attrs):
        for nvp in values:
            expr.set(nvp.get('name'), nvp.get('value'))
        return expr
    subtag = child(expr, tag)
    for nvp in values:
        if nvp.get('name') in constants.in_range_attrs:
            expr.set(nvp.get('name'), nvp.get('value'))
        else:
            subtag.set(nvp.get('name'), nvp.get('value'))
    return expr


def attributes(typename, rules, values, xmlid=None, score=None):
    """
    Represents a set of name-value pairs, tagged with
    a container typename and an optional xml id.
    The container can also hold rule expressions, passed
    in the rules parameter.

    returns an xml object containing the data
    example:
    <instance_attributes id="foo">
    <nvpair name="thing" value="yes"/>
    </instance_attributes>
    """
    e = new(typename)
    if xmlid:
        e.set("id", xmlid)
    if score:
        e.set("score", score)
    for rule in rules:
        e.append(rule)
    for nvp in values:
        e.append(nvp)
    return e


class CrmMonXmlParser(object):
    """
    Class to parse xml output of crm_mon
    """
    def __init__(self, peer=None):
        """
        Init function
        when peer set, parse peer node's results
        """
        self.peer = peer
        self.xml_elem = self._load()

    def _load(self):
        """
        Load xml output of crm_mon
        """
        _, output, _ = sh.cluster_shell().get_rc_stdout_stderr_without_input(self.peer, constants.CRM_MON_XML_OUTPUT)
        return text2elem(output)

    def is_node_online(self, node):
        """
        Check if a node is online
        """
        xpath = f'//node[@name="{node}" and @online="true"]'
        return bool(self.xml_elem.xpath(xpath))

    def get_node_list(self, attr=None):
        """
        Get a list of nodes based on the given attribute
        """
        attr_dict = {
            'standby': '[@standby="true"]',
            'online': '[@standby="false"]'
        }
        xpath_str = f'//node{attr_dict.get(attr, "")}'
        return [e.get('name') for e in self.xml_elem.xpath(xpath_str)]

    def is_resource_configured(self, ra_type):
        """
        Check if the RA is configured
        """
        xpath = f'//resource[@resource_agent="{ra_type}"]'
        return bool(self.xml_elem.xpath(xpath))

    def is_any_resource_running(self):
        """
        Check if any RA is running
        """
        xpath = '//resource[@active="true"]'
        return bool(self.xml_elem.xpath(xpath))

    def is_resource_started(self, ra):
        """
        Check if the RA started(in all clone instances if configured as clone)

        @ra could be resource id or resource type
        """
        xpath = f'//resource[(@id="{ra}" or @resource_agent="{ra}") and @active="true" and @role="Started"]'
        return bool(self.xml_elem.xpath(xpath))

    def get_resource_id_list_via_type(self, ra_type):
        """
        Given configured ra type, get the ra id list
        """
        xpath = f'//resource[@resource_agent="{ra_type}"]'
        return [elem.get('id') for elem in self.xml_elem.xpath(xpath)]
# vim:ts=4:sw=4:et: