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.Properties;
34 import java.util.UUID;
35 import java.util.concurrent.TimeUnit;
36 import org.apache.commons.collections4.CollectionUtils;
37 import org.onap.policy.controlloop.ControlLoopNotificationType;
38 import org.onap.policy.controlloop.ControlLoopOperation;
39 import org.onap.policy.controlloop.VirtualControlLoopNotification;
40 import org.onap.policy.drools.persistence.SystemPersistenceConstants;
41 import org.onap.policy.drools.system.PolicyController;
42 import org.onap.policy.drools.system.PolicyEngineConstants;
43 import org.onap.policy.drools.utils.logging.MdcTransaction;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
48 * Control Loop Metrics Tracker Implementation.
50 class CacheBasedControlLoopMetricsManager implements ControlLoopMetrics {
52 private static final String UNEXPECTED_NOTIFICATION_TYPE = "unexpected notification type {} in notification {}";
54 private static final Logger logger = LoggerFactory.getLogger(CacheBasedControlLoopMetricsManager.class);
56 private LoadingCache<UUID, VirtualControlLoopNotification> cache;
57 private long cacheSize = ControlLoopMetricsFeature.CL_CACHE_TRANS_SIZE_DEFAULT;
59 private long transactionTimeout = ControlLoopMetricsFeature.CL_CACHE_TRANS_TIMEOUT_SECONDS_DEFAULT;
62 * Numeric response code.
64 private static final Map<String, String> note2code = Map.of(
65 ControlLoopNotificationType.ACTIVE.name(), "100",
66 ControlLoopNotificationType.REJECTED.name(), "200",
67 ControlLoopNotificationType.OPERATION.name(), "300",
68 ControlLoopNotificationType.OPERATION_SUCCESS.name(), "301",
69 ControlLoopNotificationType.OPERATION_FAILURE.name(), "302",
70 ControlLoopNotificationType.FINAL_FAILURE.name(), "400",
71 ControlLoopNotificationType.FINAL_SUCCESS.name(), "401",
72 ControlLoopNotificationType.FINAL_OPENLOOP.name(), "402"
75 private static final String UNKNOWN_RESPONSE_CODE = "900";
77 public CacheBasedControlLoopMetricsManager() {
79 Properties properties = SystemPersistenceConstants.getManager()
80 .getProperties(ControlLoopMetricsFeature.CONFIGURATION_PROPERTIES_NAME);
86 Long.parseLong(properties.getProperty(ControlLoopMetricsFeature.CL_CACHE_TRANS_SIZE_PROPERTY,
87 "" + ControlLoopMetricsFeature.CL_CACHE_TRANS_SIZE_DEFAULT));
88 } catch (Exception e) {
89 logger.warn("{}:{} property cannot be accessed", ControlLoopMetricsFeature.CONFIGURATION_PROPERTIES_NAME,
90 ControlLoopMetricsFeature.CL_CACHE_TRANS_SIZE_PROPERTY, e);
93 /* transaction timeout */
96 this.transactionTimeout = Long
97 .parseLong(properties.getProperty(ControlLoopMetricsFeature.CL_CACHE_TRANS_TIMEOUT_SECONDS_PROPERTY,
98 "" + ControlLoopMetricsFeature.CL_CACHE_TRANS_TIMEOUT_SECONDS_DEFAULT));
99 } catch (Exception e) {
100 logger.warn("{}:{} property cannot be accessed", ControlLoopMetricsFeature.CONFIGURATION_PROPERTIES_NAME,
101 ControlLoopMetricsFeature.CL_CACHE_TRANS_TIMEOUT_SECONDS_PROPERTY, e);
104 resetCache(this.cacheSize, this.transactionTimeout);
108 public void resetCache(long cacheSize, long transactionTimeout) {
109 this.cacheSize = cacheSize;
110 this.transactionTimeout = transactionTimeout;
112 CacheLoader<UUID, VirtualControlLoopNotification> loader = new CacheLoader<>() {
115 public VirtualControlLoopNotification load(UUID key) {
120 RemovalListener<UUID, VirtualControlLoopNotification> listener = notification -> {
121 if (notification.wasEvicted()) {
122 evicted(notification.getValue());
123 } else if (logger.isInfoEnabled()) {
124 logger.info("REMOVAL: {} because of {}", notification.getValue().getRequestId(),
125 notification.getCause().name());
129 synchronized (this) {
130 if (this.cache != null) {
131 this.cache.cleanUp();
132 this.cache.invalidateAll();
135 this.cache = CacheBuilder.newBuilder().maximumSize(this.cacheSize)
136 .expireAfterWrite(transactionTimeout, TimeUnit.SECONDS).removalListener(listener).build(loader);
141 public void refresh() {
142 this.cache.cleanUp();
146 public List<UUID> getTransactionIds() {
147 return new ArrayList<>(this.cache.asMap().keySet());
151 public List<VirtualControlLoopNotification> getTransactions() {
152 return new ArrayList<>(this.cache.asMap().values());
156 public void transactionEvent(PolicyController controller, VirtualControlLoopNotification notification) {
157 if (!isNotificationValid(notification)) {
161 setNotificationValues(controller, notification);
163 switch (notification.getNotification()) {
168 endTransaction(controller, notification);
172 case OPERATION_SUCCESS:
173 case 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()).setTargetEntity(notification.getTarget())
247 .setStartTime(notification.getNotificationTime().toInstant()).setEndTime(Instant.now())
248 .setResponseDescription("EVICTED").setStatusCode(false).metric().resetTransaction();
252 public long getCacheSize() {
253 return this.cacheSize;
257 public void setMaxCacheSize(long cacheSize) {
258 this.cacheSize = cacheSize;
262 public long getTransactionTimeout() {
263 return this.transactionTimeout;
267 public void setTransactionTimeout(long transactionTimeout) {
268 this.transactionTimeout = transactionTimeout;
272 public long getCacheOccupancy() {
273 return this.cache.size();
276 protected void metric(VirtualControlLoopNotification notification) {
277 MdcTransaction trans = getMdcTransaction(notification);
278 List<ControlLoopOperation> operations = notification.getHistory();
279 switch (notification.getNotification()) {
281 trans.setStatusCode(true).metric().resetTransaction();
284 operation(trans.setStatusCode(true), operations).metric().resetTransaction();
286 case OPERATION_SUCCESS:
287 operation(trans.setStatusCode(true), operations).metric().transaction().resetTransaction();
289 case OPERATION_FAILURE:
290 operation(trans.setStatusCode(false), operations).metric().transaction().resetTransaction();
294 logger.warn(UNEXPECTED_NOTIFICATION_TYPE,
295 notification.getNotification(), notification);
300 private MdcTransaction getMdcTransaction(VirtualControlLoopNotification notification) {
301 return MdcTransaction
302 .newTransaction(notification.getRequestId().toString(), notification.getFrom())
303 .setServiceName(notification.getClosedLoopControlName())
304 .setServiceInstanceId(notification.getPolicyScope()
305 + ":" + notification.getPolicyName() + ":" + notification.getPolicyVersion())
306 .setProcessKey("" + notification.getAai())
307 .setTargetEntity(notification.getTargetType() + "." + notification.getTarget())
308 .setResponseCode((notification.getNotification() != null)
309 ? notificationTypeToResponseCode(notification.getNotification().name())
310 : UNKNOWN_RESPONSE_CODE)
311 .setCustomField1((notification.getNotification() != null)
312 ? notification.getNotification().name() : "")
313 .setResponseDescription(notification.getMessage())
314 .setClientIpAddress(notification.getClosedLoopEventClient());
317 protected MdcTransaction operation(MdcTransaction trans, List<ControlLoopOperation> operations) {
318 if (CollectionUtils.isEmpty(operations)) {
322 ControlLoopOperation operation = operations.get(operations.size() - 1);
324 if (operation.getActor() != null) {
325 trans.setTargetServiceName(operation.getActor() + "." + operation.getOperation());
328 if (operation.getTarget() != null) {
329 trans.setTargetVirtualEntity(operation.getTarget());
332 if (operation.getSubRequestId() != null) {
333 trans.setInvocationId(operation.getSubRequestId());
336 if (operation.getOutcome() != null) {
337 trans.setResponseDescription(operation.getOutcome() + ":" + operation.getMessage());
340 if (operation.getStart() != null) {
341 trans.setStartTime(operation.getStart());
344 if (operation.getEnd() != null) {
345 trans.setEndTime(operation.getEnd());
351 protected void transaction(PolicyController controller,
352 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);
376 PolicyEngineConstants.getManager().transaction(controller.getName(),
377 notification.getClosedLoopControlName(), trans.getMetric());
378 } catch (RuntimeException rex) {
379 logger.info("error pegging control loop transaction: {}", trans.getMetric(), rex);
382 trans.transaction().resetTransaction();
386 public String toString() {
387 return "CacheBasedControlLoopMetricsManager{" + "cacheSize=" + cacheSize
388 + ",transactionTimeout="
391 + getCacheOccupancy()
395 private String notificationTypeToResponseCode(String notificationType) {
396 String code = note2code.get(notificationType);
397 return Objects.requireNonNullElse(code, UNKNOWN_RESPONSE_CODE);