summaryrefslogtreecommitdiff
path: root/lib/ansible/modules/network/cloudengine/ce_mlag_interface.py
blob: 5c791ab66932c166eea8dba70e5bdc4f150f25f9 (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
#!/usr/bin/python
#
# 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/>.
#

ANSIBLE_METADATA = {'metadata_version': '1.1',
                    'status': ['preview'],
                    'supported_by': 'community'}

DOCUMENTATION = '''
---
module: ce_mlag_interface
version_added: "2.4"
short_description: Manages MLAG interfaces on HUAWEI CloudEngine switches.
description:
    - Manages MLAG interface attributes on HUAWEI CloudEngine switches.
author:
    - Li Yanfeng (@QijunPan)
options:
    eth_trunk_id:
        description:
            - Name of the local M-LAG interface. The value is ranging from 0 to 511.
    dfs_group_id:
        description:
            - ID of a DFS group.The value is 1.
        default: present
    mlag_id:
        description:
            - ID of the M-LAG. The value is an integer that ranges from 1 to 2048.
    mlag_system_id:
        description:
            - M-LAG global LACP system MAC address. The value is a string of 0 to 255 characters. The default value
              is the MAC address of the Ethernet port of MPU.
    mlag_priority_id:
        description:
            - M-LAG global LACP system priority. The value is an integer ranging from 0 to 65535.
              The default value is 32768.
    interface:
        description:
            - Name of the interface that enters the Error-Down state when the peer-link fails.
              The value is a string of 1 to 63 characters.
    mlag_error_down:
        description:
            - Configure the interface on the slave device to enter the Error-Down state.
        choices: ['enable','disable']
    state:
        description:
            - Specify desired state of the resource.
        default: present
        choices: ['present','absent']

'''

EXAMPLES = '''
- name: mlag interface module test
  hosts: cloudengine
  connection: local
  gather_facts: no
  vars:
    cli:
      host: "{{ inventory_hostname }}"
      port: "{{ ansible_ssh_port }}"
      username: "{{ username }}"
      password: "{{ password }}"
      transport: cli

  tasks:

  - name: Set interface mlag error down
    ce_mlag_interface:
      interface: 10GE2/0/1
      mlag_error_down: enable
      provider: "{{ cli }}"
  - name: Create mlag
    ce_mlag_interface:
      eth_trunk_id: 1
      dfs_group_id: 1
      mlag_id: 4
      provider: "{{ cli }}"
  - name: Set mlag global attribute
    ce_mlag_interface:
      mlag_system_id: 0020-1409-0407
      mlag_priority_id: 5
      provider: "{{ cli }}"
  - name: Set mlag interface attribute
    ce_mlag_interface:
      eth_trunk_id: 1
      mlag_system_id: 0020-1409-0400
      mlag_priority_id: 3
      provider: "{{ cli }}"
'''

RETURN = '''
changed:
    description: check to see if a change was made on the device
    returned: always
    type: bool
    sample: true
proposed:
    description: k/v pairs of parameters passed into module
    returned: always
    type: dict
    sample: { "interface": "eth-trunk1",
              "mlag_error_down": "disable",
              "state": "present"
            }
existing:
    description: k/v pairs of existing aaa server
    returned: always
    type: dict
    sample: {   "mlagErrorDownInfos": [
                {
                    "dfsgroupId": "1",
                    "portName": "Eth-Trunk1"
                }
              ]
            }
end_state:
    description: k/v pairs of aaa params after module execution
    returned: always
    type: dict
    sample: {}
updates:
    description: command sent to the device
    returned: always
    type: list
    sample: { "interface eth-trunk1",
              "undo m-lag unpaired-port suspend"}
'''

import re
from xml.etree import ElementTree
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.network.cloudengine.ce import load_config
from ansible.module_utils.network.cloudengine.ce import get_nc_config, set_nc_config, ce_argument_spec

CE_NC_GET_MLAG_INFO = """
<filter type="subtree">
<mlag xmlns="http://www.huawei.com/netconf/vrp" content-version="1.0" format-version="1.0">
  <mlagInstances>
    <mlagInstance>
    </mlagInstance>
  </mlagInstances>
</mlag>
</filter>
"""

CE_NC_CREATE_MLAG_INFO = """
<config>
<mlag xmlns="http://www.huawei.com/netconf/vrp" content-version="1.0" format-version="1.0">
  <mlagInstances>
    <mlagInstance operation="create">
      <dfsgroupId>%s</dfsgroupId>
      <mlagId>%s</mlagId>
      <localMlagPort>%s</localMlagPort>
    </mlagInstance>
  </mlagInstances>
</mlag>
</config>
"""

CE_NC_DELETE_MLAG_INFO = """
<config>
<mlag xmlns="http://www.huawei.com/netconf/vrp" content-version="1.0" format-version="1.0">
  <mlagInstances>
    <mlagInstance operation="delete">
      <dfsgroupId>%s</dfsgroupId>
      <mlagId>%s</mlagId>
      <localMlagPort>%s</localMlagPort>
    </mlagInstance>
  </mlagInstances>
</mlag>
</config>
"""

CE_NC_GET_LACP_MLAG_INFO = """
<filter type="subtree">
  <ifmtrunk xmlns="http://www.huawei.com/netconf/vrp" content-version="1.0" format-version="1.0">
    <TrunkIfs>
      <TrunkIf>
        <ifName>%s</ifName>
        <lacpMlagIf>
          <lacpMlagSysId></lacpMlagSysId>
          <lacpMlagPriority></lacpMlagPriority>
        </lacpMlagIf>
      </TrunkIf>
    </TrunkIfs>
  </ifmtrunk>
</filter>
"""

CE_NC_SET_LACP_MLAG_INFO_HEAD = """
<config>
  <ifmtrunk xmlns="http://www.huawei.com/netconf/vrp" content-version="1.0" format-version="1.0">
    <TrunkIfs>
      <TrunkIf>
        <ifName>%s</ifName>
        <lacpMlagIf operation="merge">
"""

CE_NC_SET_LACP_MLAG_INFO_TAIL = """
        </lacpMlagIf>
      </TrunkIf>
    </TrunkIfs>
  </ifmtrunk>
</config>
"""

CE_NC_GET_GLOBAL_LACP_MLAG_INFO = """
<filter type="subtree">
  <ifmtrunk xmlns="http://www.huawei.com/netconf/vrp" content-version="1.0" format-version="1.0">
    <lacpSysInfo>
      <lacpMlagGlobal>
        <lacpMlagSysId></lacpMlagSysId>
        <lacpMlagPriority></lacpMlagPriority>
      </lacpMlagGlobal>
    </lacpSysInfo>
  </ifmtrunk>
</filter>
"""

CE_NC_SET_GLOBAL_LACP_MLAG_INFO_HEAD = """
<config>
  <ifmtrunk xmlns="http://www.huawei.com/netconf/vrp" content-version="1.0" format-version="1.0">
    <lacpSysInfo>
      <lacpMlagGlobal operation="merge">
"""

CE_NC_SET_GLOBAL_LACP_MLAG_INFO_TAIL = """
      </lacpMlagGlobal>
    </lacpSysInfo>
  </ifmtrunk>
</config>
"""

CE_NC_GET_MLAG_ERROR_DOWN_INFO = """
<filter type="subtree">
<mlag xmlns="http://www.huawei.com/netconf/vrp" content-version="1.0" format-version="1.0">
  <errordowns>
    <errordown>
      <dfsgroupId></dfsgroupId>
      <portName></portName>
      <portState></portState>
    </errordown>
  </errordowns>
</mlag>
</filter>

"""

CE_NC_CREATE_MLAG_ERROR_DOWN_INFO = """
<config>
<mlag xmlns="http://www.huawei.com/netconf/vrp" content-version="1.0" format-version="1.0">
  <errordowns>
    <errordown operation="create">
      <dfsgroupId>1</dfsgroupId>
      <portName>%s</portName>
    </errordown>
  </errordowns>
</mlag>
</config>
"""

CE_NC_DELETE_MLAG_ERROR_DOWN_INFO = """
<config>
<mlag xmlns="http://www.huawei.com/netconf/vrp" content-version="1.0" format-version="1.0">
  <errordowns>
    <errordown operation="delete">
      <dfsgroupId>1</dfsgroupId>
      <portName>%s</portName>
    </errordown>
  </errordowns>
</mlag>
</config>

"""


def get_interface_type(interface):
    """Gets the type of interface, such as 10GE, ETH-TRUNK, VLANIF..."""

    if interface is None:
        return None

    iftype = None

    if interface.upper().startswith('GE'):
        iftype = 'ge'
    elif interface.upper().startswith('10GE'):
        iftype = '10ge'
    elif interface.upper().startswith('25GE'):
        iftype = '25ge'
    elif interface.upper().startswith('40GE'):
        iftype = '40ge'
    elif interface.upper().startswith('100GE'):
        iftype = '100ge'
    elif interface.upper().startswith('ETH-TRUNK'):
        iftype = 'eth-trunk'
    elif interface.upper().startswith('NULL'):
        iftype = 'null'
    else:
        return None

    return iftype.lower()


class MlagInterface(object):
    """
    Manages Manages MLAG interface information.
    """

    def __init__(self, argument_spec):
        self.spec = argument_spec
        self.module = None
        self.init_module()

        # module input info
        self.eth_trunk_id = self.module.params['eth_trunk_id']
        self.dfs_group_id = self.module.params['dfs_group_id']
        self.mlag_id = self.module.params['mlag_id']
        self.mlag_system_id = self.module.params['mlag_system_id']
        self.mlag_priority_id = self.module.params['mlag_priority_id']
        self.interface = self.module.params['interface']
        self.mlag_error_down = self.module.params['mlag_error_down']
        self.state = self.module.params['state']

        # state
        self.changed = False
        self.updates_cmd = list()
        self.results = dict()
        self.existing = dict()
        self.proposed = dict()
        self.end_state = dict()

        # mlag info
        self.commands = list()
        self.mlag_info = None
        self.mlag_global_info = None
        self.mlag_error_down_info = None
        self.mlag_trunk_attribute_info = None

    def init_module(self):
        """ init module """

        self.module = AnsibleModule(
            argument_spec=self.spec, supports_check_mode=True)

    def check_response(self, xml_str, xml_name):
        """Check if response message is already succeed."""

        if "<ok/>" not in xml_str:
            self.module.fail_json(msg='Error: %s failed.' % xml_name)

    def cli_add_command(self, command, undo=False):
        """add command to self.update_cmd and self.commands"""

        if undo and command.lower() not in ["quit", "return"]:
            cmd = "undo " + command
        else:
            cmd = command

        self.commands.append(cmd)          # set to device
        if command.lower() not in ["quit", "return"]:
            self.updates_cmd.append(cmd)   # show updates result

    def cli_load_config(self, commands):
        """load config by cli"""

        if not self.module.check_mode:
            load_config(self.module, commands)

    def get_mlag_info(self):
        """ get mlag info."""

        mlag_info = dict()
        conf_str = CE_NC_GET_MLAG_INFO
        xml_str = get_nc_config(self.module, conf_str)
        if "<data/>" in xml_str:
            return mlag_info
        else:
            xml_str = xml_str.replace('\r', '').replace('\n', '').\
                replace('xmlns="urn:ietf:params:xml:ns:netconf:base:1.0"', "").\
                replace('xmlns="http://www.huawei.com/netconf/vrp"', "")

            mlag_info["mlagInfos"] = list()
            root = ElementTree.fromstring(xml_str)
            dfs_mlag_infos = root.findall(
                "data/mlag/mlagInstances/mlagInstance")

            if dfs_mlag_infos:
                for dfs_mlag_info in dfs_mlag_infos:
                    mlag_dict = dict()
                    for ele in dfs_mlag_info:
                        if ele.tag in ["dfsgroupId", "mlagId", "localMlagPort"]:
                            mlag_dict[ele.tag] = ele.text
                    mlag_info["mlagInfos"].append(mlag_dict)
            return mlag_info

    def get_mlag_global_info(self):
        """ get mlag global info."""

        mlag_global_info = dict()
        conf_str = CE_NC_GET_GLOBAL_LACP_MLAG_INFO
        xml_str = get_nc_config(self.module, conf_str)
        if "<data/>" in xml_str:
            return mlag_global_info
        else:
            xml_str = xml_str.replace('\r', '').replace('\n', '').\
                replace('xmlns="urn:ietf:params:xml:ns:netconf:base:1.0"', "").\
                replace('xmlns="http://www.huawei.com/netconf/vrp"', "")

            root = ElementTree.fromstring(xml_str)
            global_info = root.findall(
                "data/ifmtrunk/lacpSysInfo/lacpMlagGlobal")

            if global_info:
                for tmp in global_info:
                    for site in tmp:
                        if site.tag in ["lacpMlagSysId", "lacpMlagPriority"]:
                            mlag_global_info[site.tag] = site.text
            return mlag_global_info

    def get_mlag_trunk_attribute_info(self):
        """ get mlag global info."""

        mlag_trunk_attribute_info = dict()
        eth_trunk = "Eth-Trunk"
        eth_trunk += self.eth_trunk_id
        conf_str = CE_NC_GET_LACP_MLAG_INFO % eth_trunk
        xml_str = get_nc_config(self.module, conf_str)
        if "<data/>" in xml_str:
            return mlag_trunk_attribute_info
        else:
            xml_str = xml_str.replace('\r', '').replace('\n', '').\
                replace('xmlns="urn:ietf:params:xml:ns:netconf:base:1.0"', "").\
                replace('xmlns="http://www.huawei.com/netconf/vrp"', "")

            root = ElementTree.fromstring(xml_str)
            global_info = root.findall(
                "data/ifmtrunk/TrunkIfs/TrunkIf/lacpMlagIf")

            if global_info:
                for tmp in global_info:
                    for site in tmp:
                        if site.tag in ["lacpMlagSysId", "lacpMlagPriority"]:
                            mlag_trunk_attribute_info[site.tag] = site.text
            return mlag_trunk_attribute_info

    def get_mlag_error_down_info(self):
        """ get error down info."""

        mlag_error_down_info = dict()
        conf_str = CE_NC_GET_MLAG_ERROR_DOWN_INFO
        xml_str = get_nc_config(self.module, conf_str)
        if "<data/>" in xml_str:
            return mlag_error_down_info
        else:
            xml_str = xml_str.replace('\r', '').replace('\n', '').\
                replace('xmlns="urn:ietf:params:xml:ns:netconf:base:1.0"', "").\
                replace('xmlns="http://www.huawei.com/netconf/vrp"', "")

            mlag_error_down_info["mlagErrorDownInfos"] = list()
            root = ElementTree.fromstring(xml_str)
            mlag_error_infos = root.findall(
                "data/mlag/errordowns/errordown")

            if mlag_error_infos:
                for mlag_error_info in mlag_error_infos:
                    mlag_error_dict = dict()
                    for ele in mlag_error_info:
                        if ele.tag in ["dfsgroupId", "portName"]:
                            mlag_error_dict[ele.tag] = ele.text
                    mlag_error_down_info[
                        "mlagErrorDownInfos"].append(mlag_error_dict)
            return mlag_error_down_info

    def check_macaddr(self):
        """check mac-address whether valid"""

        valid_char = '0123456789abcdef-'
        mac = self.mlag_system_id

        if len(mac) > 16:
            return False

        mac_list = re.findall(r'([0-9a-fA-F]+)', mac)
        if len(mac_list) != 3:
            return False

        if mac.count('-') != 2:
            return False

        for _, value in enumerate(mac, start=0):
            if value.lower() not in valid_char:
                return False

        return True

    def check_params(self):
        """Check all input params"""

        # eth_trunk_id check
        if self.eth_trunk_id:
            if not self.eth_trunk_id.isdigit():
                self.module.fail_json(
                    msg='Error: The value of eth_trunk_id is an integer.')
            if int(self.eth_trunk_id) < 0 or int(self.eth_trunk_id) > 511:
                self.module.fail_json(
                    msg='Error: The value of eth_trunk_id is not in the range from 0 to 511.')

        # dfs_group_id check
        if self.dfs_group_id:
            if self.dfs_group_id != "1":
                self.module.fail_json(
                    msg='Error: The value of dfs_group_id must be 1.')

        # mlag_id check
        if self.mlag_id:
            if not self.mlag_id.isdigit():
                self.module.fail_json(
                    msg='Error: The value of mlag_id is an integer.')
            if int(self.mlag_id) < 1 or int(self.mlag_id) > 2048:
                self.module.fail_json(
                    msg='Error: The value of mlag_id is not in the range from 1 to 2048.')

        # mlag_system_id check
        if self.mlag_system_id:
            if not self.check_macaddr():
                self.module.fail_json(
                    msg="Error: mlag_system_id has invalid value %s." % self.mlag_system_id)

        # mlag_priority_id check
        if self.mlag_priority_id:
            if not self.mlag_priority_id.isdigit():
                self.module.fail_json(
                    msg='Error: The value of mlag_priority_id is an integer.')
            if int(self.mlag_priority_id) < 0 or int(self.mlag_priority_id) > 254:
                self.module.fail_json(
                    msg='Error: The value of mlag_priority_id is not in the range from 0 to 254.')

        # interface check
        if self.interface:
            intf_type = get_interface_type(self.interface)
            if not intf_type:
                self.module.fail_json(
                    msg='Error: Interface name of %s '
                        'is error.' % self.interface)

    def is_mlag_info_change(self):
        """whether mlag info change"""

        if not self.mlag_info:
            return True

        eth_trunk = "Eth-Trunk"
        eth_trunk += self.eth_trunk_id
        for info in self.mlag_info["mlagInfos"]:
            if info["mlagId"] == self.mlag_id and info["localMlagPort"] == eth_trunk:
                return False
        return True

    def is_mlag_info_exist(self):
        """whether mlag info exist"""

        if not self.mlag_info:
            return False

        eth_trunk = "Eth-Trunk"
        eth_trunk += self.eth_trunk_id

        for info in self.mlag_info["mlagInfos"]:
            if info["mlagId"] == self.mlag_id and info["localMlagPort"] == eth_trunk:
                return True
        return False

    def is_mlag_error_down_info_change(self):
        """whether mlag error down info change"""

        if not self.mlag_error_down_info:
            return True

        for info in self.mlag_error_down_info["mlagErrorDownInfos"]:
            if info["portName"].upper() == self.interface.upper():
                return False
        return True

    def is_mlag_error_down_info_exist(self):
        """whether mlag error down info exist"""

        if not self.mlag_error_down_info:
            return False

        for info in self.mlag_error_down_info["mlagErrorDownInfos"]:
            if info["portName"].upper() == self.interface.upper():
                return True
        return False

    def is_mlag_interface_info_change(self):
        """whether mlag interface attribute info change"""

        if not self.mlag_trunk_attribute_info:
            return True

        if self.mlag_system_id:
            if self.mlag_trunk_attribute_info["lacpMlagSysId"] != self.mlag_system_id:
                return True
        if self.mlag_priority_id:
            if self.mlag_trunk_attribute_info["lacpMlagPriority"] != self.mlag_priority_id:
                return True
        return False

    def is_mlag_interface_info_exist(self):
        """whether mlag interface attribute info exist"""

        if not self.mlag_trunk_attribute_info:
            return False

        if self.mlag_system_id:
            if self.mlag_priority_id:
                if self.mlag_trunk_attribute_info["lacpMlagSysId"] == self.mlag_system_id \
                        and self.mlag_trunk_attribute_info["lacpMlagPriority"] == self.mlag_priority_id:
                    return True
            else:
                if self.mlag_trunk_attribute_info["lacpMlagSysId"] == self.mlag_system_id:
                    return True

        if self.mlag_priority_id:
            if self.mlag_system_id:
                if self.mlag_trunk_attribute_info["lacpMlagSysId"] == self.mlag_system_id \
                        and self.mlag_trunk_attribute_info["lacpMlagPriority"] == self.mlag_priority_id:
                    return True
            else:
                if self.mlag_trunk_attribute_info["lacpMlagPriority"] == self.mlag_priority_id:
                    return True

        return False

    def is_mlag_global_info_change(self):
        """whether mlag global attribute info change"""

        if not self.mlag_global_info:
            return True

        if self.mlag_system_id:
            if self.mlag_global_info["lacpMlagSysId"] != self.mlag_system_id:
                return True
        if self.mlag_priority_id:
            if self.mlag_global_info["lacpMlagPriority"] != self.mlag_priority_id:
                return True
        return False

    def is_mlag_global_info_exist(self):
        """whether mlag global attribute info exist"""

        if not self.mlag_global_info:
            return False

        if self.mlag_system_id:
            if self.mlag_priority_id:
                if self.mlag_global_info["lacpMlagSysId"] == self.mlag_system_id \
                        and self.mlag_global_info["lacpMlagPriority"] == self.mlag_priority_id:
                    return True
            else:
                if self.mlag_global_info["lacpMlagSysId"] == self.mlag_system_id:
                    return True

        if self.mlag_priority_id:
            if self.mlag_system_id:
                if self.mlag_global_info["lacpMlagSysId"] == self.mlag_system_id \
                        and self.mlag_global_info["lacpMlagPriority"] == self.mlag_priority_id:
                    return True
            else:
                if self.mlag_global_info["lacpMlagPriority"] == self.mlag_priority_id:
                    return True

        return False

    def create_mlag(self):
        """create mlag info"""

        if self.is_mlag_info_change():
            mlag_port = "Eth-Trunk"
            mlag_port += self.eth_trunk_id
            conf_str = CE_NC_CREATE_MLAG_INFO % (
                self.dfs_group_id, self.mlag_id, mlag_port)
            recv_xml = set_nc_config(self.module, conf_str)
            if "<ok/>" not in recv_xml:
                self.module.fail_json(
                    msg='Error: create mlag info failed.')

            self.updates_cmd.append("interface %s" % mlag_port)
            self.updates_cmd.append("dfs-group %s m-lag %s" %
                                    (self.dfs_group_id, self.mlag_id))
            self.changed = True

    def delete_mlag(self):
        """delete mlag info"""

        if self.is_mlag_info_exist():
            mlag_port = "Eth-Trunk"
            mlag_port += self.eth_trunk_id
            conf_str = CE_NC_DELETE_MLAG_INFO % (
                self.dfs_group_id, self.mlag_id, mlag_port)
            recv_xml = set_nc_config(self.module, conf_str)
            if "<ok/>" not in recv_xml:
                self.module.fail_json(
                    msg='Error: delete mlag info failed.')

            self.updates_cmd.append("interface %s" % mlag_port)
            self.updates_cmd.append(
                "undo dfs-group %s m-lag %s" % (self.dfs_group_id, self.mlag_id))
            self.changed = True

    def create_mlag_error_down(self):
        """create mlag error down info"""

        if self.is_mlag_error_down_info_change():
            conf_str = CE_NC_CREATE_MLAG_ERROR_DOWN_INFO % self.interface
            recv_xml = set_nc_config(self.module, conf_str)
            if "<ok/>" not in recv_xml:
                self.module.fail_json(
                    msg='Error: create mlag error down info failed.')

            self.updates_cmd.append("interface %s" % self.interface)
            self.updates_cmd.append("m-lag unpaired-port suspend")
            self.changed = True

    def delete_mlag_error_down(self):
        """delete mlag error down info"""

        if self.is_mlag_error_down_info_exist():

            conf_str = CE_NC_DELETE_MLAG_ERROR_DOWN_INFO % self.interface
            recv_xml = set_nc_config(self.module, conf_str)
            if "<ok/>" not in recv_xml:
                self.module.fail_json(
                    msg='Error: delete mlag error down info failed.')

            self.updates_cmd.append("interface %s" % self.interface)
            self.updates_cmd.append("undo m-lag unpaired-port suspend")
            self.changed = True

    def set_mlag_interface(self):
        """set mlag interface attribute info"""

        if self.is_mlag_interface_info_change():
            mlag_port = "Eth-Trunk"
            mlag_port += self.eth_trunk_id
            conf_str = CE_NC_SET_LACP_MLAG_INFO_HEAD % mlag_port
            if self.mlag_priority_id:
                conf_str += "<lacpMlagPriority>%s</lacpMlagPriority>" % self.mlag_priority_id
            if self.mlag_system_id:
                conf_str += "<lacpMlagSysId>%s</lacpMlagSysId>" % self.mlag_system_id
            conf_str += CE_NC_SET_LACP_MLAG_INFO_TAIL
            recv_xml = set_nc_config(self.module, conf_str)
            if "<ok/>" not in recv_xml:
                self.module.fail_json(
                    msg='Error: set mlag interface attribute info failed.')

            self.updates_cmd.append("interface %s" % mlag_port)
            if self.mlag_priority_id:
                self.updates_cmd.append(
                    "lacp m-lag priority %s" % self.mlag_priority_id)

            if self.mlag_system_id:
                self.updates_cmd.append(
                    "lacp m-lag system-id %s" % self.mlag_system_id)
            self.changed = True

    def delete_mlag_interface(self):
        """delete mlag interface attribute info"""

        if self.is_mlag_interface_info_exist():
            mlag_port = "Eth-Trunk"
            mlag_port += self.eth_trunk_id

            cmd = "interface %s" % mlag_port
            self.cli_add_command(cmd)

            if self.mlag_priority_id:
                cmd = "lacp m-lag priority %s" % self.mlag_priority_id
                self.cli_add_command(cmd, True)

            if self.mlag_system_id:
                cmd = "lacp m-lag system-id %s" % self.mlag_system_id
                self.cli_add_command(cmd, True)

            if self.commands:
                self.cli_load_config(self.commands)
                self.changed = True

    def set_mlag_global(self):
        """set mlag global attribute info"""

        if self.is_mlag_global_info_change():
            conf_str = CE_NC_SET_GLOBAL_LACP_MLAG_INFO_HEAD
            if self.mlag_priority_id:
                conf_str += "<lacpMlagPriority>%s</lacpMlagPriority>" % self.mlag_priority_id
            if self.mlag_system_id:
                conf_str += "<lacpMlagSysId>%s</lacpMlagSysId>" % self.mlag_system_id
            conf_str += CE_NC_SET_GLOBAL_LACP_MLAG_INFO_TAIL
            recv_xml = set_nc_config(self.module, conf_str)
            if "<ok/>" not in recv_xml:
                self.module.fail_json(
                    msg='Error: set mlag interface attribute info failed.')

            if self.mlag_priority_id:
                self.updates_cmd.append(
                    "lacp m-lag priority %s" % self.mlag_priority_id)

            if self.mlag_system_id:
                self.updates_cmd.append(
                    "lacp m-lag system-id %s" % self.mlag_system_id)
            self.changed = True

    def delete_mlag_global(self):
        """delete mlag global attribute info"""

        if self.is_mlag_global_info_exist():
            if self.mlag_priority_id:
                cmd = "lacp m-lag priority %s" % self.mlag_priority_id
                self.cli_add_command(cmd, True)

            if self.mlag_system_id:
                cmd = "lacp m-lag system-id %s" % self.mlag_system_id
                self.cli_add_command(cmd, True)

            if self.commands:
                self.cli_load_config(self.commands)
                self.changed = True

    def get_proposed(self):
        """get proposed info"""

        if self.eth_trunk_id:
            self.proposed["eth_trunk_id"] = self.eth_trunk_id
        if self.dfs_group_id:
            self.proposed["dfs_group_id"] = self.dfs_group_id
        if self.mlag_id:
            self.proposed["mlag_id"] = self.mlag_id
        if self.mlag_system_id:
            self.proposed["mlag_system_id"] = self.mlag_system_id
        if self.mlag_priority_id:
            self.proposed["mlag_priority_id"] = self.mlag_priority_id
        if self.interface:
            self.proposed["interface"] = self.interface
        if self.mlag_error_down:
            self.proposed["mlag_error_down"] = self.mlag_error_down
        if self.state:
            self.proposed["state"] = self.state

    def get_existing(self):
        """get existing info"""

        self.mlag_info = self.get_mlag_info()
        self.mlag_global_info = self.get_mlag_global_info()
        self.mlag_error_down_info = self.get_mlag_error_down_info()

        if self.eth_trunk_id or self.dfs_group_id or self.mlag_id:
            if not self.mlag_system_id and not self.mlag_priority_id:
                if self.mlag_info:
                    self.existing["mlagInfos"] = self.mlag_info["mlagInfos"]

        if self.mlag_system_id or self.mlag_priority_id:
            if self.eth_trunk_id:
                if self.mlag_trunk_attribute_info:
                    if self.mlag_system_id:
                        self.end_state["lacpMlagSysId"] = self.mlag_trunk_attribute_info[
                            "lacpMlagSysId"]
                    if self.mlag_priority_id:
                        self.end_state["lacpMlagPriority"] = self.mlag_trunk_attribute_info[
                            "lacpMlagPriority"]
            else:
                if self.mlag_global_info:
                    if self.mlag_system_id:
                        self.end_state["lacpMlagSysId"] = self.mlag_global_info[
                            "lacpMlagSysId"]
                    if self.mlag_priority_id:
                        self.end_state["lacpMlagPriority"] = self.mlag_global_info[
                            "lacpMlagPriority"]

        if self.interface or self.mlag_error_down:
            if self.mlag_error_down_info:
                self.existing["mlagErrorDownInfos"] = self.mlag_error_down_info[
                    "mlagErrorDownInfos"]

    def get_end_state(self):
        """get end state info"""

        if self.eth_trunk_id or self.dfs_group_id or self.mlag_id:
            self.mlag_info = self.get_mlag_info()
            if not self.mlag_system_id and not self.mlag_priority_id:
                if self.mlag_info:
                    self.end_state["mlagInfos"] = self.mlag_info["mlagInfos"]

        if self.mlag_system_id or self.mlag_priority_id:
            if self.eth_trunk_id:
                self.mlag_trunk_attribute_info = self.get_mlag_trunk_attribute_info()
                if self.mlag_trunk_attribute_info:
                    if self.mlag_system_id:
                        self.end_state["lacpMlagSysId"] = self.mlag_trunk_attribute_info[
                            "lacpMlagSysId"]
                    if self.mlag_priority_id:
                        self.end_state["lacpMlagPriority"] = self.mlag_trunk_attribute_info[
                            "lacpMlagPriority"]
            else:
                self.mlag_global_info = self.get_mlag_global_info()
                if self.mlag_global_info:
                    if self.mlag_system_id:
                        self.end_state["lacpMlagSysId"] = self.mlag_global_info[
                            "lacpMlagSysId"]
                    if self.mlag_priority_id:
                        self.end_state["lacpMlagPriority"] = self.mlag_global_info[
                            "lacpMlagPriority"]

        if self.interface or self.mlag_error_down:
            self.mlag_error_down_info = self.get_mlag_error_down_info()
            if self.mlag_error_down_info:
                self.end_state["mlagErrorDownInfos"] = self.mlag_error_down_info[
                    "mlagErrorDownInfos"]

    def work(self):
        """worker"""

        self.check_params()
        self.get_proposed()
        self.get_existing()

        if self.eth_trunk_id or self.dfs_group_id or self.mlag_id:
            self.mlag_info = self.get_mlag_info()
            if self.eth_trunk_id and self.dfs_group_id and self.mlag_id:
                if self.state == "present":
                    self.create_mlag()
                else:
                    self.delete_mlag()
            else:
                if not self.mlag_system_id and not self.mlag_priority_id:
                    self.module.fail_json(
                        msg='Error: eth_trunk_id, dfs_group_id, mlag_id must be config at the same time.')

        if self.mlag_system_id or self.mlag_priority_id:

            if self.eth_trunk_id:
                self.mlag_trunk_attribute_info = self.get_mlag_trunk_attribute_info()
                if self.mlag_system_id or self.mlag_priority_id:
                    if self.state == "present":
                        self.set_mlag_interface()
                    else:
                        self.delete_mlag_interface()
            else:
                self.mlag_global_info = self.get_mlag_global_info()
                if self.mlag_system_id or self.mlag_priority_id:
                    if self.state == "present":
                        self.set_mlag_global()
                    else:
                        self.delete_mlag_global()

        if self.interface or self.mlag_error_down:
            self.mlag_error_down_info = self.get_mlag_error_down_info()
            if self.interface and self.mlag_error_down:
                if self.mlag_error_down == "enable":
                    self.create_mlag_error_down()
                else:
                    self.delete_mlag_error_down()
            else:
                self.module.fail_json(
                    msg='Error: interface, mlag_error_down must be config at the same time.')

        self.get_end_state()
        self.results['changed'] = self.changed
        self.results['proposed'] = self.proposed
        self.results['existing'] = self.existing
        self.results['end_state'] = self.end_state
        if self.changed:
            self.results['updates'] = self.updates_cmd
        else:
            self.results['updates'] = list()

        self.module.exit_json(**self.results)


def main():
    """ Module main """

    argument_spec = dict(
        eth_trunk_id=dict(type='str'),
        dfs_group_id=dict(type='str'),
        mlag_id=dict(type='str'),
        mlag_system_id=dict(type='str'),
        mlag_priority_id=dict(type='str'),
        interface=dict(type='str'),
        mlag_error_down=dict(type='str', choices=['enable', 'disable']),
        state=dict(type='str', default='present',
                   choices=['present', 'absent'])
    )
    argument_spec.update(ce_argument_spec)
    module = MlagInterface(argument_spec=argument_spec)
    module.work()


if __name__ == '__main__':
    main()