2 # -*- coding: utf-8 -*-
4 # Tests various schema replication scenarios
6 # Copyright (C) Catalyst.Net Ltd. 2017
8 # This program is free software; you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 3 of the License, or
11 # (at your option) any later version.
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License
19 # along with this program. If not, see <http://www.gnu.org/licenses/>.
24 # export DC1=dc1_dns_name
25 # export DC2=dc2_dns_name
26 # export SUBUNITRUN=$samba4srcdir/scripting/bin/subunitrun
27 # PYTHONPATH="$PYTHONPATH:$samba4srcdir/torture/drs/python" $SUBUNITRUN getncchanges -U"$DOMAIN/$DC_USERNAME"%"$DC_PASSWORD"
33 from ldb import SCOPE_BASE
36 from samba.dcerpc import drsuapi
38 class DrsReplicaSyncIntegrityTestCase(drs_base.DrsBaseTestCase):
40 super(DrsReplicaSyncIntegrityTestCase, self).setUp()
42 # Note that DC2 is the DC with the testenv-specific quirks (e.g. it's
43 # the vampire_dc), so we point this test directly at that DC
44 self.set_test_ldb_dc(self.ldb_dc2)
45 (self.drs, self.drs_handle) = self._ds_bind(self.dnsname_dc2)
47 # add some randomness to the test OU. (Deletion of the last test's
48 # objects can be slow to replicate out. So the OU created by a previous
49 # testenv may still exist at this point).
50 rand = random.randint(1, 10000000)
51 self.base_dn = self.test_ldb_dc.get_default_basedn()
52 self.ou = "OU=getncchanges%d_test,%s" %(rand, self.base_dn)
53 self.test_ldb_dc.add({
55 "objectclass": "organizationalUnit"})
56 (self.default_hwm, self.default_utdv) = self._get_highest_hwm_utdv(self.test_ldb_dc)
62 # 100 is the minimum max_objects that Microsoft seems to honour
63 # (the max honoured is 400ish), so we use that in these tests
64 self.max_objects = 100
67 # store whether we used GET_TGT/GET_ANC flags in the requests
68 self.used_get_tgt = False
69 self.used_get_anc = False
72 super(DrsReplicaSyncIntegrityTestCase, self).tearDown()
73 # tidyup groups and users
75 self.ldb_dc2.delete(self.ou, ["tree_delete:1"])
76 except ldb.LdbError as (enum, string):
77 if enum == ldb.ERR_NO_SUCH_OBJECT:
80 def add_object(self, dn):
81 """Adds an OU object"""
82 self.test_ldb_dc.add({"dn": dn, "objectclass": "organizationalunit"})
83 res = self.test_ldb_dc.search(base=dn, scope=SCOPE_BASE)
84 self.assertEquals(len(res), 1)
86 def modify_object(self, dn, attr, value):
87 """Modifies an object's USN by adding an attribute value to it"""
89 m.dn = ldb.Dn(self.test_ldb_dc, dn)
90 m[attr] = ldb.MessageElement(value, ldb.FLAG_MOD_ADD, attr)
91 self.test_ldb_dc.modify(m)
93 def create_object_range(self, start, end, prefix="",
94 children=None, parent_list=None):
96 Creates a block of objects. Object names are numbered sequentially,
97 using the optional prefix supplied. If the children parameter is
98 supplied it will create a parent-child hierarchy and return the
99 top-level parents separately.
103 # Use dummy/empty lists if we're not creating a parent/child hierarchy
107 if parent_list is None:
110 # Create the parents first, then the children.
111 # This makes it easier to see in debug when GET_ANC takes effect
112 # because the parent/children become interleaved (by default,
113 # this approach means the objects are organized into blocks of
114 # parents and blocks of children together)
115 for x in range(start, end):
116 ou = "OU=test_ou_%s%d,%s" % (prefix, x, self.ou)
120 # keep track of the top-level parents (if needed)
121 parent_list.append(ou)
123 # create the block of children (if needed)
124 for x in range(start, end):
125 for child in children:
126 ou = "OU=test_ou_child%s%d,%s" % (child, x, parent_list[x])
132 def assert_expected_data(self, expected_list):
134 Asserts that we received all the DNs that we expected and
137 received_list = self.rxd_dn_list
139 # Note that with GET_ANC Windows can end up sending the same parent
140 # object multiple times, so this might be noteworthy but doesn't
141 # warrant failing the test
142 if (len(received_list) != len(expected_list)):
143 print("Note: received %d objects but expected %d" %(len(received_list),
146 # Check that we received every object that we were expecting
147 for dn in expected_list:
148 self.assertTrue(dn in received_list, "DN '%s' missing from replication." % dn)
150 def test_repl_integrity(self):
152 Modify the objects being replicated while the replication is still
153 in progress and check that no object loss occurs.
156 # The server behaviour differs between samba and Windows. Samba returns
157 # the objects in the original order (up to the pre-modify HWM). Windows
158 # incorporates the modified objects and returns them in the new order
159 # (i.e. modified objects last), up to the post-modify HWM. The Microsoft
160 # docs state the Windows behaviour is optional.
162 # Create a range of objects to replicate.
163 expected_dn_list = self.create_object_range(0, 400)
164 (orig_hwm, unused) = self._get_highest_hwm_utdv(self.test_ldb_dc)
166 # We ask for the first page of 100 objects.
167 # For this test, we don't care what order we receive the objects in,
168 # so long as by the end we've received everything
171 # Modify some of the second page of objects. This should bump the highwatermark
172 for x in range(100, 200):
173 self.modify_object(expected_dn_list[x], "displayName", "OU%d" % x)
175 (post_modify_hwm, unused) = self._get_highest_hwm_utdv(self.test_ldb_dc)
176 self.assertTrue(post_modify_hwm.highest_usn > orig_hwm.highest_usn)
178 # Get the remaining blocks of data
179 while not self.replication_complete():
182 # Check we still receive all the objects we're expecting
183 self.assert_expected_data(expected_dn_list)
185 def is_parent_known(self, dn, known_dn_list):
187 Returns True if the parent of the dn specified is in known_dn_list
190 # we can sometimes get system objects like the RID Manager returned.
191 # Ignore anything that is not under the test OU we created
192 if self.ou not in dn:
195 # Remove the child portion from the name to get the parent's DN
196 name_substrings = dn.split(",")
197 del name_substrings[0]
199 parent_dn = ",".join(name_substrings)
201 # check either this object is a parent (it's parent is the top-level
202 # test object), or its parent has been seen previously
203 return parent_dn == self.ou or parent_dn in known_dn_list
205 def _repl_send_request(self, get_anc=False, get_tgt=False):
206 """Sends a GetNCChanges request for the next block of replication data."""
208 # we're just trying to mimic regular client behaviour here, so just
209 # use the highwatermark in the last response we received
211 highwatermark = self.last_ctr.new_highwatermark
212 uptodateness_vector = self.last_ctr.uptodateness_vector
214 # this is the first replication chunk
216 uptodateness_vector = None
218 # Ask for the next block of replication data
219 replica_flags = drsuapi.DRSUAPI_DRS_WRIT_REP
223 replica_flags = drsuapi.DRSUAPI_DRS_WRIT_REP | drsuapi.DRSUAPI_DRS_GET_ANC
224 self.used_get_anc = True
227 more_flags = drsuapi.DRSUAPI_DRS_GET_TGT
228 self.used_get_tgt = True
230 # return the response from the DC
231 return self._get_replication(replica_flags,
232 max_objects=self.max_objects,
233 highwatermark=highwatermark,
234 uptodateness_vector=uptodateness_vector,
235 more_flags=more_flags)
237 def repl_get_next(self, get_anc=False, get_tgt=False, assert_links=False):
239 Requests the next block of replication data. This tries to simulate
240 client behaviour - if we receive a replicated object that we don't know
241 the parent of, then re-request the block with the GET_ANC flag set.
242 If we don't know the target object for a linked attribute, then
243 re-request with GET_TGT.
246 # send a request to the DC and get the response
247 ctr6 = self._repl_send_request(get_anc=get_anc, get_tgt=get_tgt)
249 # extract the object DNs and their GUIDs from the response
250 rxd_dn_list = self._get_ctr6_dn_list(ctr6)
251 rxd_guid_list = self._get_ctr6_object_guids(ctr6)
253 # we'll add new objects as we discover them, so take a copy of the
254 # ones we already know about, so we can modify these lists safely
255 known_objects = self.rxd_dn_list[:]
256 known_guids = self.rxd_guids[:]
258 # check that we know the parent for every object received
259 for i in range(0, len(rxd_dn_list)):
262 guid = rxd_guid_list[i]
264 if self.is_parent_known(dn, known_objects):
266 # the new DN is now known so add it to the list.
267 # It may be the parent of another child in this block
268 known_objects.append(dn)
269 known_guids.append(guid)
271 # If we've already set the GET_ANC flag then it should mean
272 # we receive the parents before the child
273 self.assertFalse(get_anc, "Unknown parent for object %s" % dn)
275 print("Unknown parent for %s - try GET_ANC" % dn)
277 # try the same thing again with the GET_ANC flag set this time
278 return self.repl_get_next(get_anc=True, get_tgt=get_tgt,
279 assert_links=assert_links)
281 # check we know about references to any objects in the linked attritbutes
282 received_links = self._get_ctr6_links(ctr6)
284 # This is so that older versions of Samba fail - we want the links to be
285 # sent roughly with the objects, rather than getting all links at the end
287 self.assertTrue(len(received_links) > 0,
288 "Links were expected in the GetNCChanges response")
290 for link in received_links:
292 # check the source object is known (Windows can actually send links
293 # where we don't know the source object yet). Samba shouldn't ever
294 # hit this case because it gets the links based on the source
295 if link.identifier not in known_guids:
297 # If we've already set the GET_ANC flag then it should mean
298 # this case doesn't happen
299 self.assertFalse(get_anc, "Unknown source object for GUID %s"
302 print("Unknown source GUID %s - try GET_ANC" % link.identifier)
304 # try the same thing again with the GET_ANC flag set this time
305 return self.repl_get_next(get_anc=True, get_tgt=get_tgt,
306 assert_links=assert_links)
308 # check we know the target object
309 if link.targetGUID not in known_guids:
311 # If we've already set the GET_TGT flag then we should have
312 # already received any objects we need to know about
313 self.assertFalse(get_tgt, "Unknown linked target for object %s"
316 print("Unknown target for %s - try GET_TGT" % link.targetDN)
318 # try the same thing again with the GET_TGT flag set this time
319 return self.repl_get_next(get_anc=get_anc, get_tgt=True,
320 assert_links=assert_links)
322 # store the last successful result so we know what HWM to request next
325 # store the objects, GUIDs, and links we received
326 self.rxd_dn_list += self._get_ctr6_dn_list(ctr6)
327 self.rxd_links += self._get_ctr6_links(ctr6)
328 self.rxd_guids += self._get_ctr6_object_guids(ctr6)
332 def replication_complete(self):
333 """Returns True if the current/last replication cycle is complete"""
335 if self.last_ctr is None or self.last_ctr.more_data:
340 def test_repl_integrity_get_anc(self):
342 Modify the parent objects being replicated while the replication is still
343 in progress (using GET_ANC) and check that no object loss occurs.
346 # Note that GET_ANC behaviour varies between Windows and Samba.
347 # On Samba GET_ANC results in the replication restarting from the very
348 # beginning. After that, Samba remembers GET_ANC and also sends the
349 # parents in subsequent requests (regardless of whether GET_ANC is
350 # specified in the later request).
351 # Windows only sends the parents if GET_ANC was specified in the last
352 # request. It will also resend a parent, even if it's already sent the
353 # parent in a previous response (whereas Samba doesn't).
355 # Create a small block of 50 parents, each with 2 children (A and B)
356 # This is so that we receive some children in the first block, so we
357 # can resend with GET_ANC before we learn too many parents
359 expected_dn_list = self.create_object_range(0, 50, prefix="parent",
361 parent_list=parent_dn_list)
363 # create the remaining parents and children
364 expected_dn_list += self.create_object_range(50, 150, prefix="parent",
366 parent_list=parent_dn_list)
368 # We've now got objects in the following order:
369 # [50 parents][100 children][100 parents][200 children]
371 # Modify the first parent so that it's now ordered last by USN
372 # This means we set the GET_ANC flag pretty much straight away
373 # because we receive the first child before the first parent
374 self.modify_object(parent_dn_list[0], "displayName", "OU0")
376 # modify a later block of parents so they also get reordered
377 for x in range(50, 100):
378 self.modify_object(parent_dn_list[x], "displayName", "OU%d" % x)
380 # Get the first block of objects - this should resend the request with
381 # GET_ANC set because we won't know about the first child's parent.
382 # On samba GET_ANC essentially starts the sync from scratch again, so
383 # we get this over with early before we learn too many parents
386 # modify the last chunk of parents. They should now have a USN higher
387 # than the highwater-mark for the replication cycle
388 for x in range(100, 150):
389 self.modify_object(parent_dn_list[x], "displayName", "OU%d" % x)
391 # Get the remaining blocks of data - this will resend the request with
392 # GET_ANC if it encounters an object it doesn't have the parent for.
393 while not self.replication_complete():
396 # The way the test objects have been created should force
397 # self.repl_get_next() to use the GET_ANC flag. If this doesn't
398 # actually happen, then the test isn't doing its job properly
399 self.assertTrue(self.used_get_anc,
400 "Test didn't use the GET_ANC flag as expected")
402 # Check we get all the objects we're expecting
403 self.assert_expected_data(expected_dn_list)
405 def assert_expected_links(self, objects_with_links, link_attr="managedBy"):
407 Asserts that a GetNCChanges response contains any expected links
408 for the objects it contains.
410 received_links = self.rxd_links
412 num_expected = len(objects_with_links)
414 self.assertTrue(len(received_links) == num_expected,
415 "Received %d links but expected %d"
416 %(len(received_links), num_expected))
418 for dn in objects_with_links:
419 self.assert_object_has_link(dn, link_attr, received_links)
421 def assert_object_has_link(self, dn, link_attr, received_links):
423 Queries the object in the DB and asserts there is a link in the
424 GetNCChanges response that matches.
427 # Look up the link attribute in the DB
428 # The extended_dn option will dump the GUID info for the link
429 # attribute (as a hex blob)
430 res = self.test_ldb_dc.search(ldb.Dn(self.test_ldb_dc, dn), attrs=[link_attr],
431 controls=['extended_dn:1:0'], scope=ldb.SCOPE_BASE)
433 # We didn't find the expected link attribute in the DB for the object.
434 # Something has gone wrong somewhere...
435 self.assertTrue(link_attr in res[0], "%s in DB doesn't have attribute %s"
438 # find the received link in the list and assert that the target and
439 # source GUIDs match what's in the DB
440 for val in res[0][link_attr]:
441 # Work out the expected source and target GUIDs for the DB link
442 target_dn = ldb.Dn(self.test_ldb_dc, val)
443 targetGUID_blob = target_dn.get_extended_component("GUID")
444 sourceGUID_blob = res[0].dn.get_extended_component("GUID")
448 for link in received_links:
449 if link.selfGUID_blob == sourceGUID_blob and \
450 link.targetGUID_blob == targetGUID_blob:
455 print("Link %s --> %s" %(dn[:25], link.targetDN[:25]))
458 self.assertTrue(found, "Did not receive expected link for DN %s" % dn)
460 def test_repl_get_tgt(self):
462 Creates a scenario where we should receive the linked attribute before
463 we know about the target object, and therefore need to use GET_TGT.
464 Note: Samba currently avoids this problem by sending all its links last
467 # create the test objects
468 reportees = self.create_object_range(0, 100, prefix="reportee")
469 managers = self.create_object_range(0, 100, prefix="manager")
470 all_objects = managers + reportees
471 expected_links = reportees
473 # add a link attribute to each reportee object that points to the
474 # corresponding manager object as the target
475 for i in range(0, 100):
476 self.modify_object(reportees[i], "managedBy", managers[i])
478 # touch the managers (the link-target objects) again to make sure the
479 # reportees (link source objects) get returned first by the replication
480 for i in range(0, 100):
481 self.modify_object(managers[i], "displayName", "OU%d" % i)
483 links_expected = True
485 # Get all the replication data - this code should resend the requests
487 while not self.replication_complete():
489 # get the next block of replication data (this sets GET_TGT if needed)
490 self.repl_get_next(assert_links=links_expected)
491 links_expected = len(self.rxd_links) < len(expected_links)
493 # The way the test objects have been created should force
494 # self.repl_get_next() to use the GET_TGT flag. If this doesn't
495 # actually happen, then the test isn't doing its job properly
496 self.assertTrue(self.used_get_tgt,
497 "Test didn't use the GET_TGT flag as expected")
499 # Check we get all the objects we're expecting
500 self.assert_expected_data(all_objects)
502 # Check we received links for all the reportees
503 self.assert_expected_links(expected_links)
505 def test_repl_get_tgt_chain(self):
507 Tests the behaviour of GET_TGT with a more complicated scenario.
508 Here we create a chain of objects linked together, so if we follow
509 the link target, then we'd traverse ~200 objects each time.
512 # create the test objects
513 objectsA = self.create_object_range(0, 100, prefix="AAA")
514 objectsB = self.create_object_range(0, 100, prefix="BBB")
515 objectsC = self.create_object_range(0, 100, prefix="CCC")
517 # create a complex set of object links:
518 # A0-->B0-->C1-->B2-->C3-->B4-->and so on...
519 # Basically each object-A should link to a circular chain of 200 B/C
520 # objects. We create the links in separate chunks here, as it makes it
521 # clearer what happens with the USN (links on Windows have their own
522 # USN, so this approach means the A->B/B->C links aren't interleaved)
523 for i in range(0, 100):
524 self.modify_object(objectsA[i], "managedBy", objectsB[i])
526 for i in range(0, 100):
527 self.modify_object(objectsB[i], "managedBy", objectsC[(i + 1) % 100])
529 for i in range(0, 100):
530 self.modify_object(objectsC[i], "managedBy", objectsB[(i + 1) % 100])
532 all_objects = objectsA + objectsB + objectsC
533 expected_links = all_objects
535 # the default order the objects now get returned in should be:
536 # [A0-A99][B0-B99][C0-C99]
538 links_expected = True
540 # Get all the replication data - this code should resend the requests
542 while not self.replication_complete():
544 # get the next block of replication data (this sets GET_TGT if needed)
545 self.repl_get_next(assert_links=links_expected)
546 links_expected = len(self.rxd_links) < len(expected_links)
548 # The way the test objects have been created should force
549 # self.repl_get_next() to use the GET_TGT flag. If this doesn't
550 # actually happen, then the test isn't doing its job properly
551 self.assertTrue(self.used_get_tgt,
552 "Test didn't use the GET_TGT flag as expected")
554 # Check we get all the objects we're expecting
555 self.assert_expected_data(all_objects)
557 # Check we received links for all the reportees
558 self.assert_expected_links(expected_links)
560 def test_repl_get_anc_link_attr(self):
562 A basic GET_ANC test where the parents have linked attributes
565 # Create a block of 100 parents and 100 children
567 expected_dn_list = self.create_object_range(0, 100, prefix="parent",
569 parent_list=parent_dn_list)
571 # Add links from the parents to the children
572 for x in range(0, 100):
573 self.modify_object(parent_dn_list[x], "managedBy", expected_dn_list[x + 100])
575 # add some filler objects at the end. This allows us to easily see
576 # which chunk the links get sent in
577 expected_dn_list += self.create_object_range(0, 100, prefix="filler")
579 # We've now got objects in the following order:
580 # [100 x children][100 x parents][100 x filler]
582 # Get the replication data - because the block of children come first,
583 # this should retry the request with GET_ANC
584 while not self.replication_complete():
587 self.assertTrue(self.used_get_anc,
588 "Test didn't use the GET_ANC flag as expected")
590 # Check we get all the objects we're expecting
591 self.assert_expected_data(expected_dn_list)
593 # Check we received links for all the parents
594 self.assert_expected_links(parent_dn_list)