2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.onap.policy.drools.apps.controlloop.feature.trans;
23 import com.google.common.cache.CacheBuilder;
24 import com.google.common.cache.CacheLoader;
25 import com.google.common.cache.LoadingCache;
26 import com.google.common.cache.RemovalListener;
27 import java.time.Instant;
28 import java.time.ZonedDateTime;
29 import java.util.ArrayList;
30 import java.util.List;
32 import java.util.Properties;
33 import java.util.UUID;
34 import java.util.concurrent.TimeUnit;
35 import org.apache.commons.collections4.CollectionUtils;
36 import org.onap.policy.controlloop.ControlLoopNotificationType;
37 import org.onap.policy.controlloop.ControlLoopOperation;
38 import org.onap.policy.controlloop.VirtualControlLoopNotification;
39 import org.onap.policy.drools.persistence.SystemPersistenceConstants;
40 import org.onap.policy.drools.system.PolicyController;
41 import org.onap.policy.drools.utils.logging.MdcTransaction;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
46 * Control Loop Metrics Tracker Implementation.
48 class CacheBasedControlLoopMetricsManager implements ControlLoopMetrics {
50 private static final String UNEXPECTED_NOTIFICATION_TYPE = "unexpected notification type {} in notification {}";
52 private static final Logger logger = LoggerFactory.getLogger(CacheBasedControlLoopMetricsManager.class);
54 private LoadingCache<UUID, VirtualControlLoopNotification> cache;
55 private long cacheSize = ControlLoopMetricsFeature.CL_CACHE_TRANS_SIZE_DEFAULT;
57 private long transactionTimeout = ControlLoopMetricsFeature.CL_CACHE_TRANS_TIMEOUT_SECONDS_DEFAULT;
60 * Numeric response code.
62 private static final Map<String, String> note2code = Map.of(
63 ControlLoopNotificationType.ACTIVE.name(), "100",
64 ControlLoopNotificationType.REJECTED.name(), "200",
65 ControlLoopNotificationType.OPERATION.name(), "300",
66 ControlLoopNotificationType.OPERATION_SUCCESS.name(), "301",
67 ControlLoopNotificationType.OPERATION_FAILURE.name(), "302",
68 ControlLoopNotificationType.FINAL_FAILURE.name(), "400",
69 ControlLoopNotificationType.FINAL_SUCCESS.name(), "401",
70 ControlLoopNotificationType.FINAL_OPENLOOP.name(), "402"
73 private static final String UNKNOWN_RESPONSE_CODE = "900";
75 public CacheBasedControlLoopMetricsManager() {
77 Properties properties = SystemPersistenceConstants.getManager()
78 .getProperties(ControlLoopMetricsFeature.CONFIGURATION_PROPERTIES_NAME);
84 Long.parseLong(properties.getProperty(ControlLoopMetricsFeature.CL_CACHE_TRANS_SIZE_PROPERTY,
85 "" + ControlLoopMetricsFeature.CL_CACHE_TRANS_SIZE_DEFAULT));
86 } catch (Exception e) {
87 logger.warn("{}:{} property cannot be accessed", ControlLoopMetricsFeature.CONFIGURATION_PROPERTIES_NAME,
88 ControlLoopMetricsFeature.CL_CACHE_TRANS_SIZE_PROPERTY, e);
91 /* transaction timeout */
94 this.transactionTimeout = Long
95 .parseLong(properties.getProperty(ControlLoopMetricsFeature.CL_CACHE_TRANS_TIMEOUT_SECONDS_PROPERTY,
96 "" + ControlLoopMetricsFeature.CL_CACHE_TRANS_TIMEOUT_SECONDS_DEFAULT));
97 } catch (Exception e) {
98 logger.warn("{}:{} property cannot be accessed", ControlLoopMetricsFeature.CONFIGURATION_PROPERTIES_NAME,
99 ControlLoopMetricsFeature.CL_CACHE_TRANS_TIMEOUT_SECONDS_PROPERTY, e);
102 resetCache(this.cacheSize, this.transactionTimeout);
106 public void resetCache(long cacheSize, long transactionTimeout) {
107 this.cacheSize = cacheSize;
108 this.transactionTimeout = transactionTimeout;
110 CacheLoader<UUID, VirtualControlLoopNotification> loader = new CacheLoader<>() {
113 public VirtualControlLoopNotification load(UUID key) {
118 RemovalListener<UUID, VirtualControlLoopNotification> listener = notification -> {
119 if (notification.wasEvicted()) {
120 evicted(notification.getValue());
121 } else if (logger.isInfoEnabled()) {
122 logger.info("REMOVAL: {} because of {}", notification.getValue().getRequestId(),
123 notification.getCause().name());
127 synchronized (this) {
128 if (this.cache != null) {
129 this.cache.cleanUp();
130 this.cache.invalidateAll();
133 this.cache = CacheBuilder.newBuilder().maximumSize(this.cacheSize)
134 .expireAfterWrite(transactionTimeout, TimeUnit.SECONDS).removalListener(listener).build(loader);
139 public void refresh() {
140 this.cache.cleanUp();
144 public List<UUID> getTransactionIds() {
145 return new ArrayList<>(this.cache.asMap().keySet());
149 public List<VirtualControlLoopNotification> getTransactions() {
150 return new ArrayList<>(this.cache.asMap().values());
154 public void transactionEvent(PolicyController controller, VirtualControlLoopNotification notification) {
155 if (!isNotificationValid(notification)) {
159 setNotificationValues(controller, notification);
161 switch (notification.getNotification()) {
166 endTransaction(notification);
170 case OPERATION_SUCCESS:
171 case OPERATION_FAILURE:
172 /* any other value is an in progress transaction */
173 inProgressTransaction(notification);
177 logger.warn(UNEXPECTED_NOTIFICATION_TYPE,
178 notification.getNotification(), notification);
183 private boolean isNotificationValid(VirtualControlLoopNotification notification) {
184 if (notification == null || notification.getRequestId() == null || notification.getNotification() == null) {
185 logger.warn("Invalid notification: {}", notification);
192 private void setNotificationValues(PolicyController controller, VirtualControlLoopNotification notification) {
193 if (notification.getNotificationTime() == null) {
194 notification.setNotificationTime(ZonedDateTime.now());
197 notification.setFrom(notification.getFrom() + ":" + controller.getName()
198 + ":" + controller.getDrools().getCanonicalSessionNames());
202 public VirtualControlLoopNotification getTransaction(UUID requestId) {
203 return cache.getIfPresent(requestId);
207 public void removeTransaction(UUID requestId) {
208 cache.invalidate(requestId);
212 * Tracks an in progress control loop transaction.
214 * @param notification control loop notification
216 protected void inProgressTransaction(VirtualControlLoopNotification notification) {
217 if (cache.getIfPresent(notification.getRequestId()) == null) {
218 cache.put(notification.getRequestId(), notification);
221 this.metric(notification);
225 * End of a control loop transaction.
227 * @param notification control loop notification
229 protected void endTransaction(VirtualControlLoopNotification notification) {
230 ZonedDateTime startTime;
231 VirtualControlLoopNotification startNotification = cache.getIfPresent(notification.getRequestId());
232 if (startNotification != null) {
233 startTime = startNotification.getNotificationTime();
235 startTime = notification.getNotificationTime();
238 this.transaction(notification, startTime);
239 if (startNotification != null) {
240 removeTransaction(startNotification.getRequestId());
244 protected void evicted(VirtualControlLoopNotification notification) {
246 .newTransaction(notification.getRequestId().toString(), notification.getFrom())
247 .setServiceName(notification.getClosedLoopControlName()).setTargetEntity(notification.getTarget())
248 .setStartTime(notification.getNotificationTime().toInstant()).setEndTime(Instant.now())
249 .setResponseDescription("EVICTED").setStatusCode(false).metric().resetTransaction();
253 public long getCacheSize() {
254 return this.cacheSize;
258 public void setMaxCacheSize(long cacheSize) {
259 this.cacheSize = cacheSize;
263 public long getTransactionTimeout() {
264 return this.transactionTimeout;
268 public void setTransactionTimeout(long transactionTimeout) {
269 this.transactionTimeout = transactionTimeout;
273 public long getCacheOccupancy() {
274 return this.cache.size();
277 protected void metric(VirtualControlLoopNotification notification) {
278 MdcTransaction trans = getMdcTransaction(notification);
279 List<ControlLoopOperation> operations = notification.getHistory();
280 switch (notification.getNotification()) {
282 trans.setStatusCode(true).metric().resetTransaction();
285 operation(trans.setStatusCode(true), operations).metric().resetTransaction();
287 case OPERATION_SUCCESS:
288 operation(trans.setStatusCode(true), operations).metric().transaction().resetTransaction();
290 case OPERATION_FAILURE:
291 operation(trans.setStatusCode(false), operations).metric().transaction().resetTransaction();
295 logger.warn(UNEXPECTED_NOTIFICATION_TYPE,
296 notification.getNotification(), notification);
301 private MdcTransaction getMdcTransaction(VirtualControlLoopNotification notification) {
302 return MdcTransaction
303 .newTransaction(notification.getRequestId().toString(), notification.getFrom())
304 .setServiceName(notification.getClosedLoopControlName())
305 .setServiceInstanceId(notification.getPolicyScope()
306 + ":" + notification.getPolicyName() + ":" + notification.getPolicyVersion())
307 .setProcessKey("" + notification.getAai())
308 .setTargetEntity(notification.getTargetType() + "." + notification.getTarget())
309 .setResponseCode((notification.getNotification() != null)
310 ? notificationTypeToResponseCode(notification.getNotification().name())
311 : UNKNOWN_RESPONSE_CODE)
312 .setCustomField1((notification.getNotification() != null)
313 ? notification.getNotification().name() : "")
314 .setResponseDescription(notification.getMessage())
315 .setClientIpAddress(notification.getClosedLoopEventClient());
318 protected MdcTransaction operation(MdcTransaction trans, List<ControlLoopOperation> operations) {
319 if (CollectionUtils.isEmpty(operations)) {
323 ControlLoopOperation operation = operations.get(operations.size() - 1);
325 if (operation.getActor() != null) {
326 trans.setTargetServiceName(operation.getActor() + "." + operation.getOperation());
329 if (operation.getTarget() != null) {
330 trans.setTargetVirtualEntity(operation.getTarget());
333 if (operation.getSubRequestId() != null) {
334 trans.setInvocationId(operation.getSubRequestId());
337 if (operation.getOutcome() != null) {
338 trans.setResponseDescription(operation.getOutcome() + ":" + operation.getMessage());
341 if (operation.getStart() != null) {
342 trans.setStartTime(operation.getStart());
345 if (operation.getEnd() != null) {
346 trans.setEndTime(operation.getEnd());
352 protected void transaction(VirtualControlLoopNotification notification, ZonedDateTime startTime) {
353 MdcTransaction trans = getMdcTransaction(notification)
354 .setStartTime(startTime.toInstant())
355 .setEndTime(notification.getNotificationTime().toInstant());
357 switch (notification.getNotification()) {
361 trans.setStatusCode(true);
366 trans.setStatusCode(false);
370 logger.warn(UNEXPECTED_NOTIFICATION_TYPE,
371 notification.getNotification(), notification);
375 trans.transaction().resetTransaction();
379 public String toString() {
380 return "CacheBasedControlLoopMetricsManager{" + "cacheSize=" + cacheSize
381 + ",transactionTimeout="
384 + getCacheOccupancy()
388 private String notificationTypeToResponseCode(String notificationType) {
389 String code = note2code.get(notificationType);
393 return UNKNOWN_RESPONSE_CODE;