summaryrefslogtreecommitdiffstats
path: root/ipalib/plugins/topology.py
blob: 2723ce1213df2c94fd1445cfe7595d35806028d9 (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
#
# Copyright (C) 2015  FreeIPA Contributors see COPYING for license
#

from ipalib import api, errors
from ipalib import Int, Str, Bool, StrEnum, Flag
from ipalib.plugable import Registry
from ipalib.plugins.baseldap import (
    LDAPObject, LDAPSearch, LDAPCreate, LDAPDelete, LDAPUpdate, LDAPQuery,
    LDAPRetrieve)
from ipalib import _, ngettext
from ipalib import output
from ipalib.util import create_topology_graph, get_topology_connection_errors
from ipapython.dn import DN


__doc__ = _("""
Topology

Management of a replication topology.

Requires minimum domain level 1.
""")

register = Registry()

MINIMUM_DOMAIN_LEVEL = 1


def validate_domain_level(api):
    current = int(api.Command.domainlevel_get()['result'])
    if current < MINIMUM_DOMAIN_LEVEL:
        raise errors.InvalidDomainLevelError(
            reason=_('Topology management requires minimum domain level {0} '
                   .format(MINIMUM_DOMAIN_LEVEL))
        )


@register()
class topologysegment(LDAPObject):
    """
    Topology segment.
    """
    parent_object = 'topologysuffix'
    container_dn = api.env.container_topology
    object_name = _('segment')
    object_name_plural = _('segments')
    object_class = ['iparepltoposegment']
    default_attributes = [
        'cn',
        'ipaReplTopoSegmentdirection', 'ipaReplTopoSegmentrightNode',
        'ipaReplTopoSegmentLeftNode', 'nsds5replicastripattrs',
        'nsds5replicatedattributelist', 'nsds5replicatedattributelisttotal',
        'nsds5replicatimeout', 'nsds5replicaenabled'
    ]
    search_display_attributes = [
        'cn', 'ipaReplTopoSegmentdirection', 'ipaReplTopoSegmentrightNode',
        'ipaReplTopoSegmentLeftNode'
    ]

    label = _('Topology Segments')
    label_singular = _('Topology Segment')

    takes_params = (
        Str(
            'cn',
            maxlength=255,
            cli_name='name',
            primary_key=True,
            label=_('Segment name'),
            default_from=lambda iparepltoposegmentleftnode, iparepltoposegmentrightnode:
                         '%s-to-%s' % (iparepltoposegmentleftnode, iparepltoposegmentrightnode),
            normalizer=lambda value: value.lower(),
            doc=_('Arbitrary string identifying the segment'),
        ),
        Str(
            'iparepltoposegmentleftnode',
            pattern='^[a-zA-Z0-9.][a-zA-Z0-9.-]{0,252}[a-zA-Z0-9.$-]?$',
            pattern_errmsg='may only include letters, numbers, -, . and $',
            maxlength=255,
            cli_name='leftnode',
            label=_('Left node'),
            normalizer=lambda value: value.lower(),
            doc=_('Left replication node - an IPA server'),
            flags={'no_update'},
        ),
        Str(
            'iparepltoposegmentrightnode',
            pattern='^[a-zA-Z0-9.][a-zA-Z0-9.-]{0,252}[a-zA-Z0-9.$-]?$',
            pattern_errmsg='may only include letters, numbers, -, . and $',
            maxlength=255,
            cli_name='rightnode',
            label=_('Right node'),
            normalizer=lambda value: value.lower(),
            doc=_('Right replication node - an IPA server'),
            flags={'no_update'},
        ),
        StrEnum(
            'iparepltoposegmentdirection',
            cli_name='direction',
            label=_('Connectivity'),
            values=(u'both', u'left-right', u'right-left'),
            default=u'both',
            doc=_('Direction of replication between left and right replication '
                  'node'),
            flags={'no_option', 'no_update'},
        ),
        Str(
            'nsds5replicastripattrs?',
            cli_name='stripattrs',
            label=_('Attributes to strip'),
            normalizer=lambda value: value.lower(),
            doc=_('A space separated list of attributes which are removed from '
                  'replication updates.')
        ),
        Str(
            'nsds5replicatedattributelist?',
            cli_name='replattrs',
            label='Attributes to replicate',
            doc=_('Attributes that are not replicated to a consumer server '
                  'during a fractional update. E.g., `(objectclass=*) '
                  '$ EXCLUDE accountlockout memberof'),
        ),
        Str(
            'nsds5replicatedattributelisttotal?',
            cli_name='replattrstotal',
            label=_('Attributes for total update'),
            doc=_('Attributes that are not replicated to a consumer server '
                  'during a total update. E.g. (objectclass=*) $ EXCLUDE '
                  'accountlockout'),
        ),
        Int(
            'nsds5replicatimeout?',
            cli_name='timeout',
            label=_('Session timeout'),
            minvalue=0,
            doc=_('Number of seconds outbound LDAP operations waits for a '
                  'response from the remote replica before timing out and '
                  'failing'),
        ),
        StrEnum(
            'nsds5replicaenabled?',
            cli_name='enabled',
            label=_('Replication agreement enabled'),
            doc=_('Whether a replication agreement is active, meaning whether '
                  'replication is occurring per that agreement'),
            values=(u'on', u'off'),
            flags={'no_option'},
        ),
    )

    def validate_nodes(self, ldap, dn, entry_attrs):
        leftnode = entry_attrs.get('iparepltoposegmentleftnode')
        rightnode = entry_attrs.get('iparepltoposegmentrightnode')

        if not leftnode and not rightnode:
            return  # nothing to check

        # check if nodes are IPA servers
        masters = self.api.Command.server_find('', sizelimit=0)['result']
        m_hostnames = [master['cn'][0].lower() for master in masters]

        if leftnode and leftnode not in m_hostnames:
            raise errors.ValidationError(
                name='leftnode',
                error=_('left node is not a topology node: %(leftnode)s') %
                     dict(leftnode=leftnode)
            )

        if rightnode and rightnode not in m_hostnames:
            raise errors.ValidationError(
                name='rightnode',
                error=_('right node is not a topology node: %(rightnode)s') %
                     dict(rightnode=rightnode)
            )

        # prevent creation of reflexive relation
        key = 'leftnode'
        if not leftnode or not rightnode:  # get missing end
            _entry_attrs = ldap.get_entry(dn, ['*'])
            if not leftnode:
                key = 'rightnode'
                leftnode = _entry_attrs['iparepltoposegmentleftnode'][0]
            else:
                rightnode = _entry_attrs['iparepltoposegmentrightnode'][0]

        if leftnode == rightnode:
            raise errors.ValidationError(
                name=key,
                error=_('left node and right node must not be the same')
            )


@register()
class topologysegment_find(LDAPSearch):
    __doc__ = _('Search for topology segments.')

    msg_summary = ngettext(
        '%(count)d segment matched',
        '%(count)d segments matched', 0
    )


@register()
class topologysegment_add(LDAPCreate):
    __doc__ = _('Add a new segment.')

    msg_summary = _('Added segment "%(value)s"')

    def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
        assert isinstance(dn, DN)
        validate_domain_level(self.api)
        self.obj.validate_nodes(ldap, dn, entry_attrs)
        return dn


@register()
class topologysegment_del(LDAPDelete):
    __doc__ = _('Delete a segment.')

    msg_summary = _('Deleted segment "%(value)s"')

    def pre_callback(self, ldap, dn, *keys, **options):
        assert isinstance(dn, DN)
        validate_domain_level(self.api)
        return dn


@register()
class topologysegment_mod(LDAPUpdate):
    __doc__ = _('Modify a segment.')

    msg_summary = _('Modified segment "%(value)s"')

    def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
        assert isinstance(dn, DN)
        validate_domain_level(self.api)
        self.obj.validate_nodes(ldap, dn, entry_attrs)
        return dn


@register()
class topologysegment_reinitialize(LDAPQuery):
    __doc__ = _('Request a full re-initialization of the node '
                'retrieving data from the other node.')

    has_output = output.standard_value
    msg_summary = _('%(value)s')

    takes_options = (
        Flag(
            'left?',
            doc=_('Initialize left node'),
            default=False,
        ),
        Flag(
            'right?',
            doc=_('Initialize right node'),
            default=False,
        ),
        Flag(
            'stop?',
            doc=_('Stop already started refresh of chosen node(s)'),
            default=False,
        ),
    )

    def execute(self, *keys, **options):
        dn = self.obj.get_dn(*keys, **options)
        validate_domain_level(self.api)

        entry = self.obj.backend.get_entry(
            dn, [
                'nsds5beginreplicarefresh;left',
                'nsds5beginreplicarefresh;right'
            ])

        left = options.get('left')
        right = options.get('right')
        stop = options.get('stop')

        if not left and not right:
            raise errors.OptionError(
                _('left or right node has to be specified')
            )

        if left and right:
            raise errors.OptionError(
                _('only one node can be specified')
            )

        action = u'start'
        msg = _('Replication refresh for segment: "%(pkey)s" requested.')
        if stop:
            action = u'stop'
            msg = _('Stopping of replication refresh for segment: "'
                    '%(pkey)s" requested.')

        # left and right are swapped because internally it's a push not
        # pull operation
        if right:
            entry['nsds5beginreplicarefresh;left'] = [action]
        if left:
            entry['nsds5beginreplicarefresh;right'] = [action]

        self.obj.backend.update_entry(entry)

        msg = msg % {'pkey': keys[-1]}
        return dict(
            result=True,
            value=msg,
        )


@register()
class topologysegment_show(LDAPRetrieve):
    __doc__ = _('Display a segment.')


@register()
class topologysuffix(LDAPObject):
    """
    Suffix managed by the topology plugin.
    """
    container_dn = api.env.container_topology
    object_name = _('suffix')
    object_name_plural = _('suffices')
    object_class = ['iparepltopoconf']
    default_attributes = ['cn', 'ipaReplTopoConfRoot']
    search_display_attributes = ['cn', 'ipaReplTopoConfRoot']
    label = _('Topology suffices')
    label_singular = _('Topology suffix')

    takes_params = (
        Str(
            'cn',
            cli_name='name',
            primary_key=True,
            label=_('Suffix name'),
        ),
        Str(
            'iparepltopoconfroot',
            maxlength=255,
            cli_name='suffix',
            label=_('LDAP suffix to be managed'),
            normalizer=lambda value: value.lower(),
        ),
    )


@register()
class topologysuffix_find(LDAPSearch):
    __doc__ = _('Search for topology suffices.')

    msg_summary = ngettext(
        '%(count)d topology suffix matched',
        '%(count)d topology suffices matched', 0
    )


@register()
class topologysuffix_del(LDAPDelete):
    __doc__ = _('Delete a topology suffix.')

    NO_CLI = True

    msg_summary = _('Deleted topology suffix "%(value)s"')

    def pre_callback(self, ldap, dn, *keys, **options):
        assert isinstance(dn, DN)
        validate_domain_level(self.api)
        return dn


@register()
class topologysuffix_add(LDAPCreate):
    __doc__ = _('Add a new topology suffix to be managed.')

    NO_CLI = True

    msg_summary = _('Added topology suffix "%(value)s"')

    def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
        assert isinstance(dn, DN)
        validate_domain_level(self.api)
        return dn


@register()
class topologysuffix_mod(LDAPUpdate):
    __doc__ = _('Modify a topology suffix.')

    NO_CLI = True

    msg_summary = _('Modified topology suffix "%(value)s"')

    def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
        assert isinstance(dn, DN)
        validate_domain_level(self.api)
        return dn


@register()
class topologysuffix_show(LDAPRetrieve):
    __doc__ = _('Show managed suffix.')


@register()
class topologysuffix_verify(LDAPQuery):
    __doc__ = _('''
Verify replication topology for suffix.

Checks done:
  1. check if a topology is not disconnected. In other words if there are
     replication paths between all servers.
  2. check if servers don't have more than the recommended number of
     replication agreements
''')

    def execute(self, *keys, **options):

        validate_domain_level(self.api)

        masters = self.api.Command.server_find('', sizelimit=0)['result']
        segments = self.api.Command.topologysegment_find(
            keys[0], sizelimit=0)['result']
        graph = create_topology_graph(masters, segments)
        master_cns = [m['cn'][0] for m in masters]
        master_cns.sort()

        # check if each master can contact others
        connect_errors = get_topology_connection_errors(graph)

        # check if suggested maximum number of agreements per replica
        max_agmts_errors = []
        for m in master_cns:
            # chosen direction doesn't matter much given that 'both' is the
            # only allowed direction
            suppliers = graph.get_tails(m)
            if len(suppliers) > self.api.env.recommended_max_agmts:
                max_agmts_errors.append((m, suppliers))

        return dict(
            result={
                'in_order': not connect_errors and not max_agmts_errors,
                'connect_errors': connect_errors,
                'max_agmts_errors': max_agmts_errors,
                'max_agmts': self.api.env.recommended_max_agmts
            },
        )

    def output_for_cli(self, textui, output, *args, **options):

        in_order = output['result']['in_order']
        connect_errors = output['result']['connect_errors']
        max_agmts_errors = output['result']['max_agmts_errors']

        if in_order:
            header = _('Replication topology of suffix "%(suffix)s" '
                       'is in order.')
        else:
            header = _('Replication topology of suffix "%(suffix)s" contains '
                       'errors.')
        textui.print_h1(header % {'suffix': args[0]})

        if connect_errors:
            textui.print_dashed(unicode(_('Topology is disconnected')))
            for err in connect_errors:
                msg = _("Server %(srv)s can't contact servers: %(replicas)s")
                msg = msg % {'srv': err[0], 'replicas': ', '.join(err[2])}
                textui.print_indented(msg)

        if max_agmts_errors:
            textui.print_dashed(unicode(_('Recommended maximum number of '
                                          'agreements per replica exceeded')))
            textui.print_attribute(
                unicode(_("Maximum number of agreements per replica")),
                [output['result']['max_agmts']]
            )
            for err in max_agmts_errors:
                msg = _('Server "%(srv)s" has %(n)d agreements with servers:')
                msg = msg % {'srv': err[0], 'n': len(err[1])}
                textui.print_indented(msg)
                for replica in err[1]:
                    textui.print_indented(replica, 2)

        return 0