Initial TCA commit into DCAEGEN2
[dcaegen2/analytics/tca.git] / dcae-analytics-cdap-tca / src / main / java / org / openecomp / dcae / apod / analytics / cdap / tca / utils / CDAPTCAUtils.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.cdap.tca.utils;
22
23 import co.cask.cdap.api.RuntimeContext;
24 import com.google.common.base.Function;
25 import com.google.common.collect.Lists;
26 import org.openecomp.dcae.apod.analytics.cdap.common.exception.CDAPSettingsException;
27 import org.openecomp.dcae.apod.analytics.cdap.common.persistance.tca.TCAVESAlertEntity;
28 import org.openecomp.dcae.apod.analytics.cdap.tca.settings.TCAAppPreferences;
29 import org.openecomp.dcae.apod.analytics.cdap.tca.settings.TCAPolicyPreferences;
30 import org.openecomp.dcae.apod.analytics.cdap.tca.validator.TCAPolicyPreferencesValidator;
31 import org.openecomp.dcae.apod.analytics.cdap.tca.validator.TCAPreferencesValidator;
32 import org.openecomp.dcae.apod.analytics.common.AnalyticsConstants;
33 import org.openecomp.dcae.apod.analytics.model.domain.policy.tca.TCAPolicy;
34 import org.openecomp.dcae.apod.analytics.tca.utils.TCAUtils;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37
38 import java.io.IOException;
39 import java.util.Collection;
40 import java.util.List;
41 import java.util.Map;
42 import java.util.TreeMap;
43
44 import static com.google.common.collect.Lists.newArrayList;
45 import static org.openecomp.dcae.apod.analytics.cdap.common.utils.ValidationUtils.validateSettings;
46 import static org.openecomp.dcae.apod.analytics.common.AnalyticsConstants.TCA_POLICY_METRICS_PER_FUNCTIONAL_ROLE_PATH;
47
48 /**
49  * Utility Helper methods for CDAP TCA sub module.
50  *
51  * <p>
52  * @author Rajiv Singla . Creation Date: 10/24/2016.
53  */
54 public abstract class CDAPTCAUtils extends TCAUtils {
55
56     private static final Logger LOG = LoggerFactory.getLogger(CDAPTCAUtils.class);
57
58     /**
59      * Function that extracts alert message string from {@link TCAVESAlertEntity}
60      */
61     public static final Function<TCAVESAlertEntity, String> MAP_ALERT_ENTITY_TO_ALERT_STRING_FUNCTION =
62             new Function<TCAVESAlertEntity, String>() {
63                 @Override
64                 public String apply(TCAVESAlertEntity alertEntity) {
65                     return alertEntity == null ? null : alertEntity.getAlertMessage();
66                 }
67             };
68
69
70     /**
71      * Parses and validates Runtime Arguments to {@link TCAAppPreferences} object
72      *
73      * @param runtimeContext Runtime Context
74      *
75      * @return validated runtime arguments as {@link TCAAppPreferences} object
76      */
77     public static TCAAppPreferences getValidatedTCAAppPreferences(final RuntimeContext runtimeContext) {
78         // Parse runtime arguments
79         final Map<String, String> runtimeArguments = runtimeContext.getRuntimeArguments();
80         final TCAAppPreferences tcaAppPreferences =
81                 ANALYTICS_MODEL_OBJECT_MAPPER.convertValue(runtimeArguments, TCAAppPreferences.class);
82
83         // Validate runtime arguments
84         validateSettings(tcaAppPreferences, new TCAPreferencesValidator());
85
86         return tcaAppPreferences;
87     }
88
89
90     /**
91      * Extracts alert message strings from {@link TCAVESAlertEntity}
92      *
93      * @param alertEntities collection of alert entities
94      *
95      * @return List of alert message strings
96      */
97     public static List<String> extractAlertFromAlertEntities(final Collection<TCAVESAlertEntity> alertEntities) {
98         return Lists.transform(newArrayList(alertEntities), MAP_ALERT_ENTITY_TO_ALERT_STRING_FUNCTION);
99     }
100
101
102     /**
103      * Converts Runtime Arguments to {@link TCAPolicyPreferences} object
104      *
105      * @param runtimeContext CDAP Runtime Arguments
106      *
107      * @return TCA Policy Preferences
108      */
109     public static TCAPolicy getValidatedTCAPolicyPreferences(final RuntimeContext runtimeContext) {
110
111         final Map<String, String> runtimeArguments = runtimeContext.getRuntimeArguments();
112         final TreeMap<String, String> sortedRuntimeArguments = new TreeMap<>(runtimeArguments);
113
114         LOG.debug("Printing all Received Runtime Arguments:");
115         for (Map.Entry<String, String> runtimeArgsEntry : sortedRuntimeArguments.entrySet()) {
116             LOG.debug("{}:{}", runtimeArgsEntry.getKey(), runtimeArgsEntry.getValue());
117         }
118
119         TCAPolicyPreferences tcaPolicyPreferences = new TCAPolicyPreferences();
120
121         final String tcaPolicy = sortedRuntimeArguments.get(AnalyticsConstants.TCA_POLICY_JSON_KEY);
122
123         if (tcaPolicy != null) {
124
125             LOG.debug(" tcaPolicy is being read from JSON String");
126
127             // initialize unquotedTCAPolicy
128             String unquotedTCAPolicy = tcaPolicy;
129
130             //remove starting and ending quote from tcaPolicy
131             if (tcaPolicy.trim().startsWith(AnalyticsConstants.TCA_POLICY_STRING_DELIMITER) && tcaPolicy.trim().endsWith
132                     (AnalyticsConstants.TCA_POLICY_STRING_DELIMITER)) {
133                 unquotedTCAPolicy = tcaPolicy.trim().substring(1, tcaPolicy.trim().length() - 1);
134             }
135
136             try {
137                 tcaPolicyPreferences = readValue(unquotedTCAPolicy , TCAPolicyPreferences.class);
138             } catch (IOException e) {
139                 throw new CDAPSettingsException("Invalid tca policy format", LOG, e);
140             }
141
142         } else {  // old controller is being used.  Validate preferences as received from old controller
143
144             // extract TCA Policy Domain from Runtime Arguments
145             final String policyDomain = sortedRuntimeArguments.get(AnalyticsConstants.TCA_POLICY_DOMAIN_PATH);
146
147             // create new TCA Policy object
148             tcaPolicyPreferences.setDomain(policyDomain);
149
150             // filter out other non relevant fields which are not related to tca policy
151             final Map<String, String> tcaPolicyMap = filterMapByKeyNamePrefix(sortedRuntimeArguments,
152                     TCA_POLICY_METRICS_PER_FUNCTIONAL_ROLE_PATH);
153
154             // determine functional Roles
155             final Map<String, Map<String, String>> functionalRolesMap =
156                     extractSubTree(tcaPolicyMap, 2, 3, AnalyticsConstants.TCA_POLICY_DELIMITER);
157
158             // create metrics per functional role list
159             tcaPolicyPreferences.setMetricsPerFunctionalRole(
160                     createTCAPolicyMetricsPerFunctionalRoleList(functionalRolesMap));
161
162         }
163
164         // validate tca Policy Preferences
165         validateSettings(tcaPolicyPreferences, new TCAPolicyPreferencesValidator());
166
167         LOG.info("Printing Effective TCA Policy: {}", tcaPolicyPreferences);
168
169         return tcaPolicyPreferences;
170     }
171 }