2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2019-2021 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.Objects;
33 import java.util.UUID;
34 import java.util.concurrent.TimeUnit;
37 import org.apache.commons.collections4.CollectionUtils;
38 import org.onap.policy.controlloop.ControlLoopNotificationType;
39 import org.onap.policy.controlloop.ControlLoopOperation;
40 import org.onap.policy.controlloop.VirtualControlLoopNotification;
41 import org.onap.policy.drools.persistence.SystemPersistenceConstants;
42 import org.onap.policy.drools.system.PolicyController;
43 import org.onap.policy.drools.system.PolicyEngineConstants;
44 import org.onap.policy.drools.utils.logging.MdcTransaction;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
49 * Control Loop Metrics Tracker Implementation.
51 class CacheBasedControlLoopMetricsManager implements ControlLoopMetrics {
53 private static final String UNEXPECTED_NOTIFICATION_TYPE = "unexpected notification type {} in notification {}";
55 private static final Logger logger = LoggerFactory.getLogger(CacheBasedControlLoopMetricsManager.class);
57 private LoadingCache<UUID, VirtualControlLoopNotification> cache;
60 private long cacheSize = ControlLoopMetricsFeature.CL_CACHE_TRANS_SIZE_DEFAULT;
64 private long transactionTimeout = ControlLoopMetricsFeature.CL_CACHE_TRANS_TIMEOUT_SECONDS_DEFAULT;
67 * Numeric response code.
69 private static final Map<String, String> note2code = Map.of(
70 ControlLoopNotificationType.ACTIVE.name(), "100",
71 ControlLoopNotificationType.REJECTED.name(), "200",
72 ControlLoopNotificationType.OPERATION.name(), "300",
73 ControlLoopNotificationType.OPERATION_SUCCESS.name(), "301",
74 ControlLoopNotificationType.OPERATION_FAILURE.name(), "302",
75 ControlLoopNotificationType.FINAL_FAILURE.name(), "400",
76 ControlLoopNotificationType.FINAL_SUCCESS.name(), "401",
77 ControlLoopNotificationType.FINAL_OPENLOOP.name(), "402"
80 private static final String UNKNOWN_RESPONSE_CODE = "900";
82 public CacheBasedControlLoopMetricsManager() {
84 var properties = SystemPersistenceConstants.getManager()
85 .getProperties(ControlLoopMetricsFeature.CONFIGURATION_PROPERTIES_NAME);
91 Long.parseLong(properties.getProperty(ControlLoopMetricsFeature.CL_CACHE_TRANS_SIZE_PROPERTY,
92 "" + ControlLoopMetricsFeature.CL_CACHE_TRANS_SIZE_DEFAULT));
93 } catch (Exception e) {
94 logger.warn("{}:{} property cannot be accessed", ControlLoopMetricsFeature.CONFIGURATION_PROPERTIES_NAME,
95 ControlLoopMetricsFeature.CL_CACHE_TRANS_SIZE_PROPERTY, e);
98 /* transaction timeout */
101 this.transactionTimeout = Long
102 .parseLong(properties.getProperty(ControlLoopMetricsFeature.CL_CACHE_TRANS_TIMEOUT_SECONDS_PROPERTY,
103 "" + ControlLoopMetricsFeature.CL_CACHE_TRANS_TIMEOUT_SECONDS_DEFAULT));
104 } catch (Exception e) {
105 logger.warn("{}:{} property cannot be accessed", ControlLoopMetricsFeature.CONFIGURATION_PROPERTIES_NAME,
106 ControlLoopMetricsFeature.CL_CACHE_TRANS_TIMEOUT_SECONDS_PROPERTY, e);
109 resetCache(this.cacheSize, this.transactionTimeout);
113 public void resetCache(long cacheSize, long transactionTimeout) {
114 this.cacheSize = cacheSize;
115 this.transactionTimeout = transactionTimeout;
117 CacheLoader<UUID, VirtualControlLoopNotification> loader = new CacheLoader<>() {
120 public VirtualControlLoopNotification load(UUID key) {
125 RemovalListener<UUID, VirtualControlLoopNotification> listener = notification -> {
126 if (notification.wasEvicted()) {
127 evicted(notification.getValue());
128 } else if (logger.isInfoEnabled()) {
129 logger.info("REMOVAL: {} because of {}", notification.getValue().getRequestId(),
130 notification.getCause().name());
134 synchronized (this) {
135 if (this.cache != null) {
136 this.cache.cleanUp();
137 this.cache.invalidateAll();
140 this.cache = CacheBuilder.newBuilder().maximumSize(this.cacheSize)
141 .expireAfterWrite(transactionTimeout, TimeUnit.SECONDS).removalListener(listener).build(loader);
146 public void refresh() {
147 this.cache.cleanUp();
151 public List<UUID> getTransactionIds() {
152 return new ArrayList<>(this.cache.asMap().keySet());
156 public List<VirtualControlLoopNotification> getTransactions() {
157 return new ArrayList<>(this.cache.asMap().values());
161 public void transactionEvent(PolicyController controller, VirtualControlLoopNotification notification) {
162 if (!isNotificationValid(notification)) {
166 setNotificationValues(controller, notification);
168 switch (notification.getNotification()) {
173 endTransaction(controller, notification);
177 case OPERATION_SUCCESS:
178 case OPERATION_FAILURE:
179 /* any other value is an in progress transaction */
180 inProgressTransaction(notification);
184 logger.warn(UNEXPECTED_NOTIFICATION_TYPE,
185 notification.getNotification(), notification);
190 private boolean isNotificationValid(VirtualControlLoopNotification notification) {
191 if (notification == null || notification.getRequestId() == null || notification.getNotification() == null) {
192 logger.warn("Invalid notification: {}", notification);
199 private void setNotificationValues(PolicyController controller, VirtualControlLoopNotification notification) {
200 if (notification.getNotificationTime() == null) {
201 notification.setNotificationTime(ZonedDateTime.now());
204 notification.setFrom(notification.getFrom() + ":" + controller.getName()
205 + ":" + controller.getDrools().getCanonicalSessionNames());
209 public VirtualControlLoopNotification getTransaction(UUID requestId) {
210 return cache.getIfPresent(requestId);
214 public void removeTransaction(UUID requestId) {
215 cache.invalidate(requestId);
219 * Tracks an in progress control loop transaction.
221 * @param notification control loop notification
223 protected void inProgressTransaction(VirtualControlLoopNotification notification) {
224 if (cache.getIfPresent(notification.getRequestId()) == null) {
225 cache.put(notification.getRequestId(), notification);
228 this.metric(notification);
232 * End of a control loop transaction.
234 * @param controller controller
235 * @param notification control loop notification
237 protected void endTransaction(PolicyController controller, VirtualControlLoopNotification notification) {
238 ZonedDateTime startTime;
239 VirtualControlLoopNotification startNotification = cache.getIfPresent(notification.getRequestId());
240 startTime = Objects.requireNonNullElse(startNotification, notification).getNotificationTime();
242 this.transaction(controller, notification, startTime);
243 if (startNotification != null) {
244 removeTransaction(startNotification.getRequestId());
248 protected void evicted(VirtualControlLoopNotification notification) {
250 .newTransaction(notification.getRequestId().toString(), notification.getFrom())
251 .setServiceName(notification.getClosedLoopControlName()).setTargetEntity(notification.getTarget())
252 .setStartTime(notification.getNotificationTime().toInstant()).setEndTime(Instant.now())
253 .setResponseDescription("EVICTED").setStatusCode(false).metric().resetTransaction();
257 public void setMaxCacheSize(long cacheSize) {
258 this.cacheSize = cacheSize;
262 public long getCacheOccupancy() {
263 return this.cache.size();
266 protected void metric(VirtualControlLoopNotification notification) {
267 var trans = getMdcTransaction(notification);
268 List<ControlLoopOperation> operations = notification.getHistory();
269 switch (notification.getNotification()) {
271 trans.setStatusCode(true).metric().resetTransaction();
274 operation(trans.setStatusCode(true), operations).metric().resetTransaction();
276 case OPERATION_SUCCESS:
277 operation(trans.setStatusCode(true), operations).metric().transaction().resetTransaction();
279 case OPERATION_FAILURE:
280 operation(trans.setStatusCode(false), operations).metric().transaction().resetTransaction();
284 logger.warn(UNEXPECTED_NOTIFICATION_TYPE,
285 notification.getNotification(), notification);
290 private MdcTransaction getMdcTransaction(VirtualControlLoopNotification notification) {
291 return MdcTransaction
292 .newTransaction(notification.getRequestId().toString(), notification.getFrom())
293 .setServiceName(notification.getClosedLoopControlName())
294 .setServiceInstanceId(notification.getPolicyScope()
295 + ":" + notification.getPolicyName() + ":" + notification.getPolicyVersion())
296 .setProcessKey("" + notification.getAai())
297 .setTargetEntity(notification.getTargetType() + "." + notification.getTarget())
298 .setResponseCode((notification.getNotification() != null)
299 ? notificationTypeToResponseCode(notification.getNotification().name())
300 : UNKNOWN_RESPONSE_CODE)
301 .setCustomField1((notification.getNotification() != null)
302 ? notification.getNotification().name() : "")
303 .setResponseDescription(notification.getMessage())
304 .setClientIpAddress(notification.getClosedLoopEventClient());
307 protected MdcTransaction operation(MdcTransaction trans, List<ControlLoopOperation> operations) {
308 if (CollectionUtils.isEmpty(operations)) {
312 ControlLoopOperation operation = operations.get(operations.size() - 1);
314 if (operation.getActor() != null) {
315 trans.setTargetServiceName(operation.getActor() + "." + operation.getOperation());
318 if (operation.getTarget() != null) {
319 trans.setTargetVirtualEntity(operation.getTarget());
322 if (operation.getSubRequestId() != null) {
323 trans.setInvocationId(operation.getSubRequestId());
326 if (operation.getOutcome() != null) {
327 trans.setResponseDescription(operation.getOutcome() + ":" + operation.getMessage());
330 if (operation.getStart() != null) {
331 trans.setStartTime(operation.getStart());
334 if (operation.getEnd() != null) {
335 trans.setEndTime(operation.getEnd());
341 protected void transaction(PolicyController controller,
342 VirtualControlLoopNotification notification, ZonedDateTime startTime) {
343 MdcTransaction trans = getMdcTransaction(notification)
344 .setStartTime(startTime.toInstant())
345 .setEndTime(notification.getNotificationTime().toInstant());
347 switch (notification.getNotification()) {
351 trans.setStatusCode(true);
356 trans.setStatusCode(false);
360 logger.warn(UNEXPECTED_NOTIFICATION_TYPE,
361 notification.getNotification(), notification);
366 PolicyEngineConstants.getManager().transaction(controller.getName(),
367 notification.getClosedLoopControlName(), trans.getMetric());
368 } catch (RuntimeException rex) {
369 logger.info("error pegging control loop transaction: {}", trans.getMetric(), rex);
372 trans.transaction().resetTransaction();
376 public String toString() {
377 return "CacheBasedControlLoopMetricsManager{" + "cacheSize=" + cacheSize
378 + ",transactionTimeout="
381 + getCacheOccupancy()
385 private String notificationTypeToResponseCode(String notificationType) {
386 String code = note2code.get(notificationType);
387 return Objects.requireNonNullElse(code, UNKNOWN_RESPONSE_CODE);