2 * ============LICENSE_START===================================================
3 * SPARKY (AAI UI service)
4 * ============================================================================
5 * Copyright © 2017 AT&T Intellectual Property.
6 * Copyright © 2017 Amdocs
8 * ============================================================================
9 * Licensed under the Apache License, Version 2.0 (the "License");
10 * you may not use this file except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
20 * ============LICENSE_END=====================================================
22 * ECOMP and OpenECOMP are trademarks
23 * and service marks of AT&T Intellectual Property.
26 package org.openecomp.sparky.synchronizer;
28 import static java.util.concurrent.CompletableFuture.supplyAsync;
30 import org.openecomp.cl.mdc.MdcContext;
32 import org.openecomp.cl.mdc.MdcContext;
34 import com.fasterxml.jackson.core.JsonProcessingException;
35 import com.fasterxml.jackson.databind.JsonNode;
36 import com.fasterxml.jackson.databind.ObjectReader;
37 import com.fasterxml.jackson.databind.node.ArrayNode;
39 import java.io.IOException;
40 import java.net.InetAddress;
41 import java.net.UnknownHostException;
42 import java.util.ArrayList;
43 import java.util.Collection;
44 import java.util.Deque;
45 import java.util.Iterator;
46 import java.util.List;
48 import java.util.concurrent.ConcurrentHashMap;
49 import java.util.concurrent.ConcurrentLinkedDeque;
50 import java.util.concurrent.ExecutorService;
51 import java.util.function.Supplier;
53 import org.openecomp.cl.api.Logger;
54 import org.openecomp.cl.eelf.LoggerFactory;
55 import org.openecomp.sparky.config.oxm.OxmEntityDescriptor;
56 import org.openecomp.sparky.dal.NetworkTransaction;
57 import org.openecomp.sparky.dal.aai.config.ActiveInventoryConfig;
58 import org.openecomp.sparky.dal.elasticsearch.config.ElasticSearchConfig;
59 import org.openecomp.sparky.dal.rest.HttpMethod;
60 import org.openecomp.sparky.dal.rest.OperationResult;
61 import org.openecomp.sparky.logging.AaiUiMsgs;
62 import org.openecomp.sparky.synchronizer.config.SynchronizerConfiguration;
63 import org.openecomp.sparky.synchronizer.entity.MergableEntity;
64 import org.openecomp.sparky.synchronizer.entity.SearchableEntity;
65 import org.openecomp.sparky.synchronizer.entity.SelfLinkDescriptor;
66 import org.openecomp.sparky.synchronizer.enumeration.OperationState;
67 import org.openecomp.sparky.synchronizer.enumeration.SynchronizerState;
68 import org.openecomp.sparky.synchronizer.task.PerformActiveInventoryRetrieval;
69 import org.openecomp.sparky.synchronizer.task.PerformElasticSearchPut;
70 import org.openecomp.sparky.synchronizer.task.PerformElasticSearchRetrieval;
71 import org.openecomp.sparky.synchronizer.task.PerformElasticSearchUpdate;
72 import org.openecomp.sparky.util.NodeUtils;
76 * The Class SearchableEntitySynchronizer.
78 public class SearchableEntitySynchronizer extends AbstractEntitySynchronizer
79 implements IndexSynchronizer {
82 * The Class RetrySearchableEntitySyncContainer.
84 private class RetrySearchableEntitySyncContainer {
85 NetworkTransaction txn;
89 * Instantiates a new retry searchable entity sync container.
94 public RetrySearchableEntitySyncContainer(NetworkTransaction txn, SearchableEntity se) {
99 public NetworkTransaction getNetworkTransaction() {
103 public SearchableEntity getSearchableEntity() {
108 private static final Logger LOG =
109 LoggerFactory.getInstance().getLogger(SearchableEntitySynchronizer.class);
111 private boolean allWorkEnumerated;
112 private Deque<SelfLinkDescriptor> selflinks;
113 private Deque<RetrySearchableEntitySyncContainer> retryQueue;
114 private Map<String, Integer> retryLimitTracker;
115 protected ExecutorService esPutExecutor;
118 * Instantiates a new searchable entity synchronizer.
120 * @param indexName the index name
121 * @throws Exception the exception
123 public SearchableEntitySynchronizer(String indexName) throws Exception {
124 super(LOG, "SES", 2, 5, 5, indexName);
125 this.allWorkEnumerated = false;
126 this.selflinks = new ConcurrentLinkedDeque<SelfLinkDescriptor>();
127 this.retryQueue = new ConcurrentLinkedDeque<RetrySearchableEntitySyncContainer>();
128 this.retryLimitTracker = new ConcurrentHashMap<String, Integer>();
129 this.synchronizerName = "Searchable Entity Synchronizer";
130 this.esPutExecutor = NodeUtils.createNamedExecutor("SES-ES-PUT", 5, LOG);
131 this.aaiEntityStats.initializeCountersFromOxmEntityDescriptors(
132 oxmModelLoader.getSearchableEntityDescriptors());
133 this.esEntityStats.initializeCountersFromOxmEntityDescriptors(
134 oxmModelLoader.getSearchableEntityDescriptors());
135 this.syncDurationInMs = -1;
139 * Collect all the work.
141 * @return the operation state
143 private OperationState collectAllTheWork() {
144 final Map<String, String> contextMap = MDC.getCopyOfContextMap();
145 Map<String, OxmEntityDescriptor> descriptorMap =
146 oxmModelLoader.getSearchableEntityDescriptors();
148 if (descriptorMap.isEmpty()) {
149 LOG.error(AaiUiMsgs.ERROR_LOADING_OXM_SEARCHABLE_ENTITIES);
150 LOG.info(AaiUiMsgs.ERROR_LOADING_OXM_SEARCHABLE_ENTITIES);
151 return OperationState.ERROR;
154 Collection<String> syncTypes = descriptorMap.keySet();
156 /*Collection<String> syncTypes = new ArrayList<String>();
157 syncTypes.add("service-instance");*/
162 * launch a parallel async thread to process the documents for each entity-type (to max the
163 * of the configured executor anyway)
166 aaiWorkOnHand.set(syncTypes.size());
168 for (String key : syncTypes) {
170 supplyAsync(new Supplier<Void>() {
174 MDC.setContextMap(contextMap);
175 OperationResult typeLinksResult = null;
177 typeLinksResult = aaiDataProvider.getSelfLinksByEntityType(key);
178 aaiWorkOnHand.decrementAndGet();
179 processEntityTypeSelfLinks(typeLinksResult);
180 } catch (Exception exc) {
181 // TODO -> LOG, what should be logged here?
187 }, aaiExecutor).whenComplete((result, error) -> {
190 LOG.error(AaiUiMsgs.ERROR_GENERIC,
191 "An error occurred getting data from AAI. Error = " + error.getMessage());
197 while (aaiWorkOnHand.get() != 0) {
199 if (LOG.isDebugEnabled()) {
200 LOG.debug(AaiUiMsgs.WAIT_FOR_ALL_SELFLINKS_TO_BE_COLLECTED);
206 aaiWorkOnHand.set(selflinks.size());
207 allWorkEnumerated = true;
210 while (!isSyncDone()) {
216 * Make sure we don't hang on to retries that failed which could cause issues during future
219 retryLimitTracker.clear();
221 } catch (Exception exc) {
222 // TODO -> LOG, waht should be logged here?
225 return OperationState.OK;
229 * @see org.openecomp.sparky.synchronizer.IndexSynchronizer#doSync()
232 public OperationState doSync() {
233 this.syncDurationInMs = -1;
234 String txnID = NodeUtils.getRandomTxnId();
235 MdcContext.initialize(txnID, "SearchableEntitySynchronizer", "", "Sync", "");
238 this.allWorkEnumerated = false;
239 syncStartedTimeStampInMs = System.currentTimeMillis();
242 return OperationState.OK;
246 * Process entity type self links.
248 * @param operationResult the operation result
250 private void processEntityTypeSelfLinks(OperationResult operationResult) {
252 JsonNode rootNode = null;
254 final String jsonResult = operationResult.getResult();
256 if (jsonResult != null && jsonResult.length() > 0 && operationResult.wasSuccessful()) {
259 rootNode = mapper.readTree(jsonResult);
260 } catch (IOException exc) {
262 "Could not deserialize JSON (representing operation result) as node tree. " +
263 "Operation result = " + jsonResult + ". " + exc.getLocalizedMessage();
264 LOG.error(AaiUiMsgs.JSON_PROCESSING_ERROR, message);
267 JsonNode resultData = rootNode.get("result-data");
268 ArrayNode resultDataArrayNode = null;
270 if (resultData.isArray()) {
271 resultDataArrayNode = (ArrayNode) resultData;
273 Iterator<JsonNode> elementIterator = resultDataArrayNode.elements();
274 JsonNode element = null;
276 while (elementIterator.hasNext()) {
277 element = elementIterator.next();
279 final String resourceType = NodeUtils.getNodeFieldAsText(element, "resource-type");
280 final String resourceLink = NodeUtils.getNodeFieldAsText(element, "resource-link");
282 OxmEntityDescriptor descriptor = null;
284 if (resourceType != null && resourceLink != null) {
286 descriptor = oxmModelLoader.getEntityDescriptor(resourceType);
288 if (descriptor == null) {
289 LOG.error(AaiUiMsgs.MISSING_ENTITY_DESCRIPTOR, resourceType);
290 // go to next element in iterator
294 if (descriptor.hasSearchableAttributes()) {
295 selflinks.add(new SelfLinkDescriptor(resourceLink, SynchronizerConfiguration.NODES_ONLY_MODIFIER, resourceType));
308 private void syncEntityTypes() {
310 while (selflinks.peek() != null) {
312 SelfLinkDescriptor linkDescriptor = selflinks.poll();
313 aaiWorkOnHand.decrementAndGet();
315 OxmEntityDescriptor descriptor = null;
317 if (linkDescriptor.getSelfLink() != null && linkDescriptor.getEntityType() != null) {
319 descriptor = oxmModelLoader.getEntityDescriptor(linkDescriptor.getEntityType());
321 if (descriptor == null) {
322 LOG.error(AaiUiMsgs.MISSING_ENTITY_DESCRIPTOR, linkDescriptor.getEntityType());
323 // go to next element in iterator
327 NetworkTransaction txn = new NetworkTransaction();
328 txn.setDescriptor(descriptor);
329 txn.setLink(linkDescriptor.getSelfLink());
330 txn.setOperationType(HttpMethod.GET);
331 txn.setEntityType(linkDescriptor.getEntityType());
333 aaiWorkOnHand.incrementAndGet();
335 supplyAsync(new PerformActiveInventoryRetrieval(txn, aaiDataProvider), aaiExecutor)
336 .whenComplete((result, error) -> {
338 aaiWorkOnHand.decrementAndGet();
341 LOG.error(AaiUiMsgs.AAI_RETRIEVAL_FAILED_GENERIC, error.getLocalizedMessage());
343 if (result == null) {
344 LOG.error(AaiUiMsgs.AAI_RETRIEVAL_FAILED_FOR_SELF_LINK,
345 linkDescriptor.getSelfLink());
347 updateActiveInventoryCounters(result);
348 fetchDocumentForUpsert(result);
359 * Perform document upsert.
361 * @param esGetTxn the es get txn
364 protected void performDocumentUpsert(NetworkTransaction esGetTxn, SearchableEntity se) {
368 * As part of the response processing we need to do the following:
369 * <li>1. Extract the version (if present), it will be the ETAG when we use the
370 * Search-Abstraction-Service
371 * <li>2. Spawn next task which is to do the PUT operation into elastic with or with the version
373 * <li>a) if version is null or RC=404, then standard put, no _update with version tag
374 * <li>b) if version != null, do PUT with _update?version= versionNumber in the URI to elastic
380 link = getElasticFullUrl("/" + se.getId(), getIndexName());
381 } catch (Exception exc) {
382 LOG.error(AaiUiMsgs.ES_LINK_UPSERT, exc.getLocalizedMessage());
386 String versionNumber = null;
387 boolean wasEntryDiscovered = false;
388 if (esGetTxn.getOperationResult().getResultCode() == 404) {
389 LOG.info(AaiUiMsgs.ES_SIMPLE_PUT, se.getEntityPrimaryKeyValue());
390 } else if (esGetTxn.getOperationResult().getResultCode() == 200) {
391 wasEntryDiscovered = true;
393 versionNumber = NodeUtils.extractFieldValueFromObject(
394 NodeUtils.convertJsonStrToJsonNode(esGetTxn.getOperationResult().getResult()),
396 } catch (IOException exc) {
398 "Error extracting version number from response, aborting searchable entity sync of "
399 + se.getEntityPrimaryKeyValue() + ". Error - " + exc.getLocalizedMessage();
400 LOG.error(AaiUiMsgs.ERROR_EXTRACTING_FROM_RESPONSE, message);
405 * Not being a 200 does not mean a failure. eg 201 is returned for created. TODO -> Should we
408 LOG.error(AaiUiMsgs.ES_OPERATION_RETURN_CODE,
409 String.valueOf(esGetTxn.getOperationResult().getResultCode()));
414 String jsonPayload = null;
415 if (wasEntryDiscovered) {
417 ArrayList<JsonNode> sourceObject = new ArrayList<JsonNode>();
418 NodeUtils.extractObjectsByKey(
419 NodeUtils.convertJsonStrToJsonNode(esGetTxn.getOperationResult().getResult()),
420 "_source", sourceObject);
422 if (!sourceObject.isEmpty()) {
423 String responseSource = NodeUtils.convertObjectToJson(sourceObject.get(0), false);
424 MergableEntity me = mapper.readValue(responseSource, MergableEntity.class);
425 ObjectReader updater = mapper.readerForUpdating(me);
426 MergableEntity merged = updater.readValue(se.getIndexDocumentJson());
427 jsonPayload = mapper.writeValueAsString(merged);
429 } catch (IOException exc) {
431 "Error extracting source value from response, aborting searchable entity sync of "
432 + se.getEntityPrimaryKeyValue() + ". Error - " + exc.getLocalizedMessage();
433 LOG.error(AaiUiMsgs.ERROR_EXTRACTING_FROM_RESPONSE, message);
437 jsonPayload = se.getIndexDocumentJson();
440 if (wasEntryDiscovered) {
441 if (versionNumber != null && jsonPayload != null) {
443 String requestPayload = esDataProvider.buildBulkImportOperationRequest(getIndexName(),
444 ElasticSearchConfig.getConfig().getType(), se.getId(), versionNumber, jsonPayload);
446 NetworkTransaction transactionTracker = new NetworkTransaction();
447 transactionTracker.setEntityType(esGetTxn.getEntityType());
448 transactionTracker.setDescriptor(esGetTxn.getDescriptor());
449 transactionTracker.setOperationType(HttpMethod.PUT);
451 esWorkOnHand.incrementAndGet();
452 supplyAsync(new PerformElasticSearchUpdate(ElasticSearchConfig.getConfig().getBulkUrl(),
453 requestPayload, esDataProvider, transactionTracker), esPutExecutor)
454 .whenComplete((result, error) -> {
456 esWorkOnHand.decrementAndGet();
459 String message = "Searchable entity sync UPDATE PUT error - "
460 + error.getLocalizedMessage();
461 LOG.error(AaiUiMsgs.ES_SEARCHABLE_ENTITY_SYNC_ERROR, message);
463 updateElasticSearchCounters(result);
464 processStoreDocumentResult(result, esGetTxn, se);
470 if (link != null && jsonPayload != null) {
472 NetworkTransaction updateElasticTxn = new NetworkTransaction();
473 updateElasticTxn.setLink(link);
474 updateElasticTxn.setEntityType(esGetTxn.getEntityType());
475 updateElasticTxn.setDescriptor(esGetTxn.getDescriptor());
476 updateElasticTxn.setOperationType(HttpMethod.PUT);
478 esWorkOnHand.incrementAndGet();
479 supplyAsync(new PerformElasticSearchPut(jsonPayload, updateElasticTxn, esDataProvider),
480 esPutExecutor).whenComplete((result, error) -> {
482 esWorkOnHand.decrementAndGet();
486 "Searchable entity sync UPDATE PUT error - " + error.getLocalizedMessage();
487 LOG.error(AaiUiMsgs.ES_SEARCHABLE_ENTITY_SYNC_ERROR, message);
489 updateElasticSearchCounters(result);
490 processStoreDocumentResult(result, esGetTxn, se);
495 } catch (Exception exc) {
496 String message = "Exception caught during searchable entity sync PUT operation. Message - "
497 + exc.getLocalizedMessage();
498 LOG.error(AaiUiMsgs.ES_SEARCHABLE_ENTITY_SYNC_ERROR, message);
503 * Populate searchable entity document.
506 * @param result the result
507 * @param resultDescriptor the result descriptor
508 * @throws JsonProcessingException the json processing exception
509 * @throws IOException Signals that an I/O exception has occurred.
511 protected void populateSearchableEntityDocument(SearchableEntity doc, String result,
512 OxmEntityDescriptor resultDescriptor) throws JsonProcessingException, IOException {
514 doc.setEntityType(resultDescriptor.getEntityName());
516 JsonNode entityNode = mapper.readTree(result);
518 List<String> primaryKeyValues = new ArrayList<String>();
519 String pkeyValue = null;
521 for (String keyName : resultDescriptor.getPrimaryKeyAttributeName()) {
522 pkeyValue = NodeUtils.getNodeFieldAsText(entityNode, keyName);
523 if (pkeyValue != null) {
524 primaryKeyValues.add(pkeyValue);
526 String message = "populateSearchableEntityDocument(), pKeyValue is null for entityType = "
527 + resultDescriptor.getEntityName();
528 LOG.warn(AaiUiMsgs.WARN_GENERIC, message);
532 final String primaryCompositeKeyValue = NodeUtils.concatArray(primaryKeyValues, "/");
533 doc.setEntityPrimaryKeyValue(primaryCompositeKeyValue);
535 final List<String> searchTagFields = resultDescriptor.getSearchableAttributes();
538 * Based on configuration, use the configured field names for this entity-Type to build a
539 * multi-value collection of search tags for elastic search entity search criteria.
541 for (String searchTagField : searchTagFields) {
542 String searchTagValue = NodeUtils.getNodeFieldAsText(entityNode, searchTagField);
543 if (searchTagValue != null && !searchTagValue.isEmpty()) {
544 doc.addSearchTagWithKey(searchTagValue, searchTagField);
550 * Fetch document for upsert.
554 private void fetchDocumentForUpsert(NetworkTransaction txn) {
555 if (!txn.getOperationResult().wasSuccessful()) {
556 String message = "Self link failure. Result - " + txn.getOperationResult().getResult();
557 LOG.error(AaiUiMsgs.ERROR_GENERIC, message);
562 if (txn.getDescriptor().hasSearchableAttributes()) {
564 final String jsonResult = txn.getOperationResult().getResult();
565 if (jsonResult != null && jsonResult.length() > 0) {
567 SearchableEntity se = new SearchableEntity(oxmModelLoader);
568 se.setLink(ActiveInventoryConfig.extractResourcePath(txn.getLink()));
569 populateSearchableEntityDocument(se, jsonResult, txn.getDescriptor());
574 link = getElasticFullUrl("/" + se.getId(), getIndexName());
575 } catch (Exception exc) {
576 LOG.error(AaiUiMsgs.ES_FAILED_TO_CONSTRUCT_QUERY, exc.getLocalizedMessage());
580 NetworkTransaction n2 = new NetworkTransaction();
582 n2.setEntityType(txn.getEntityType());
583 n2.setDescriptor(txn.getDescriptor());
584 n2.setOperationType(HttpMethod.GET);
586 esWorkOnHand.incrementAndGet();
588 supplyAsync(new PerformElasticSearchRetrieval(n2, esDataProvider), esExecutor)
589 .whenComplete((result, error) -> {
591 esWorkOnHand.decrementAndGet();
594 LOG.error(AaiUiMsgs.ES_RETRIEVAL_FAILED, error.getLocalizedMessage());
596 updateElasticSearchCounters(result);
597 performDocumentUpsert(result, se);
604 } catch (JsonProcessingException exc) {
605 // TODO -> LOG, waht should be logged here?
606 } catch (IOException exc) {
607 // TODO -> LOG, waht should be logged here?
612 * Process store document result.
614 * @param esPutResult the es put result
615 * @param esGetResult the es get result
618 private void processStoreDocumentResult(NetworkTransaction esPutResult,
619 NetworkTransaction esGetResult, SearchableEntity se) {
621 OperationResult or = esPutResult.getOperationResult();
623 if (!or.wasSuccessful()) {
624 if (or.getResultCode() == VERSION_CONFLICT_EXCEPTION_CODE) {
626 if (shouldAllowRetry(se.getId())) {
627 esWorkOnHand.incrementAndGet();
629 RetrySearchableEntitySyncContainer rsc =
630 new RetrySearchableEntitySyncContainer(esGetResult, se);
631 retryQueue.push(rsc);
633 String message = "Store document failed during searchable entity synchronization"
634 + " due to version conflict. Entity will be re-synced.";
635 LOG.warn(AaiUiMsgs.ES_SEARCHABLE_ENTITY_SYNC_ERROR, message);
639 "Store document failed during searchable entity synchronization with result code "
640 + or.getResultCode() + " and result message " + or.getResult();
641 LOG.error(AaiUiMsgs.ES_SEARCHABLE_ENTITY_SYNC_ERROR, message);
647 * Perform retry sync.
649 private void performRetrySync() {
650 while (retryQueue.peek() != null) {
652 RetrySearchableEntitySyncContainer rsc = retryQueue.poll();
655 SearchableEntity se = rsc.getSearchableEntity();
656 NetworkTransaction txn = rsc.getNetworkTransaction();
661 * In this retry flow the se object has already derived its fields
663 link = getElasticFullUrl("/" + se.getId(), getIndexName());
664 } catch (Exception exc) {
665 LOG.error(AaiUiMsgs.ES_FAILED_TO_CONSTRUCT_URI, exc.getLocalizedMessage());
669 NetworkTransaction retryTransaction = new NetworkTransaction();
670 retryTransaction.setLink(link);
671 retryTransaction.setEntityType(txn.getEntityType());
672 retryTransaction.setDescriptor(txn.getDescriptor());
673 retryTransaction.setOperationType(HttpMethod.GET);
676 * IMPORTANT - DO NOT incrementAndGet the esWorkOnHand as this is a retry flow! We already
677 * called incrementAndGet when queuing the failed PUT!
680 supplyAsync(new PerformElasticSearchRetrieval(retryTransaction, esDataProvider),
681 esExecutor).whenComplete((result, error) -> {
683 esWorkOnHand.decrementAndGet();
686 LOG.error(AaiUiMsgs.ES_RETRIEVAL_FAILED_RESYNC, error.getLocalizedMessage());
688 updateElasticSearchCounters(result);
689 performDocumentUpsert(result, se);
699 * Should allow retry.
702 * @return true, if successful
704 private boolean shouldAllowRetry(String id) {
705 boolean isRetryAllowed = true;
706 if (retryLimitTracker.get(id) != null) {
707 Integer currentCount = retryLimitTracker.get(id);
708 if (currentCount.intValue() >= RETRY_COUNT_PER_ENTITY_LIMIT.intValue()) {
709 isRetryAllowed = false;
710 String message = "Searchable entity re-sync limit reached for " + id
711 + ", re-sync will no longer be attempted for this entity";
712 LOG.error(AaiUiMsgs.ES_SEARCHABLE_ENTITY_SYNC_ERROR, message);
714 Integer newCount = new Integer(currentCount.intValue() + 1);
715 retryLimitTracker.put(id, newCount);
718 Integer firstRetryCount = new Integer(1);
719 retryLimitTracker.put(id, firstRetryCount);
722 return isRetryAllowed;
726 public SynchronizerState getState() {
728 return SynchronizerState.PERFORMING_SYNCHRONIZATION;
731 return SynchronizerState.IDLE;
736 * @see org.openecomp.sparky.synchronizer.IndexSynchronizer#getStatReport(boolean)
739 public String getStatReport(boolean showFinalReport) {
740 syncDurationInMs = System.currentTimeMillis() - syncStartedTimeStampInMs;
741 return this.getStatReport(syncDurationInMs, showFinalReport);
745 * @see org.openecomp.sparky.synchronizer.IndexSynchronizer#shutdown()
748 public void shutdown() {
749 this.shutdownExecutors();
753 protected boolean isSyncDone() {
754 int totalWorkOnHand = aaiWorkOnHand.get() + esWorkOnHand.get();
756 if (totalWorkOnHand > 0 || !allWorkEnumerated) {