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
|
import uuid
import time
from typing import Optional, Dict, Any
from multiprocessing.pool import ThreadPool
import json
from azure.cosmos import exceptions, PartitionKey
class ConflictWorker(object):
def __init__(self, database_name, basic_collection_name, manual_collection_name, lww_collection_name, udp_collection_name):
self.clients = []
self.basic_collection_link = "dbs/" + database_name + "/colls/" + basic_collection_name
self.manual_collection_link = "dbs/" + database_name + "/colls/" + manual_collection_name
self.lww_collection_link = "dbs/" + database_name + "/colls/" + lww_collection_name
self.udp_collection_link = "dbs/" + database_name + "/colls/" + udp_collection_name
self.database_name = database_name
self.basic_collection_name = basic_collection_name
self.manual_collection_name = manual_collection_name
self.lww_collection_name = lww_collection_name
self.udp_collection_name = udp_collection_name
def add_client(self, client):
self.clients.append(client)
def initialize_async(self):
create_client = self.clients[0]
database = create_client.create_database_if_not_exists(self.database_name)
basic_collection = self.create_document_collection(database, self.basic_collection_name, None)
manual_resolution_policy = {'mode': 'Custom'}
manual_collection = self.create_document_collection(database, self.manual_collection_name, manual_resolution_policy)
lww_conflict_resolution_policy = {'mode': 'LastWriterWins', 'conflictResolutionPath': '/regionId'}
lww_collection = self.create_document_collection(database, self.lww_collection_name, lww_conflict_resolution_policy)
udp_custom_resolution_policy = {'mode': 'Custom' }
udp_collection = self.create_document_collection(database,self.udp_collection_name, udp_custom_resolution_policy)
lww_sproc = {'id':'resolver',
'body': "function resolver(incomingRecord, existingRecord, isTombstone, conflictingRecords) {\r\n" +
" var collection = getContext().getCollection();\r\n" +
"\r\n" +
" if (!incomingRecord) {\r\n" +
" if (existingRecord) {\r\n" +
"\r\n" +
" collection.deleteDocument(existingRecord._self, {}, function(err, responseOptions) {\r\n" +
" if (err) throw err;\r\n" +
" });\r\n" +
" }\r\n" +
" } else if (isTombstone) {\r\n" +
" // delete always wins.\r\n" +
" } else {\r\n" +
" var documentToUse = incomingRecord;\r\n" +
"\r\n" +
" if (existingRecord) {\r\n" +
" if (documentToUse.regionId < existingRecord.regionId) {\r\n" +
" documentToUse = existingRecord;\r\n" +
" }\r\n" +
" }\r\n" +
"\r\n" +
" var i;\r\n" +
" for (i = 0; i < conflictingRecords.length; i++) {\r\n" +
" if (documentToUse.regionId < conflictingRecords[i].regionId) {\r\n" +
" documentToUse = conflictingRecords[i];\r\n" +
" }\r\n" +
" }\r\n" +
"\r\n" +
" tryDelete(conflictingRecords, incomingRecord, existingRecord, documentToUse);\r\n" +
" }\r\n" +
"\r\n" +
" function tryDelete(documents, incoming, existing, documentToInsert) {\r\n" +
" if (documents.length > 0) {\r\n" +
" collection.deleteDocument(documents[0]._self, {}, function(err, responseOptions) {\r\n" +
" if (err) throw err;\r\n" +
"\r\n" +
" documents.shift();\r\n" +
" tryDelete(documents, incoming, existing, documentToInsert);\r\n" +
" });\r\n" +
" } else if (existing) {\r\n" +
" collection.replaceDocument(existing._self, documentToInsert,\r\n" +
" function(err, documentCreated) {\r\n" +
" if (err) throw err;\r\n" +
" });\r\n" +
" } else {\r\n" +
" collection.createDocument(collection.getSelfLink(), documentToInsert,\r\n" +
" function(err, documentCreated) {\r\n" +
" if (err) throw err;\r\n" +
" });\r\n" +
" }\r\n" +
" }\r\n" +
"}"
}
try:
udp_collection.scripts.create_stored_procedure(lww_sproc)
except exceptions.CosmosResourceExistsError:
return
def create_document_collection (self, database, collection_id, conflict_resolution_policy):
read_collection = database.create_container_if_not_exists(id=collection_id, partition_key=PartitionKey(path="/id"),
conflict_resolution_policy=conflict_resolution_policy)
return read_collection
def run_manual_conflict_async(self):
print("\r\nInsert Conflict\r\n")
self.run_insert_conflict_on_manual_async()
print("\r\nUpdate Conflict\r\n")
self.run_update_conflict_on_manual_async()
print("\r\nDelete Conflict\r\n")
self.run_delete_conflict_on_manual_async()
def run_LWW_conflict_async(self):
print("\r\nInsert Conflict\r\n")
self.run_insert_conflict_on_LWW_async()
print("\r\nUpdate Conflict\r\n")
self.run_update_conflict_on_LWW_async()
print("\r\nDelete Conflict\r\n")
self.run_delete_conflict_on_LWW_async()
def run_UDP_async(self):
print("\r\nInsert Conflict\r\n")
self.run_insert_conflict_on_UDP_async()
print("\r\nUpdate Conflict\r\n")
self.run_update_conflict_on_UDP_async()
print("\r\nDelete Conflict\r\n")
self.run_delete_conflict_on_UDP_async()
def run_insert_conflict_on_manual_async(self):
while True:
print("1) Performing conflicting insert across %d regions on %s" % (len(self.clients), self.manual_collection_link))
id = str(uuid.uuid4())
i = 0
pool = ThreadPool(processes = len(self.clients))
insert_document_futures = []
for client in self.clients:
conflict_document = {'id': id, 'regionId': i, 'regionEndpoint': client.client_connection.ReadEndpoint}
insert_document_future = pool.apply_async(self.try_insert_document, (client, self.manual_collection_name, conflict_document))
insert_document_futures.append(insert_document_future)
i += 1
number_of_conflicts = -1
inserted_documents = []
for insert_document_future in insert_document_futures:
inserted_document = insert_document_future.get()
inserted_documents.append(inserted_document)
if inserted_document:
number_of_conflicts += 1
if number_of_conflicts > 0:
print("2) Caused %d insert conflicts, verifying conflict resolution" % number_of_conflicts)
time.sleep(2) #allow conflicts resolution to propagate
for conflicting_insert in inserted_documents:
if conflicting_insert:
self.validate_manual_conflict_async(self.clients, conflicting_insert)
break
else:
print("Retrying insert to induce conflicts")
def run_update_conflict_on_manual_async(self):
while True:
id = str(uuid.uuid4())
conflict_document_for_insertion = {'id': id, 'regionId': 0, 'regionEndpoint': self.clients[0].client_connection.ReadEndpoint}
conflict_document_for_insertion = self.try_insert_document(self.clients[0], self.manual_collection_name, conflict_document_for_insertion)
time.sleep(1) #1 Second for write to sync.
print("1) Performing conflicting update across %d regions on %s" % (len(self.clients), self.manual_collection_link))
i = 0
access_condition = {'condition': 'IfMatch', 'type': conflict_document_for_insertion['_etag']}
pool = ThreadPool(processes = len(self.clients))
update_document_futures = []
for client in self.clients:
database = client.get_database_client(self.database_name)
container = database.get_container_client(self.manual_collection_name)
conflict_document = {'id': id, 'regionId': i, 'regionEndpoint': client.client_connection.ReadEndpoint}
update_document_future = pool.apply_async(self.try_update_document, (container, conflict_document, access_condition))
update_document_futures.append(update_document_future)
i += 1
number_of_conflicts = -1
update_documents = []
for update_document_future in update_document_futures:
update_document = update_document_future.get()
update_documents.append(update_document)
if update_document:
number_of_conflicts += 1
if number_of_conflicts > 0:
print("2) Caused %d update conflicts, verifying conflict resolution" % number_of_conflicts)
time.sleep(2) #allow conflicts resolution to propagate
for conflicting_update in update_documents:
if conflicting_update:
self.validate_manual_conflict_async(self.clients, conflicting_update)
break
else:
print("Retrying update to induce conflicts")
def run_delete_conflict_on_manual_async(self):
while True:
id = str(uuid.uuid4())
conflict_document_for_insertion = {'id': id, 'regionId': 0, 'regionEndpoint': self.clients[0].client_connection.ReadEndpoint}
conflict_document_for_insertion = self.try_insert_document(self.clients[0], self.manual_collection_name, conflict_document_for_insertion)
time.sleep(1) #1 Second for write to sync.
print("1) Performing conflicting delete across %d regions on %s" % (len(self.clients), self.manual_collection_link))
i = 0
access_condition = {'condition': 'IfMatch', 'type': conflict_document_for_insertion['_etag']}
pool = ThreadPool(processes = len(self.clients))
delete_document_futures = []
for client in self.clients:
database = client.get_database_client(self.database_name)
container = database.get_container_client(self.manual_collection_name)
conflict_document = conflict_document_for_insertion.copy()
conflict_document['regionId'] = i
conflict_document['regionEndpoint'] = client.client_connection.ReadEndpoint
delete_document_future = pool.apply_async(self.try_delete_document, (container, conflict_document, access_condition))
delete_document_futures.append(delete_document_future)
i += 1
number_of_conflicts = -1
delete_documents = []
for delete_document_future in delete_document_futures:
delete_document = delete_document_future.get()
delete_documents.append(delete_document)
if delete_document:
number_of_conflicts += 1
if number_of_conflicts > 0:
print("2) Caused %d delete conflicts, verifying conflict resolution" % number_of_conflicts)
# Conflicts will not be registered in conflict feed for delete-delete
# operations. The 'hasDeleteConflict' part of LWW validation can be reused for
# manual conflict resolution policy validation of delete-delete conflicts.
self.validate_LWW_async(self.clients, delete_documents, True)
break
else:
print("Retrying delete to induce conflicts")
def run_insert_conflict_on_LWW_async(self):
while True:
print("1) Performing conflicting insert across %d regions on %s" % (len(self.clients), self.lww_collection_link))
id = str(uuid.uuid4())
i = 0
pool = ThreadPool(processes = len(self.clients))
insert_document_futures = []
for client in self.clients:
conflict_document = {'id': id, 'regionId': i, 'regionEndpoint': client.client_connection.ReadEndpoint}
insert_document_future = pool.apply_async(self.try_insert_document, (client, self.lww_collection_name, conflict_document))
insert_document_futures.append(insert_document_future)
i += 1
inserted_documents = []
for insert_document_future in insert_document_futures:
inserted_document = insert_document_future.get()
if inserted_document:
inserted_documents.append(inserted_document)
if len(inserted_documents) > 1:
print("2) Caused %d insert conflicts, verifying conflict resolution" % len(inserted_documents))
time.sleep(2) #allow conflicts resolution to propagate
self.validate_LWW_async(self.clients, inserted_documents, False)
break
else:
print("Retrying insert to induce conflicts")
def run_update_conflict_on_LWW_async(self):
while True:
id = str(uuid.uuid4())
conflict_document_for_insertion = {'id': id, 'regionId': 0, 'regionEndpoint': self.clients[0].client_connection.ReadEndpoint}
conflict_document_for_insertion = self.try_insert_document(self.clients[0], self.lww_collection_name, conflict_document_for_insertion)
time.sleep(1) #1 Second for write to sync.
print("1) Performing conflicting update across %d regions on %s" % (len(self.clients), self.lww_collection_link))
i = 0
access_condition = {'condition': 'IfMatch', 'type': conflict_document_for_insertion['_etag']}
pool = ThreadPool(processes = len(self.clients))
update_document_futures = []
for client in self.clients:
database = client.get_database_client(self.database_name)
container = database.get_container_client(self.lww_collection_name)
conflict_document = {'id': id, 'regionId': i, 'regionEndpoint': client.client_connection.ReadEndpoint}
update_document_future = pool.apply_async(self.try_update_document, (container, conflict_document, access_condition))
update_document_futures.append(update_document_future)
i += 1
update_documents = []
for update_document_future in update_document_futures:
update_document = update_document_future.get()
if update_document:
update_documents.append(update_document)
if len(update_documents) > 1:
print("2) Caused %d update conflicts, verifying conflict resolution" % len(update_documents))
time.sleep(2) #allow conflicts resolution to propagate
self.validate_LWW_async(self.clients, update_documents, False)
break
else:
print("Retrying update to induce conflicts")
def run_delete_conflict_on_LWW_async(self):
while True:
id = str(uuid.uuid4())
conflict_document_for_insertion = {'id': id, 'regionId': 0, 'regionEndpoint': self.clients[0].client_connection.ReadEndpoint}
conflict_document_for_insertion = self.try_insert_document(self.clients[0], self.lww_collection_name, conflict_document_for_insertion)
time.sleep(1) #1 Second for write to sync.
print("1) Performing conflicting update/delete across 3 regions on %s" % self.lww_collection_link)
i = 0
access_condition = {'condition': 'IfMatch', 'type': conflict_document_for_insertion['_etag']}
pool = ThreadPool(processes = len(self.clients))
delete_document_futures = []
for client in self.clients:
database = client.get_database_client(self.database_name)
container = database.get_container_client(self.lww_collection_name)
conflict_document = {'id': id, 'regionId': i, 'regionEndpoint': client.client_connection.ReadEndpoint}
delete_document_future = pool.apply_async(self.try_update_or_delete_document, (container, conflict_document, access_condition))
delete_document_futures.append(delete_document_future)
i += 1
delete_documents = []
for delete_document_future in delete_document_futures:
delete_document = delete_document_future.get()
if delete_document:
delete_documents.append(delete_document)
if len(delete_documents) > 1:
print("2) Caused %d delete conflicts, verifying conflict resolution" % len(delete_documents))
time.sleep(2) #allow conflicts resolution to propagate
# Delete should always win. irrespective of UDP.
self.validate_LWW_async(self.clients, delete_documents, True)
break
else:
print("Retrying update/delete to induce conflicts")
def run_insert_conflict_on_UDP_async(self):
while True:
print("1) Performing conflicting insert across 3 regions on %s" % self.udp_collection_link)
id = str(uuid.uuid4())
i = 0
pool = ThreadPool(processes = len(self.clients))
insert_document_futures = []
for client in self.clients:
conflict_document = {'id': id, 'regionId': i, 'regionEndpoint': client.client_connection.ReadEndpoint}
insert_document_future = pool.apply_async(self.try_insert_document, (client, self.udp_collection_name, conflict_document))
insert_document_futures.append(insert_document_future)
i += 1
inserted_documents = []
for insert_document_future in insert_document_futures:
inserted_document = insert_document_future.get()
if inserted_document:
inserted_documents.append(inserted_document)
if len(inserted_documents) > 1:
print("2) Caused %d insert conflicts, verifying conflict resolution" % len(inserted_documents))
time.sleep(2) #allow conflicts resolution to propagate
self.validate_UDP_async(self.clients, inserted_documents, False)
break
else:
print("Retrying insert to induce conflicts")
def run_update_conflict_on_UDP_async(self):
while True:
id = str(uuid.uuid4())
conflict_document_for_insertion = {'id': id, 'regionId': 0, 'regionEndpoint': self.clients[0].client_connection.ReadEndpoint}
conflict_document_for_insertion = self.try_insert_document(self.clients[0], self.udp_collection_name, conflict_document_for_insertion)
time.sleep(1) #1 Second for write to sync.
print("1) Performing conflicting update across %d regions on %s" % (len(self.clients), self.udp_collection_link))
i = 0
access_condition = {'condition': 'IfMatch', 'type': conflict_document_for_insertion['_etag']}
pool = ThreadPool(processes = len(self.clients))
update_document_futures = []
for client in self.clients:
database = client.get_database_client(self.database_name)
container = database.get_container_client(self.udp_collection_name)
conflict_document = {'id': id, 'regionId': i, 'regionEndpoint': client.client_connection.ReadEndpoint}
update_document_future = pool.apply_async(self.try_update_document, (container, conflict_document, access_condition))
update_document_futures.append(update_document_future)
i += 1
update_documents = []
for update_document_future in update_document_futures:
update_document = update_document_future.get()
if update_document:
update_documents.append(update_document)
if len(update_documents) > 1:
print("2) Caused %d update conflicts, verifying conflict resolution" % len(update_documents))
time.sleep(2) #allow conflicts resolution to propagate
self.validate_UDP_async(self.clients, update_documents, False)
break
else:
print("Retrying update to induce conflicts")
def run_delete_conflict_on_UDP_async(self):
while True:
id = str(uuid.uuid4())
conflict_document_for_insertion = {'id': id, 'regionId': 0, 'regionEndpoint': self.clients[0].client_connection.ReadEndpoint}
conflict_document_for_insertion = self.try_insert_document(self.clients[0], self.udp_collection_name, conflict_document_for_insertion)
time.sleep(1) #1 Second for write to sync.
print("1) Performing conflicting update/delete across 3 regions on %s" % self.udp_collection_link)
i = 0
access_condition = {'condition': 'IfMatch', 'type': conflict_document_for_insertion['_etag']}
pool = ThreadPool(processes = len(self.clients))
delete_document_futures = []
for client in self.clients:
database = client.get_database_client(self.database_name)
container = database.get_container_client(self.udp_collection_name)
conflict_document = {'id': id, 'regionId': i, 'regionEndpoint': client.client_connection.ReadEndpoint}
delete_document_future = pool.apply_async(self.try_update_or_delete_document, (container, conflict_document, access_condition))
delete_document_futures.append(delete_document_future)
i += 1
delete_documents = []
for delete_document_future in delete_document_futures:
delete_document = delete_document_future.get()
if delete_document:
delete_documents.append(delete_document)
if len(delete_documents) > 1:
print("2) Caused %d delete conflicts, verifying conflict resolution" % len(delete_documents))
time.sleep(2) #allow conflicts resolution to propagate
# Delete should always win. irrespective of UDP.
self.validate_UDP_async(self.clients, delete_documents, True)
break
else:
print("Retrying update/delete to induce conflicts")
def try_insert_document(self, client, collection_name, document):
try:
database = client.get_database_client(self.database_name)
container = database.get_container_client(collection_name)
return container.create_item(document)
except exceptions.CosmosResourceExistsError:
print("Error found trying to insert document.")
return None
def try_update_document(self, container, document, access_condition):
try:
return container.replace_item(document['id'], document, access_condition=access_condition)
except (exceptions.CosmosResourceNotFoundError, exceptions.CosmosAccessConditionFailedError):
# Lost synchronously or no document yet. No conflict is induced.
return None
def try_delete_document(self, container, document, access_condition):
try:
container.delete_item(document['id'], document['id'], access_condition=access_condition)
return document
except (exceptions.CosmosResourceNotFoundError, exceptions.CosmosAccessConditionFailedError):
#Lost synchronously. No conflict is induced.
return None
def try_update_or_delete_document(self, container, conflict_document, access_condition):
if int(conflict_document['regionId']) % 2 == 1:
#We delete from region 1, even though region 2 always win.
return self.try_delete_document(container, conflict_document, access_condition)
else:
return self.try_update_document(container, conflict_document, access_condition)
def validate_manual_conflict_async(self, clients, conflict_document):
conflict_exists = False
for client in clients:
conflict_exists = self.validate_manual_conflict_async_internal(client, conflict_document)
if conflict_exists:
self.delete_conflict_async(conflict_document)
def validate_manual_conflict_async_internal(self, client, conflict_document):
database = client.get_database_client(self.database_name)
container = database.get_container_client(self.manual_collection_name)
while True:
conflicts_iterator = iter(container.list_conflicts())
conflict = next(conflicts_iterator, None)
while conflict:
if conflict['operationType'] != 'delete':
conflict_document_content = json.loads(conflict['content'])
if conflict_document['id'] == conflict_document_content['id']:
if ((conflict_document['_rid'] == conflict_document_content['_rid']) and
(conflict_document['_etag'] == conflict_document_content['_etag'])):
print("Document from Region %d lost conflict @ %s" %
(int(conflict_document['regionId']), client.client_connection.ReadEndpoint))
return True
else:
#Checking whether this is the winner.
winner_document = container.read_item(conflict_document['id'], conflict_document['id'])
print("Document from Region %d won the conflict @ %s" %
(int(winner_document['regionId']), client.client_connection.ReadEndpoint))
return False
else:
if conflict['resourceId'] == conflict_document['_rid']:
print("Delete conflict found @ %s" % client.client_connection.ReadEndpoint)
return False
conflict = next(conflicts_iterator, None)
self.trace_error("Document %s is not found in conflict feed @ %s, retrying" %
(conflict_document['id'], client.client_connection.ReadEndpoint))
time.sleep(0.5)
def delete_conflict_async(self, conflict_document):
del_client = self.clients[0]
database = del_client.get_database_client(self.database_name)
container = database.get_container_client(self.manual_collection_name)
conflicts_iterator = iter(container.list_conflicts())
conflict = next(conflicts_iterator, None)
while conflict:
conflict_content = json.loads(conflict['content'])
if conflict['operationType'] != 'delete':
if ((conflict_content['_rid'] == conflict_document['_rid']) and
(conflict_content['_etag'] == conflict_document['_etag'])):
print("Deleting manual conflict %s from region %d" %
(conflict['resourceId'],
int(conflict_content['regionId'])))
container.delete_conflict(conflict['id'], conflict_content['id'])
elif conflict['resourceId'] == conflict_document['_rid']:
print("Deleting manual conflict %s from region %d" %
(conflict['resourceId'],
int(conflict_document['regionId'])))
container.delete_conflict(conflict['id'], conflict_content['id'])
conflict = next(conflicts_iterator, None)
def validate_LWW_async(self, clients, conflict_document, has_delete_conflict):
for client in clients:
self.validate_LWW_async_internal(client, conflict_document, has_delete_conflict)
def validate_LWW_async_internal(self, client, conflict_document, has_delete_conflict):
database = client.get_database_client(self.database_name)
container = database.get_container_client(self.lww_collection_name)
conflicts_iterator = iter(container.list_conflicts())
conflict = next(conflicts_iterator, None)
conflict_count = 0
while conflict:
conflict_count += 1
conflict = next(conflicts_iterator, None)
if conflict_count > 0:
self.trace_error("Found %d conflicts in the lww collection" % conflict_count)
return
if has_delete_conflict:
while True:
try:
container.read_item(conflict_document[0]['id'], conflict_document[0]['id'])
self.trace_error("Delete conflict for document %s didn't win @ %s" %
(conflict_document[0]['id'], client.client_connection.ReadEndpoint))
time.sleep(0.5)
except exceptions.CosmosResourceNotFoundError:
print("Delete conflict won @ %s" % client.client_connection.ReadEndpoint)
return
except exceptions.CosmosHttpResponseError:
self.trace_error("Delete conflict for document %s didn't win @ %s" %
(conflict_document[0]['id'], client.client_connection.ReadEndpoint))
time.sleep(0.5)
winner_document: Optional[Dict[str, Any]] = None
for document in conflict_document:
if winner_document is None or int(winner_document['regionId']) <= int(document['regionId']):
winner_document = document
if winner_document is None:
print("Winner document not found.")
return
print("Document from region %d should be the winner" % int(winner_document['regionId']))
while True:
try:
existing_document = container.read_item(winner_document['id'], winner_document['id'])
if int(existing_document['regionId']) == int(winner_document['regionId']):
print("Winner document from region %d found at %s" %
(int(existing_document['regionId']), client.client_connection.ReadEndpoint))
break
else:
self.trace_error("Winning document version from region %d is not found @ %s, retrying..." %
(int(winner_document["regionId"]), client.client_connection.WriteEndpoint))
time.sleep(0.5)
except exceptions.AzureError as e:
self.trace_error("Winner document from region %d is not found @ %s, retrying..." %
(int(winner_document["regionId"]), client.client_connection.WriteEndpoint))
time.sleep(0.5)
def validate_UDP_async(self, clients, conflict_document, has_delete_conflict):
for client in clients:
self.validate_UDP_async_internal(client, conflict_document, has_delete_conflict)
def validate_UDP_async_internal(self, client, conflict_document, has_delete_conflict):
database = client.get_database_client(self.database_name)
container = database.get_container_client(self.udp_collection_name)
conflicts_iterator = iter(container.list_conflicts())
conflict = next(conflicts_iterator, None)
conflict_count = 0
while conflict:
conflict_count += 1
conflict = next(conflicts_iterator, None)
if conflict_count > 0:
self.trace_error("Found %d conflicts in the udp collection" % conflict_count)
return
if has_delete_conflict:
while True:
try:
container.read_item(conflict_document[0]['id'], conflict_document[0]['id'])
self.trace_error("Delete conflict for document %s didn't win @ %s" %
(conflict_document[0]['id'], client.client_connection.ReadEndpoint))
time.sleep(0.5)
except exceptions.CosmosResourceNotFoundError:
print("Delete conflict won @ %s" % client.client_connection.ReadEndpoint)
return
except exceptions.CosmosHttpResponseError:
self.trace_error("Delete conflict for document %s didn't win @ %s" %
(conflict_document[0]['id'], client.client_connection.ReadEndpoint))
time.sleep(0.5)
winner_document: Optional[Dict[str, Any]] = None
for document in conflict_document:
if winner_document is None or int(winner_document['regionId']) <= int(document['regionId']):
winner_document = document
if winner_document is None:
print("Winner document not found.")
return
print("Document from region %d should be the winner" % int(winner_document['regionId']))
while True:
try:
existing_document = container.read_item(winner_document['id'], winner_document['id'])
if int(existing_document['regionId']) == int(winner_document['regionId']):
print("Winner document from region %d found at %s" %
(int(existing_document["regionId"]), client.client_connection.ReadEndpoint))
break
else:
self.trace_error("Winning document version from region %d is not found @ %s, retrying..." %
(int(winner_document['regionId']), client.client_connection.WriteEndpoint))
time.sleep(0.5)
except exceptions.AzureError:
self.trace_error("Winner document from region %d is not found @ %s, retrying..." %
(int(winner_document['regionId']), client.client_connection.WriteEndpoint))
time.sleep(0.5)
def trace_error(self, message):
print('\n' + message + '\n')
|