Initial TCA commit into DCAEGEN2
[dcaegen2/analytics/tca.git] / dcae-analytics-tca / src / main / java / org / openecomp / dcae / apod / analytics / tca / processor / TCACEFPolicyThresholdsProcessor.java
1 /*
2  * ===============================LICENSE_START======================================
3  *  dcae-analytics
4  * ================================================================================
5  *    Copyright © 2017 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
10  *
11  *          http://www.apache.org/licenses/LICENSE-2.0
12  *
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===========================================
19  */
20
21 package org.openecomp.dcae.apod.analytics.tca.processor;
22
23 import com.google.common.base.Optional;
24 import com.google.common.collect.Table;
25 import org.openecomp.dcae.apod.analytics.common.exception.MessageProcessingException;
26 import org.openecomp.dcae.apod.analytics.model.domain.cef.EventListener;
27 import org.openecomp.dcae.apod.analytics.model.domain.policy.tca.MetricsPerFunctionalRole;
28 import org.openecomp.dcae.apod.analytics.model.domain.policy.tca.TCAPolicy;
29 import org.openecomp.dcae.apod.analytics.model.domain.policy.tca.Threshold;
30 import org.openecomp.dcae.apod.analytics.tca.utils.TCAUtils;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
33
34 import java.util.HashMap;
35 import java.util.List;
36 import java.util.Map;
37 import java.util.Set;
38
39 import javax.annotation.Nonnull;
40
41 /**
42  *<p>
43  *     TCA CEF Policy Threshold processor
44  *     <br>
45  *     Pre Conditions: Domain and Functional Role must be present in CEF Event Listener Object
46  *</p>
47  *
48  * @author Rajiv Singla . Creation Date: 11/9/2016.
49  */
50 public class TCACEFPolicyThresholdsProcessor extends AbstractTCAECEFPolicyProcessor {
51
52     private static final long serialVersionUID = 1L;
53
54     private static final Logger LOG = LoggerFactory.getLogger(TCACEFPolicyThresholdsProcessor.class);
55
56     @Override
57     public TCACEFProcessorContext preProcessor(@Nonnull TCACEFProcessorContext processorContext) {
58         // validates Domain and Functional Role are present
59         final EventListener eventListener = processorContext.getCEFEventListener();
60         final String domain = eventListener.getEvent().getCommonEventHeader().getDomain();
61         final String functionalRole = eventListener.getEvent().getCommonEventHeader().getFunctionalRole();
62         if (domain == null || functionalRole == null) {
63             final String errorMessage = "CEF Event Listener domain or functional role not Present. " +
64                     "Invalid use of this Processor";
65             throw new MessageProcessingException(errorMessage, LOG, new IllegalArgumentException(errorMessage));
66         }
67         return super.preProcessor(processorContext);
68     }
69
70     @Override
71     public String getProcessorDescription() {
72         return "Applies TCA Policy rules to incoming CEF message. If any thresholds are violated attaches max " +
73                 "Severity violated threshold to TCA Processor Context";
74     }
75
76     @Override
77     public TCACEFProcessorContext processMessage(TCACEFProcessorContext processorContext) {
78
79         final String cefMessage = processorContext.getMessage();
80
81         // Determine domain and functional Role
82         final EventListener eventListener = processorContext.getCEFEventListener();
83         final String functionalRole = eventListener.getEvent().getCommonEventHeader().getFunctionalRole();
84
85         // Get Table containing Functional Role and Thresholds Field Path
86         final TCAPolicy tcaPolicy = processorContext.getTCAPolicy();
87         final Table<String, String, List<Threshold>> functionalRoleFieldPathsTable =
88                 TCAUtils.getPolicyFRThresholdsTableSupplier(tcaPolicy).get();
89
90         // Get Policy Field Paths for that functional Role
91         final Map<String, List<Threshold>> policyFieldPathsMap = functionalRoleFieldPathsTable.row(functionalRole);
92         final Set<String> policyFieldPaths = policyFieldPathsMap.keySet();
93
94         // Get Json Values for Policy Fields
95         final Map<String, List<Long>> messageFieldValuesMap = TCAUtils.getJsonPathValue(cefMessage, policyFieldPaths);
96
97         // Determine all violated thresholds per message field Path
98         final Map<String, Threshold> violatedThresholdsMap = new HashMap<>();
99         for (Map.Entry<String, List<Long>> messageFieldValuesMapEntry : messageFieldValuesMap.entrySet()) {
100             final String messageFieldPath = messageFieldValuesMapEntry.getKey();
101             final List<Threshold> messageFieldAssociatedPolicyThresholds = policyFieldPathsMap.get(messageFieldPath);
102             if (messageFieldAssociatedPolicyThresholds != null) {
103                 final Optional<Threshold> thresholdOptional = TCAUtils.thresholdCalculator(
104                         messageFieldValuesMapEntry.getValue(), messageFieldAssociatedPolicyThresholds);
105                 if (thresholdOptional.isPresent()) {
106                     violatedThresholdsMap.put(messageFieldPath, thresholdOptional.get());
107                 }
108             }
109         }
110
111         // No threshold were violated
112         if (violatedThresholdsMap.isEmpty()) {
113
114             final String terminationMessage = "No Policy Threshold violated by the VES CEF Message.";
115             setTerminatingProcessingMessage(terminationMessage, processorContext);
116
117         } else {
118
119             // If there are policy violations then determine max priority violation
120             final Threshold maxSeverityThresholdViolation =
121                     TCAUtils.prioritizeThresholdViolations(violatedThresholdsMap);
122             final MetricsPerFunctionalRole violatedMetrics = TCAUtils.createViolatedMetrics(tcaPolicy,
123                     maxSeverityThresholdViolation, functionalRole);
124             // attach policy violation to processor Context
125             processorContext.setMetricsPerFunctionalRole(violatedMetrics);
126
127             final String finishMessage = String.format("Policy Threshold violation detected for threshold: %s",
128                     maxSeverityThresholdViolation);
129             setFinishedProcessingMessage(finishMessage, processorContext);
130
131         }
132
133         return processorContext;
134     }
135 }