2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2019-2022 AT&T Intellectual Property. All rights reserved.
6 * Modifications Copyright (C) 2023 Nordix Foundation.
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 * ============LICENSE_END=========================================================
22 package org.onap.policy.drools.apps.controlloop.feature.trans;
24 import com.google.common.cache.CacheBuilder;
25 import com.google.common.cache.CacheLoader;
26 import com.google.common.cache.LoadingCache;
27 import com.google.common.cache.RemovalListener;
28 import java.time.Instant;
29 import java.time.ZonedDateTime;
30 import java.util.ArrayList;
31 import java.util.List;
33 import java.util.Objects;
34 import java.util.UUID;
35 import java.util.concurrent.TimeUnit;
38 import org.apache.commons.collections4.CollectionUtils;
39 import org.onap.policy.controlloop.ControlLoopNotificationType;
40 import org.onap.policy.controlloop.ControlLoopOperation;
41 import org.onap.policy.controlloop.VirtualControlLoopNotification;
42 import org.onap.policy.drools.persistence.SystemPersistenceConstants;
43 import org.onap.policy.drools.system.PolicyController;
44 import org.onap.policy.drools.system.PolicyEngineConstants;
45 import org.onap.policy.drools.utils.logging.MdcTransaction;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
50 * Control Loop Metrics Tracker Implementation.
52 class CacheBasedControlLoopMetricsManager implements ControlLoopMetrics {
54 private static final String UNEXPECTED_NOTIFICATION_TYPE = "unexpected notification type {} in notification {}";
56 private static final Logger logger = LoggerFactory.getLogger(CacheBasedControlLoopMetricsManager.class);
58 private LoadingCache<UUID, VirtualControlLoopNotification> cache;
61 private long cacheSize = ControlLoopMetricsFeature.CL_CACHE_TRANS_SIZE_DEFAULT;
65 private long transactionTimeout = ControlLoopMetricsFeature.CL_CACHE_TRANS_TIMEOUT_SECONDS_DEFAULT;
68 * Numeric response code.
70 private static final Map<String, String> note2code = Map.of(
71 ControlLoopNotificationType.ACTIVE.name(), "100",
72 ControlLoopNotificationType.REJECTED.name(), "200",
73 ControlLoopNotificationType.OPERATION.name(), "300",
74 ControlLoopNotificationType.OPERATION_SUCCESS.name(), "301",
75 ControlLoopNotificationType.OPERATION_FAILURE.name(), "302",
76 ControlLoopNotificationType.FINAL_FAILURE.name(), "400",
77 ControlLoopNotificationType.FINAL_SUCCESS.name(), "401",
78 ControlLoopNotificationType.FINAL_OPENLOOP.name(), "402"
81 private static final String UNKNOWN_RESPONSE_CODE = "900";
83 public CacheBasedControlLoopMetricsManager() {
85 var properties = SystemPersistenceConstants.getManager()
86 .getProperties(ControlLoopMetricsFeature.CONFIGURATION_PROPERTIES_NAME);
92 Long.parseLong(properties.getProperty(ControlLoopMetricsFeature.CL_CACHE_TRANS_SIZE_PROPERTY,
93 "" + ControlLoopMetricsFeature.CL_CACHE_TRANS_SIZE_DEFAULT));
94 } catch (Exception e) {
95 logger.warn("{}:{} property cannot be accessed", ControlLoopMetricsFeature.CONFIGURATION_PROPERTIES_NAME,
96 ControlLoopMetricsFeature.CL_CACHE_TRANS_SIZE_PROPERTY, e);
99 /* transaction timeout */
102 this.transactionTimeout = Long
103 .parseLong(properties.getProperty(ControlLoopMetricsFeature.CL_CACHE_TRANS_TIMEOUT_SECONDS_PROPERTY,
104 "" + ControlLoopMetricsFeature.CL_CACHE_TRANS_TIMEOUT_SECONDS_DEFAULT));
105 } catch (Exception e) {
106 logger.warn("{}:{} property cannot be accessed", ControlLoopMetricsFeature.CONFIGURATION_PROPERTIES_NAME,
107 ControlLoopMetricsFeature.CL_CACHE_TRANS_TIMEOUT_SECONDS_PROPERTY, e);
110 resetCache(this.cacheSize, this.transactionTimeout);
114 public void resetCache(long cacheSize, long transactionTimeout) {
115 this.cacheSize = cacheSize;
116 this.transactionTimeout = transactionTimeout;
118 CacheLoader<UUID, VirtualControlLoopNotification> loader = new CacheLoader<>() {
121 public VirtualControlLoopNotification load(UUID key) {
126 RemovalListener<UUID, VirtualControlLoopNotification> listener = notification -> {
127 if (notification.wasEvicted()) {
128 evicted(notification.getValue());
129 } else if (logger.isInfoEnabled()) {
130 logger.info("REMOVAL: {} because of {}", notification.getValue().getRequestId(),
131 notification.getCause().name());
135 synchronized (this) {
136 if (this.cache != null) {
137 this.cache.cleanUp();
138 this.cache.invalidateAll();
141 this.cache = CacheBuilder.newBuilder().maximumSize(this.cacheSize)
142 .expireAfterWrite(transactionTimeout, TimeUnit.SECONDS).removalListener(listener).build(loader);
147 public void refresh() {
148 this.cache.cleanUp();
152 public List<UUID> getTransactionIds() {
153 return new ArrayList<>(this.cache.asMap().keySet());
157 public List<VirtualControlLoopNotification> getTransactions() {
158 return new ArrayList<>(this.cache.asMap().values());
162 public void transactionEvent(PolicyController controller, VirtualControlLoopNotification notification) {
163 if (!isNotificationValid(notification)) {
167 setNotificationValues(controller, notification);
169 switch (notification.getNotification()) {
170 case REJECTED, FINAL_FAILURE, FINAL_SUCCESS, FINAL_OPENLOOP:
171 endTransaction(controller, notification);
173 case ACTIVE, OPERATION, OPERATION_SUCCESS, OPERATION_FAILURE:
174 /* any other value is an in progress transaction */
175 inProgressTransaction(notification);
179 logger.warn(UNEXPECTED_NOTIFICATION_TYPE,
180 notification.getNotification(), notification);
185 private boolean isNotificationValid(VirtualControlLoopNotification notification) {
186 if (notification == null || notification.getRequestId() == null || notification.getNotification() == null) {
187 logger.warn("Invalid notification: {}", notification);
194 private void setNotificationValues(PolicyController controller, VirtualControlLoopNotification notification) {
195 if (notification.getNotificationTime() == null) {
196 notification.setNotificationTime(ZonedDateTime.now());
199 notification.setFrom(notification.getFrom() + ":" + controller.getName()
200 + ":" + controller.getDrools().getCanonicalSessionNames());
204 public VirtualControlLoopNotification getTransaction(UUID requestId) {
205 return cache.getIfPresent(requestId);
209 public void removeTransaction(UUID requestId) {
210 cache.invalidate(requestId);
214 * Tracks an in progress control loop transaction.
216 * @param notification control loop notification
218 protected void inProgressTransaction(VirtualControlLoopNotification notification) {
219 if (cache.getIfPresent(notification.getRequestId()) == null) {
220 cache.put(notification.getRequestId(), notification);
223 this.metric(notification);
227 * End of a control loop transaction.
229 * @param controller controller
230 * @param notification control loop notification
232 protected void endTransaction(PolicyController controller, VirtualControlLoopNotification notification) {
233 ZonedDateTime startTime;
234 VirtualControlLoopNotification startNotification = cache.getIfPresent(notification.getRequestId());
235 startTime = Objects.requireNonNullElse(startNotification, notification).getNotificationTime();
237 this.transaction(controller, notification, startTime);
238 if (startNotification != null) {
239 removeTransaction(startNotification.getRequestId());
243 protected void evicted(VirtualControlLoopNotification notification) {
245 .newTransaction(notification.getRequestId().toString(), notification.getFrom())
246 .setServiceName(notification.getClosedLoopControlName())
247 .setServiceInstanceId(notification.getPolicyName() + ":" + notification.getPolicyVersion())
248 .setProcessKey("" + notification.getAai())
249 .setTargetEntity(notification.getTargetType() + "." + notification.getTarget())
250 .setResponseCode(UNKNOWN_RESPONSE_CODE)
251 .setStartTime(notification.getNotificationTime().toInstant())
252 .setEndTime(Instant.now())
253 .setResponseDescription("EVICTED")
254 .setStatusCode(false)
255 .setCustomField1((notification.getNotification() != null)
256 ? notification.getNotification().name() : "")
257 .setCustomField2(notification.getPolicyScope())
258 .setClientIpAddress(notification.getClosedLoopEventClient())
265 public void setMaxCacheSize(long cacheSize) {
266 this.cacheSize = cacheSize;
270 public long getCacheOccupancy() {
271 return this.cache.size();
274 protected void metric(VirtualControlLoopNotification notification) {
275 var trans = getMdcTransaction(notification);
276 List<ControlLoopOperation> operations = notification.getHistory();
277 switch (notification.getNotification()) {
279 trans.setStatusCode(true).metric().resetTransaction();
282 operation(trans.setStatusCode(true), operations).metric().resetTransaction();
284 case OPERATION_SUCCESS:
285 operation(trans.setStatusCode(true), operations).metric().transaction().resetTransaction();
287 case OPERATION_FAILURE:
288 operation(trans.setStatusCode(false), operations).metric().transaction().resetTransaction();
292 logger.warn(UNEXPECTED_NOTIFICATION_TYPE,
293 notification.getNotification(), notification);
298 private MdcTransaction getMdcTransaction(VirtualControlLoopNotification notification) {
299 return MdcTransaction
300 .newTransaction(notification.getRequestId().toString(), notification.getFrom())
301 .setServiceName(notification.getClosedLoopControlName())
302 .setServiceInstanceId(notification.getPolicyName() + ":" + notification.getPolicyVersion())
303 .setProcessKey("" + notification.getAai())
304 .setTargetEntity(notification.getTargetType() + "." + notification.getTarget())
305 .setResponseCode((notification.getNotification() != null)
306 ? notificationTypeToResponseCode(notification.getNotification().name())
307 : UNKNOWN_RESPONSE_CODE)
308 .setCustomField1((notification.getNotification() != null)
309 ? notification.getNotification().name() : "")
310 .setCustomField2(notification.getPolicyScope())
311 .setResponseDescription(notification.getMessage())
312 .setClientIpAddress(notification.getClosedLoopEventClient());
315 protected MdcTransaction operation(MdcTransaction trans, List<ControlLoopOperation> operations) {
316 if (CollectionUtils.isEmpty(operations)) {
320 ControlLoopOperation operation = operations.get(operations.size() - 1);
322 if (operation.getActor() != null) {
323 trans.setTargetServiceName(operation.getActor() + "." + operation.getOperation());
326 if (operation.getTarget() != null) {
327 trans.setTargetVirtualEntity(operation.getTarget());
330 if (operation.getSubRequestId() != null) {
331 trans.setInvocationId(operation.getSubRequestId());
334 if (operation.getOutcome() != null) {
335 trans.setResponseDescription(operation.getOutcome() + ":" + operation.getMessage());
338 if (operation.getStart() != null) {
339 trans.setStartTime(operation.getStart());
342 if (operation.getEnd() != null) {
343 trans.setEndTime(operation.getEnd());
349 protected void transaction(PolicyController controller,
350 VirtualControlLoopNotification notification, ZonedDateTime startTime) {
351 MdcTransaction trans = getMdcTransaction(notification)
352 .setStartTime(startTime.toInstant())
353 .setEndTime(notification.getNotificationTime().toInstant());
355 switch (notification.getNotification()) {
359 trans.setStatusCode(true);
364 trans.setStatusCode(false);
368 logger.warn(UNEXPECTED_NOTIFICATION_TYPE,
369 notification.getNotification(), notification);
374 PolicyEngineConstants.getManager().transaction(controller.getName(),
375 notification.getClosedLoopControlName(), trans.getMetric());
376 } catch (RuntimeException rex) {
377 logger.info("error pegging control loop transaction: {}", trans.getMetric(), rex);
380 trans.transaction().resetTransaction();
384 public String toString() {
385 return "CacheBasedControlLoopMetricsManager{" + "cacheSize=" + cacheSize
386 + ",transactionTimeout="
389 + getCacheOccupancy()
393 private String notificationTypeToResponseCode(String notificationType) {
394 String code = note2code.get(notificationType);
395 return Objects.requireNonNullElse(code, UNKNOWN_RESPONSE_CODE);