|
| 1 | +package org.zstack.core.thread; |
| 2 | + |
| 3 | +import org.springframework.beans.factory.annotation.Autowire; |
| 4 | +import org.springframework.beans.factory.annotation.Autowired; |
| 5 | +import org.springframework.beans.factory.annotation.Configurable; |
| 6 | +import org.zstack.header.core.AbstractCompletion; |
| 7 | +import org.zstack.header.core.Completion; |
| 8 | +import org.zstack.header.core.ReturnValueCompletion; |
| 9 | +import org.zstack.header.errorcode.ErrorCode; |
| 10 | +import org.zstack.utils.Utils; |
| 11 | +import org.zstack.utils.logging.CLogger; |
| 12 | + |
| 13 | +import java.util.ArrayList; |
| 14 | +import java.util.Collections; |
| 15 | +import java.util.List; |
| 16 | +import java.util.concurrent.ConcurrentHashMap; |
| 17 | +import java.util.stream.Collectors; |
| 18 | + |
| 19 | +/** |
| 20 | + * Base implementation for coalesce queues. |
| 21 | + * |
| 22 | + * @param <T> Request Item Type |
| 23 | + * @param <R> Batch Execution Result Type |
| 24 | + * @param <V> Single Request Result Type |
| 25 | + */ |
| 26 | +@Configurable(preConstruction = true, autowire = Autowire.BY_TYPE) |
| 27 | +public abstract class AbstractCoalesceQueue<T, R, V> { |
| 28 | + private static final CLogger logger = Utils.getLogger(AbstractCoalesceQueue.class); |
| 29 | + |
| 30 | + @Autowired |
| 31 | + private ThreadFacade thdf; |
| 32 | + |
| 33 | + private final ConcurrentHashMap<String, SignatureQueue> signatureQueues = new ConcurrentHashMap<>(); |
| 34 | + |
| 35 | + protected class PendingRequest { |
| 36 | + final T item; |
| 37 | + final AbstractCompletion completion; |
| 38 | + |
| 39 | + PendingRequest(T item, AbstractCompletion completion) { |
| 40 | + this.item = item; |
| 41 | + this.completion = completion; |
| 42 | + } |
| 43 | + |
| 44 | + @SuppressWarnings("unchecked") |
| 45 | + void notifySuccess(V result) { |
| 46 | + if (completion == null) { |
| 47 | + return; |
| 48 | + } |
| 49 | + |
| 50 | + if (completion instanceof ReturnValueCompletion) { |
| 51 | + ((ReturnValueCompletion<V>) completion).success(result); |
| 52 | + } else if (completion instanceof Completion) { |
| 53 | + ((Completion) completion).success(); |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + void notifyFailure(ErrorCode errorCode) { |
| 58 | + if (completion == null) { |
| 59 | + return; |
| 60 | + } |
| 61 | + |
| 62 | + if (completion instanceof ReturnValueCompletion) { |
| 63 | + ((ReturnValueCompletion<V>) completion).fail(errorCode); |
| 64 | + } else if (completion instanceof Completion) { |
| 65 | + ((Completion) completion).fail(errorCode); |
| 66 | + } |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + private class SignatureQueue { |
| 71 | + final String syncSignature; |
| 72 | + List<PendingRequest> pendingList = Collections.synchronizedList(new ArrayList<>()); |
| 73 | + |
| 74 | + SignatureQueue(String syncSignature) { |
| 75 | + this.syncSignature = syncSignature; |
| 76 | + } |
| 77 | + |
| 78 | + synchronized List<PendingRequest> takeAll() { |
| 79 | + List<PendingRequest> toProcess = pendingList; |
| 80 | + pendingList = Collections.synchronizedList(new ArrayList<>()); |
| 81 | + return toProcess; |
| 82 | + } |
| 83 | + |
| 84 | + synchronized void add(PendingRequest request) { |
| 85 | + pendingList.add(request); |
| 86 | + } |
| 87 | + |
| 88 | + synchronized boolean isEmpty() { |
| 89 | + return pendingList.isEmpty(); |
| 90 | + } |
| 91 | + } |
| 92 | + |
| 93 | + protected abstract String getName(); |
| 94 | + |
| 95 | + protected abstract void executeBatch(List<T> items, AbstractCompletion completion); |
| 96 | + |
| 97 | + protected abstract AbstractCompletion createBatchCompletion(String syncSignature, List<PendingRequest> requests, SyncTaskChain chain); |
| 98 | + |
| 99 | + protected abstract V calculateResult(T item, R batchResult); |
| 100 | + |
| 101 | + protected final void handleSuccess(String syncSignature, List<PendingRequest> requests, R batchResult, SyncTaskChain chain) { |
| 102 | + for (PendingRequest req : requests) { |
| 103 | + try { |
| 104 | + V singleResult = calculateResult(req.item, batchResult); |
| 105 | + req.notifySuccess(singleResult); |
| 106 | + } catch (Throwable t) { |
| 107 | + logger.warn(String.format("[%s] failed to calculate result for item %s", getName(), req.item), t); |
| 108 | + req.notifyFailure(org.zstack.core.Platform.operr("failed to calculate result: %s", t.getMessage())); |
| 109 | + } |
| 110 | + } |
| 111 | + cleanup(syncSignature); |
| 112 | + chain.next(); |
| 113 | + } |
| 114 | + |
| 115 | + protected final void handleFailure(String syncSignature, List<PendingRequest> requests, ErrorCode errorCode, SyncTaskChain chain) { |
| 116 | + for (PendingRequest req : requests) { |
| 117 | + req.notifyFailure(errorCode); |
| 118 | + } |
| 119 | + cleanup(syncSignature); |
| 120 | + chain.next(); |
| 121 | + } |
| 122 | + |
| 123 | + void setThreadFacade(ThreadFacade thdf) { |
| 124 | + this.thdf = thdf; |
| 125 | + } |
| 126 | + |
| 127 | + protected final void submitRequest(String syncSignature, T item, AbstractCompletion completion) { |
| 128 | + doSubmit(syncSignature, new PendingRequest(item, completion)); |
| 129 | + } |
| 130 | + |
| 131 | + private void doSubmit(String syncSignature, PendingRequest request) { |
| 132 | + SignatureQueue queue = signatureQueues.computeIfAbsent(syncSignature, SignatureQueue::new); |
| 133 | + queue.add(request); |
| 134 | + |
| 135 | + thdf.chainSubmit(new ChainTask(null) { |
| 136 | + @Override |
| 137 | + public String getSyncSignature() { |
| 138 | + return String.format("coalesce-queue-%s-%s", AbstractCoalesceQueue.this.getName(), syncSignature); |
| 139 | + } |
| 140 | + |
| 141 | + @Override |
| 142 | + public void run(SyncTaskChain chain) { |
| 143 | + List<PendingRequest> requests = queue.takeAll(); |
| 144 | + |
| 145 | + if (requests.isEmpty()) { |
| 146 | + chain.next(); |
| 147 | + return; |
| 148 | + } |
| 149 | + |
| 150 | + String name = getName(); |
| 151 | + logger.debug(String.format("[%s] coalescing %d requests for signature[%s]", |
| 152 | + name, requests.size(), syncSignature)); |
| 153 | + |
| 154 | + AbstractCompletion batchCompletion = createBatchCompletion(syncSignature, requests, chain); |
| 155 | + List<T> items = requests.stream().map(req -> req.item).collect(Collectors.toList()); |
| 156 | + executeBatch(items, batchCompletion); |
| 157 | + } |
| 158 | + |
| 159 | + @Override |
| 160 | + public String getName() { |
| 161 | + return String.format("%s-coalesced-batch-%s", AbstractCoalesceQueue.this.getName(), syncSignature); |
| 162 | + } |
| 163 | + |
| 164 | + @Override |
| 165 | + protected int getSyncLevel() { |
| 166 | + return 1; |
| 167 | + } |
| 168 | + }); |
| 169 | + } |
| 170 | + |
| 171 | + private void cleanup(String syncSignature) { |
| 172 | + signatureQueues.computeIfPresent(syncSignature, (k, queue) -> { |
| 173 | + if (queue.isEmpty()) { |
| 174 | + return null; |
| 175 | + } |
| 176 | + return queue; |
| 177 | + }); |
| 178 | + } |
| 179 | + |
| 180 | + int getActiveQueueCount() { |
| 181 | + return signatureQueues.size(); |
| 182 | + } |
| 183 | +} |
0 commit comments