This repository has been archived by the owner on Sep 26, 2022. It is now read-only.
/
_ldap.py
2053 lines (1709 loc) · 64.1 KB
/
_ldap.py
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
"""Low level admin API to manipulate global cell topology.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import sys
import collections
import copy
import json
import itertools
import logging
import shlex
import ldap3
import ldap3.core.exceptions as ldap_exceptions
import jinja2
import six
if sys.platform == 'win32':
import treadmill.ldap3kerberos
sys.modules['ldap3.protocol.sasl.kerberos'] = treadmill.ldap3kerberos
# pylint: disable=too-many-lines
_LOGGER = logging.getLogger(__name__)
_SYNTAX_2_TYPE = {
'1.3.6.1.4.1.1466.115.121.1.7': 'bool',
'1.3.6.1.4.1.1466.115.121.1.15': 'str',
'1.3.6.1.4.1.1466.115.121.1.12': 'dn',
'1.3.6.1.4.1.1466.115.121.1.26': 'ias_str',
'1.3.6.1.4.1.1466.115.121.1.27': 'int',
'1.3.6.1.4.1.1466.115.121.1.36': 'numeric',
'1.3.6.1.4.1.1466.115.121.1.38': 'oid',
'1.3.6.1.4.1.1466.115.121.1.40': 'octets',
}
_TYPE_2_EQUALITY = {
('str', False): 'caseExactMatch',
('str', True): 'caseIgnoreMatch',
('dn', False): 'distinguishedNameMatch',
('int', False): 'integerMatch',
}
_TYPE_2_ORDERING = {
('int', None): 'integerOrderingMatch',
}
_TYPE_2_SUBSTR = {
('str', False): 'caseExactSubstringsMatch',
('str', True): 'caseIgnoreSubstringsMatch',
}
_TREADMILL_ATTR_OID_PREFIX = '1.3.6.1.4.1.360.10.6.1.'
_TREADMILL_OBJCLS_OID_PREFIX = '1.3.6.1.4.1.360.10.6.2.'
DEFAULT_PARTITION = '_default'
DEFAULT_TENANT = '_default'
def _to_bool(value):
"""Fuzzy converion of string/int to bool."""
if isinstance(value, bool):
return value
# XXX: This is necessary until previous bad entries are aacleaned up.
_LOGGER.warning('Deprecation warning: bool as str')
s_value = str(value).lower()
if s_value in ('0', 'false'):
return False
else:
return True
def _entry_2_dict(entry, schema):
"""Convert LDAP entry like object to dict.
"""
obj = dict()
for ldap_field, obj_field, field_type in schema:
if obj_field is None:
continue
if ldap_field not in entry:
if isinstance(field_type, list):
obj[obj_field] = []
else:
obj[obj_field] = None
continue
value = entry[ldap_field]
if isinstance(field_type, list):
if field_type[0] is str:
obj[obj_field] = [v for v in value]
else:
obj[obj_field] = [field_type[0](v) for v in value]
elif field_type is bool:
obj[obj_field] = _to_bool(value[0])
elif field_type is dict:
obj[obj_field] = json.loads(value[0])
elif field_type is str:
obj[obj_field] = value[0]
else:
obj[obj_field] = field_type(value[0])
return {
k: v
for k, v in six.iteritems(obj)
if v is not None
}
def _dict_2_entry(obj, schema, option=None, option_idx=None):
"""Converts dict to ldap entry."""
# TODO: refactor to eliminate too many branches warning.
#
# pylint: disable=R0912
entry = dict()
for ldap_field, obj_field, field_type in schema:
if obj_field not in obj:
continue
value = obj[obj_field]
if option is not None:
assert option_idx is not None
ldap_field = '{attribute};{option_prefix}-{option_idx:x}'.format(
attribute=ldap_field,
option_prefix=option,
option_idx=option_idx
)
if value is None:
entry[ldap_field] = []
else:
if isinstance(field_type, list):
# TODO: we need to check that all values are of specified type.
if value:
filtered = [
six.text_type(v)
for v in value
if v is not None
]
if len(filtered) < len(value):
_LOGGER.critical('Expected %r, got %r',
field_type, value)
entry[ldap_field] = filtered
elif field_type is bool:
entry[ldap_field] = [_to_bool(value)]
elif field_type is dict:
entry[ldap_field] = [
json.dumps(
# Use an OrderedDict to guaranty the stability of the
# dictionary key order in the JSON dump.
collections.OrderedDict(
sorted(value.items(), key=lambda t: t[0])
)
)
]
else:
entry[ldap_field] = [six.text_type(value)]
return entry
def _empty_list_entry(schema):
"""Generate an empty list entry for the provided schema.
"""
entry = {}
for ldap_field, _obj_field, _field_type in schema:
entry[ldap_field] = []
return entry
def _to_obj_list(obj_list, key, prefix, schema):
"""Convert a (keyed) object list, into an entry.
:param ``list`` obj_list:
List of object
:param ``str`` key:
Key attribute in each object
:param ``str`` prefix:
LDAP attribute prefix (AttributeOption)
:param schema:
Object's schema
"""
obj_iter = sorted(
obj_list,
key=lambda obj: obj[key]
)
if not obj_iter:
entry = _empty_list_entry(schema)
else:
entry = {}
for idx, obj in enumerate(obj_iter):
entry.update(
_dict_2_entry(
obj,
schema, prefix,
idx
)
)
return entry
def _remove_empty(entry):
"""Remove any empty values and empty lists from entry."""
new_entry = copy.deepcopy(entry)
for key, value in six.iteritems(new_entry):
if isinstance(value, dict):
new_entry[key] = _remove_empty(value)
emptykeys = [
key
for key, value in six.iteritems(new_entry)
if not value
]
for key in emptykeys:
del new_entry[key]
return new_entry
def _attrtype_2_abstract(attrtype):
"""Converts attribute type to 'abstract' representation."""
name = attrtype['name']
syntax = attrtype['syntax']
abstract = {}
assert syntax in _SYNTAX_2_TYPE
abstract['type'] = _SYNTAX_2_TYPE[syntax]
abstract['desc'] = attrtype['desc']
if abstract['type'] == 'str':
if attrtype.get('equality') == 'caseIgnoreMatch':
abstract['ignore_case'] = True
abstract['idx'] = attrtype['idx']
return (name, abstract)
def _abstract_2_attrtype(name, abstract):
"""Converts abstract attribute type to full LDAP definition."""
attr = {}
attr['idx'] = abstract['idx']
attr['oid'] = _TREADMILL_ATTR_OID_PREFIX + six.text_type(attr['idx'])
attr['name'] = name
attr['desc'] = abstract.get('desc', name)
type_2_syntax = {
v: k
for k, v in six.iteritems(_SYNTAX_2_TYPE)
}
assert abstract['type'] in type_2_syntax
attr['syntax'] = type_2_syntax[abstract['type']]
type_case = (abstract['type'], bool(abstract.get('ignore_case')))
attr['equality'] = _TYPE_2_EQUALITY.get(type_case)
attr['substr'] = _TYPE_2_SUBSTR.get(type_case)
attr['ordering'] = _TYPE_2_ORDERING.get(type_case)
if abstract.get('single_value'):
attr['single_value'] = True
if abstract.get('obsolete'):
attr['obsolete'] = True
return attr
def _attrtype_2_str(attr):
"""Converts attribute type dictionary to str.
"""
template = (
'( {{ oid_pfx }}{{ item.idx }}'
' NAME \'{{ item.name }}\''
' DESC \'{{ item.desc }}\''
' SYNTAX {{ item.syntax }}'
' {% if item.equality -%}'
' EQUALITY {{ item.equality }}'
' {% endif -%}'
' {% if item.substr -%}'
' SUBSTR {{ item.substr }}'
' {% endif -%}'
' {% if item.ordering -%}'
' ORDERING {{ item.ordering }}'
' {% endif -%}'
' {% if item.single_value -%}'
' SINGLE-VALUE'
' {% endif -%} )'
)
return six.text_type(
jinja2.Template(template).render(
item=attr,
oid_pfx=_TREADMILL_ATTR_OID_PREFIX
)
)
def _objcls_2_abstract(obj_cls):
"""Converts object class to abstract."""
name = obj_cls['name']
abstract = {
'must': obj_cls.get('must', []),
'may': obj_cls.get('may', []),
'desc': obj_cls.get('desc', ''),
'idx': obj_cls['idx'],
}
return (name, abstract)
def _objcls_2_str(name, obj_cls):
"""Converts object class dict to string.
"""
template = (
'( {{ oid_pfx }}{{ item.idx }}'
' NAME \'{{ name }}\''
' DESC \'{{ item.desc }}\''
' SUP top STRUCTURAL'
' MUST ( {{ item.must | join(" $ ") }} )'
' {% if item.may -%}'
' MAY ( {{ item.may | join(" $ ") }} )'
' {% endif -%}'
' )'
)
return six.text_type(
jinja2.Template(template).render(
name=name,
item=obj_cls,
oid_pfx=_TREADMILL_OBJCLS_OID_PREFIX
)
)
def _entry_plain_keys(entry):
"""Return an entry keys, stripping all options.
"""
return sorted({
k.split(';', 1)[0]
for k in entry.keys()
})
def _group_entry_by_opt(entry):
"""Group by attr;option."""
attrs_with_opt = [
tuple(k.split(';') + [entry[k]])
for k in entry.keys()
if ';' in k
]
# Sort by option first, field name second
attrs_with_opt.sort(key=lambda x: (x[1], x[0]))
return {
key: list(group)[0::1]
for key, group in itertools.groupby(
attrs_with_opt,
lambda x: x[1]
)
}
def _grouped_to_list_of_dict(grouped, prefix, schema):
"""Converts grouped attribute to list of dicts."""
def _to_dict(values):
"""converts to dict."""
return _entry_2_dict(
{
k: v
for k, _, v in values
},
schema
)
filtered = {
k: v
for k, v in six.iteritems(grouped)
if k.startswith(prefix)
}
values_list = [
_to_dict(v) for _k, v in six.iteritems(filtered)
]
return sorted(
values_list,
key=lambda x: sorted(list(six.iteritems(x)))
)
def _diff_attribute_values(old_value, new_value):
"""Returns True if the attribute values are different."""
are_different = len(old_value) != len(new_value)
if not are_different:
old_value_dict = dict.fromkeys(old_value)
new_value_dict = dict.fromkeys(new_value)
for value in old_value:
if value not in new_value_dict:
are_different = True
break
if not are_different:
for value in new_value:
if value not in old_value_dict:
are_different = True
break
return are_different
def _diff_entries(old_entry, new_entry):
"""Diff the entries and produce a diff dictionary suitable for update."""
# Adapted from python-ldap (http://www.python-ldap.org/) modlist
# https://github.com/pyldap/pyldap/blob/master/Lib/ldap/modlist.py#L51
diff = {}
attrtype_lower_map = {}
for attr in old_entry.keys():
attrtype_lower_map[attr.lower()] = attr
for attrtype in new_entry.keys():
attrtype_lower = attrtype.lower()
# Filter away null-strings
new_values = [
value
for value in new_entry[attrtype]
if value is not None
]
if attrtype_lower in attrtype_lower_map:
old_values = old_entry.get(attrtype_lower_map[attrtype_lower], [])
old_values = [
value
for value in old_values
if value is not None
]
del attrtype_lower_map[attrtype_lower]
else:
old_values = []
if not old_values and new_values:
# Add a new attribute to entry
diff.setdefault(attrtype, []).append(
(ldap3.MODIFY_ADD, new_values)
)
elif old_values and new_values:
# Replace existing attribute
if _diff_attribute_values(old_values, new_values):
diff.setdefault(attrtype, []).append(
(ldap3.MODIFY_REPLACE, new_values))
elif old_values and not new_values:
# Completely delete an existing attribute
diff.setdefault(attrtype, []).append(
(ldap3.MODIFY_DELETE, []))
# Remove all attributes of old_entry which are not present
# in new_entry at all
for attr in attrtype_lower_map:
attrtype = attrtype_lower_map[attr]
diff.setdefault(attrtype, []).append((ldap3.MODIFY_DELETE, []))
return diff
class AndQuery:
"""And query helper."""
def __init__(self, key, value):
self.clauses = [(key, value)]
def __call__(self, key, value):
"""Add constraint."""
self.clauses.append((key, value))
def __str__(self):
return self.to_str()
def to_str(self):
"""Converts to LDAP query string."""
paren = ['(%s=%s)' % (k, v) for k, v in self.clauses]
query = ''.join(paren)
if len(paren) > 1:
query = '(&%s)' % query
return query
class Admin:
"""Manages Treadmill objects in ldap.
"""
# Allow such names as 'dn', 'ou'
# pylint: disable=invalid-name
# pylint: disable=too-many-statements
def __init__(self, uri, ldap_suffix,
user=None, password=None, connect_timeout=5, write_uri=None):
self.uri = uri
self.write_uri = write_uri
self.ldap_suffix = ldap_suffix
self.root_ou = 'ou=treadmill,%s' % ldap_suffix
self.user = user
self.password = password
self._connect_timeout = connect_timeout
self.ldap = None
self.write_ldap = None
def close(self):
"""Closes ldap connection."""
try:
if self.ldap:
self.ldap.unbind()
except ldap_exceptions.LDAPCommunicationError:
_LOGGER.exception('cannot close connection.')
try:
if self.write_ldap:
self.write_ldap.unbind()
except ldap_exceptions.LDAPCommunicationError:
_LOGGER.exception('cannot close connection.')
def dn(self, parts):
"""Constructs dn."""
return ','.join(parts + [self.root_ou])
def _connect_to_uri(self, uri):
"""Create an LDAP connection to the given URI."""
try:
server = ldap3.Server(
uri,
mode=ldap3.IP_V4_ONLY,
connect_timeout=self._connect_timeout,
)
if self.user and self.password:
ldap_auth = {
'user': self.user,
'password': self.password
}
else:
ldap_auth = {
'authentication': ldap3.SASL,
'sasl_mechanism': 'GSSAPI',
'sasl_credentials': (True,)
}
return ldap3.Connection(
server,
client_strategy=ldap3.RESTARTABLE,
auto_bind=True,
auto_encode=True,
auto_escape=True,
return_empty_attributes=False,
**ldap_auth
)
except (ldap_exceptions.LDAPSocketOpenError,
ldap_exceptions.LDAPBindError,
ldap_exceptions.LDAPMaximumRetriesError):
_LOGGER.debug('Failed to connect to %s', uri, exc_info=True)
return None
def connect(self):
"""Connects (binds) to LDAP server."""
ldap3.set_config_parameter('RESTARTABLE_TRIES', 3)
ldap3.set_config_parameter('DEFAULT_CLIENT_ENCODING', 'utf8')
ldap3.set_config_parameter('DEFAULT_SERVER_ENCODING', 'utf8')
# This is needed because twisted monkey-patches socket._is_ipv6
# and ldap3 code is wrong.
# pylint: disable=protected-access
ldap3.Server._is_ipv6 = lambda x, y: False
if self.ldap or self.write_ldap:
_LOGGER.debug('Closing existing connections before connect')
self.close()
for uri in self.uri:
ldap_connection = self._connect_to_uri(uri)
if ldap_connection is not None:
self.ldap = ldap_connection
break
if not self.ldap:
raise ldap_exceptions.LDAPBindError(
'Failed to connect to any LDAP server: {}'.format(
', '.join(self.uri)
)
)
if not self.write_uri:
self.write_ldap = self.ldap
return
for write_uri in self.write_uri:
ldap_connection = self._connect_to_uri(write_uri)
if ldap_connection is not None:
self.write_ldap = ldap_connection
break
if not self.write_ldap:
raise ldap_exceptions.LDAPBindError(
'Failed to connect to any LDAP server: {}'.format(
', '.join(self.write_uri)
)
)
def search(self, search_base=None, search_filter=None,
search_scope=ldap3.SUBTREE, attributes=None, dirty=False):
"""Call ldap search and return a generator of dn, entry tuples.
"""
if search_base is None:
search_base = self.root_ou
if search_filter is None:
search_filter = '(objectClass=*)'
if attributes is None:
attributes = ['*', '+']
# If entries in the potential search results were written or modified
# recently, we use the connection to the write server to avoid problems
# with replication delays between provider and consumer
ldap = self.write_ldap if dirty else self.ldap
ldap.result = None
ldap.search(
search_base=search_base,
search_filter=search_filter,
search_scope=search_scope,
attributes=attributes,
dereference_aliases=ldap3.DEREF_NEVER
)
self._test_raise_exceptions(ldap)
return iter(ldap.response)
def paged_search(self, search_base=None, search_filter=None,
search_scope=ldap3.SUBTREE, attributes=None, dirty=False):
"""Call ldap paged search and return a generator of dn, entry tuples.
:returns:
``generator`` - Search result generator
"""
if search_base is None:
search_base = self.root_ou
if search_filter is None:
search_filter = '(objectClass=*)'
if attributes is None:
attributes = ['*', '+']
# If entries in the potential search results were written or modified
# recently, we use the connection to the write server to avoid problems
# with replication delays between provider and consumer
ldap = self.write_ldap if dirty else self.ldap
ldap.result = None
res_gen = ldap.extend.standard.paged_search(
search_base=search_base,
search_filter=search_filter,
search_scope=search_scope,
attributes=attributes,
dereference_aliases=ldap3.DEREF_NEVER,
paged_size=50,
paged_criticality=True,
generator=True
)
self._test_raise_exceptions(ldap)
return res_gen
def _test_raise_exceptions(self, ldap=None):
"""
Looks for specific error conditions or throws if non-success state.
"""
if ldap is None:
ldap = self.ldap
if not ldap.result or 'result' not in ldap.result:
return
exception_type = None
result_code = ldap.result['result']
if result_code == 68:
exception_type = ldap_exceptions.LDAPEntryAlreadyExistsResult
elif result_code == 32:
exception_type = ldap_exceptions.LDAPNoSuchObjectResult
elif result_code == 50:
exception_type =\
ldap_exceptions.LDAPInsufficientAccessRightsResult
elif result_code != 0:
exception_type = ldap_exceptions.LDAPOperationResult
if exception_type:
raise exception_type(result=ldap.result['result'],
description=ldap.result['description'],
dn=ldap.result['dn'],
message=ldap.result['message'],
response_type=ldap.result['type'])
def modify(self, dn, changes):
"""Call ldap modify and raise exception on non-success."""
if changes:
self.write_ldap.modify(dn, changes)
self._test_raise_exceptions(self.write_ldap)
def add(self, dn, object_class=None, attributes=None):
"""Call ldap add and raise exception on non-success."""
sorted_attributes = collections.OrderedDict(sorted(
(k, v)
for k, v in six.iteritems(attributes)
)) if attributes else None
self.write_ldap.add(dn, object_class, sorted_attributes)
self._test_raise_exceptions(self.write_ldap)
def delete(self, dn):
"""Call ldap delete and raise exception on non-success."""
self.write_ldap.delete(dn)
self._test_raise_exceptions(self.write_ldap)
def schema(self, abstract=True):
"""Get schema."""
# Disable too many branches warning.
#
# pylint: disable=R0912
#
# NOTE: cn=schema,cn=config does *NOT* support paged searches.
result = self.search(search_base='cn=schema,cn=config',
search_filter='(cn={*}treadmill)',
search_scope=ldap3.LEVEL,
attributes=['olcAttributeTypes',
'olcObjectClasses'])
entry = next(result, None)
if entry is None:
return None
schema_dn, schema = entry['dn'], entry['attributes']
attr_types = []
for attr_type_s in schema.get('olcAttributeTypes', []):
# Split preserving quotes.
attr_type_l = shlex.split(attr_type_s)
# Remove leading and closing bracket.
attr_type_l = attr_type_l[1:-1]
oid = attr_type_l.pop(0)
assert oid.startswith(_TREADMILL_ATTR_OID_PREFIX)
# Extract index: the last number in OID
# (assuming that custom OID hierarchy has only 1 level)
attr = {'oid': oid, 'idx': int(oid.split('.')[-1])}
# Remaining are key/value pairs. Iterate over each, converting
# key to lowercase.
while attr_type_l:
token = attr_type_l.pop(0)
if token == 'NAME':
attr['name'] = attr_type_l.pop(0)
if token == 'SYNTAX':
attr['syntax'] = attr_type_l.pop(0)
elif token == 'DESC':
attr['desc'] = attr_type_l.pop(0)
elif token == 'ORDERING':
attr['ordering'] = attr_type_l.pop(0)
elif token == 'SUBSTR':
attr['substr'] = attr_type_l.pop(0)
elif token == 'EQUALITY':
attr['equality'] = attr_type_l.pop(0)
elif token == 'SINGLE-VALUE':
attr['single_value'] = True
elif token == 'COLLECTIVE':
attr['collective'] = True
elif token == 'OBSOLETE':
attr['obsolete'] = True
else:
assert 'Unsupported token: %s: %s' % (attr_type_s, token)
attr_types.append(attr)
obj_classes = []
def _parse_attr_list(alist):
"""Parses ( a $ b ) => [a, b]"""
result = []
assert alist.pop(0) == '('
while len(alist) > 1:
result.append(alist.pop(0))
sep = alist.pop(0)
if sep == ')':
return result
assert sep == '$'
for obj_cls_s in schema.get('olcObjectClasses', []):
# Split preserving quotes.
obj_cls_l = shlex.split(obj_cls_s)
# Remove leading and closing bracket.
obj_cls_l = obj_cls_l[1:-1]
oid = obj_cls_l.pop(0)
# Extract index: the last number in OID
# (assuming that custom OID hierarchy has only 1 level)
obj_cls = {'oid': oid, 'idx': int(oid.split('.')[-1])}
# poor man parsing.
while obj_cls_l:
token = obj_cls_l.pop(0)
if token == 'NAME':
obj_cls['name'] = obj_cls_l.pop(0)
elif token == 'DESC':
obj_cls['desc'] = obj_cls_l.pop(0)
elif token == 'SUP':
assert obj_cls_l.pop(0) == 'top'
elif token == 'STRUCTURAL':
continue
elif token == 'MUST':
obj_cls['must'] = _parse_attr_list(obj_cls_l)
elif token == 'MAY':
obj_cls['may'] = _parse_attr_list(obj_cls_l)
else:
assert 'Invalid token: %s, %r' % (obj_cls_s, token)
obj_classes.append(obj_cls)
if abstract:
attr_types = {
name: abstract
for (name, abstract) in (
_attrtype_2_abstract(a) for a in attr_types
)
}
obj_classes = {
name: abstract
for (name, abstract) in (
_objcls_2_abstract(o) for o in obj_classes
)
}
return {'dn': schema_dn,
'attributeTypes': attr_types,
'objectClasses': obj_classes}
@staticmethod
def _schema_attrtype_diff(old_attr_types, new_attr_types):
"""Construct difference between old/new attr type list.
"""
to_add = dict()
to_del = dict()
common = set(new_attr_types.keys()) & set(old_attr_types.keys())
added = set(new_attr_types.keys()) - set(old_attr_types.keys())
for name in common:
old_attr = old_attr_types[name]
new_attr = new_attr_types[name]
for key in ['type', 'ignore_case']:
if new_attr.get(key) != old_attr.get(key):
assert 'Type modified in place: %s' % name
for key in ['desc']:
if new_attr.get(key) != old_attr.get(key):
new_attr['idx'] = old_attr['idx']
to_del[name] = old_attr
to_add[name] = new_attr
# Calculate max oid index.
if not old_attr_types:
next_oid = 1
else:
next_oid = max([attr['idx']
for attr in old_attr_types.values()]) + 1
for name in added:
attr = new_attr_types[name]
attr['idx'] = next_oid
next_oid += 1
to_add[name] = attr
return to_del, to_add
@staticmethod
def _schema_objcls_diff(old_ocs, new_ocs):
"""Construct difference between old/new attr type list.
"""
to_add = dict()
to_del = dict()
common = set(new_ocs.keys()) & set(old_ocs.keys())
added = set(new_ocs.keys()) - set(old_ocs.keys())
for name in common:
old_oc = old_ocs[name]
new_oc = new_ocs[name]
old_oc['name'] = name
new_oc['name'] = name
new_oc['idx'] = old_oc['idx']
if _objcls_2_str(name, old_oc) != _objcls_2_str(name, new_oc):
to_del[name] = old_oc
to_add[name] = new_oc
# Calculate max oid index.
if not old_ocs:
next_oid = 1
else:
next_oid = 1 + max([
item['idx']
for item in old_ocs.values()
])
for name in added:
objcls = new_ocs[name]
objcls['idx'] = next_oid
next_oid += 1
to_add[name] = objcls
return to_del, to_add
def update_schema(self, new_schema):
"""Safely update schema, preserving existing attribute types."""
old_schema = self.schema() or self.init_schema()
schema_dn = old_schema['dn']
old_attr_types = old_schema['attributeTypes']
new_attr_types = new_schema['attributeTypes']
changes = collections.defaultdict(list)
to_del, to_add = self._schema_attrtype_diff(old_attr_types,
new_attr_types)
if to_del:
values = [_attrtype_2_str(_abstract_2_attrtype(name, attr))
for name, attr in six.iteritems(to_del)]
_LOGGER.debug('del: %s - olcAttributeTypes: %r', schema_dn, values)
changes['olcAttributeTypes'].extend(
[(ldap3.MODIFY_DELETE, values)])
if to_add:
values = [_attrtype_2_str(_abstract_2_attrtype(name, attr))
for name, attr in six.iteritems(to_add)]
_LOGGER.debug('add: %s - olcAttributeTypes: %r', schema_dn, values)
changes['olcAttributeTypes'].extend([(ldap3.MODIFY_ADD, values)])
old_obj_classes = old_schema['objectClasses']
new_obj_classes = new_schema['objectClasses']
to_del, to_add = self._schema_objcls_diff(old_obj_classes,
new_obj_classes)
if to_del:
values = [_objcls_2_str(name, item)
for name, item in six.iteritems(to_del)]
_LOGGER.debug('del: %s - olcObjectClasses: %r', schema_dn, values)
changes['olcObjectClasses'].extend([(ldap3.MODIFY_DELETE, values)])
if to_add:
values = [_objcls_2_str(name, item)
for name, item in six.iteritems(to_add)]
_LOGGER.debug('add: %s - olcObjectClasses: %r', schema_dn, values)
changes['olcObjectClasses'].extend([(ldap3.MODIFY_ADD, values)])
if changes:
# TODO must be modified in a specific order to avoid exceptions
self.modify(schema_dn, changes)
else:
_LOGGER.info('Schema is up to date.')
def init_schema(self):
"""Initializes treadmill ldap schema namespace."""
schema_dn = 'cn=treadmill,cn=schema,cn=config'
schema_object_class = 'olcSchemaConfig'
schema_attributes = {'cn': 'treadmill'}
_LOGGER.debug('Creating: %s %s %s',
schema_dn, schema_object_class, schema_attributes)
self.add(schema_dn, schema_object_class, schema_attributes)
return self.schema()
def init(self):
"""Initializes treadmill ldap namespace."""
# TOOD: not sure if this takes into account more tnan 2 levels in
# ldap_suffix, e.g. dc=x,dc=y,dc=com
dc = self.ldap_suffix.split(',')[0].split('=')[1]
def _build_ou(ou, name=None):
"""Helper to build an ou string."""
return 'ou=' + ou + ',' + self.root_ou, \
['organizationalUnit'], \
{'ou': name or ou}
dir_entries = [
(self.ldap_suffix,
['dcObject', 'organization'],
{'o': [dc], 'dc': [dc]}),
(self.root_ou,
['organizationalUnit'],
{'ou': self.root_ou}),
_build_ou('apps', 'applications'),
_build_ou('cells'),
_build_ou('dns-servers'),
_build_ou('servers'),
_build_ou('tenants'),
_build_ou('allocations'),
_build_ou('app-groups'),
]