99b021947a429116ccdd87232229be4412926617
[clamp.git] / src / main / java / org / onap / clamp / loop / components / external / PolicyComponent.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP CLAMP
4  * ================================================================================
5  * Copyright (C) 2019 AT&T Intellectual Property. All rights
6  *                             reserved.
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
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
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============================================
20  * ===================================================================
21  *
22  */
23
24 package org.onap.clamp.loop.components.external;
25
26 import com.att.eelf.configuration.EELFLogger;
27 import com.att.eelf.configuration.EELFManager;
28 import com.google.gson.GsonBuilder;
29 import com.google.gson.JsonArray;
30 import com.google.gson.JsonObject;
31
32 import java.util.ArrayList;
33 import java.util.HashMap;
34 import java.util.LinkedList;
35 import java.util.List;
36 import java.util.Map.Entry;
37
38 import javax.persistence.Transient;
39
40 import org.apache.camel.Exchange;
41 import org.onap.clamp.loop.Loop;
42 import org.onap.clamp.policy.microservice.MicroServicePolicy;
43 import org.onap.clamp.policy.operational.OperationalPolicy;
44
45 public class PolicyComponent extends ExternalComponent {
46
47     @Transient
48     private static final EELFLogger logger = EELFManager.getInstance().getLogger(PolicyComponent.class);
49
50     public static final ExternalComponentState IN_ERROR = new ExternalComponentState("IN_ERROR",
51             "There was an error during the sending to policy, the policy engine may be corrupted or inconsistent", 100);
52     public static final ExternalComponentState NOT_SENT = new ExternalComponentState("NOT_SENT",
53             "The policies defined have NOT yet been created on the policy engine", 90);
54     public static final ExternalComponentState SENT = new ExternalComponentState("SENT",
55             "The policies defined have been created but NOT deployed on the policy engine", 50);
56     public static final ExternalComponentState SENT_AND_DEPLOYED = new ExternalComponentState("SENT_AND_DEPLOYED",
57             "The policies defined have been created and deployed on the policy engine", 10);
58     public static final ExternalComponentState UNKNOWN = new ExternalComponentState("UNKNOWN",
59             "The current status is not clear. Need to regresh the status to get the current status.", 0);
60
61     /**
62      * Default constructor.
63      */
64     public PolicyComponent() {
65         /*
66          * We assume it's good by default as we will receive the state for each policy
67          * on by one, each time we increase the level we can't decrease it anymore.
68          * That's why it starts with the lowest one SENT_AND_DEPLOYED.
69          */
70         super(UNKNOWN);
71     }
72
73     @Override
74     public String getComponentName() {
75         return "POLICY";
76     }
77
78     /**
79      * Generates the Json that must be sent to policy to add all policies to Active
80      * PDP group.
81      *
82      * @return The json, payload to send
83      */
84     public static String createPoliciesPayloadPdpGroup(Loop loop) {
85         HashMap<String,HashMap<String, List<JsonObject>>> pdpGroupMap = new HashMap <String,HashMap<String, List<JsonObject>>>();
86         for (OperationalPolicy opPolicy : loop.getOperationalPolicies()) {
87             pdpGroupMap = updatePdpGroupMap(opPolicy.getPdpGroup(), opPolicy.getPdpSubgroup(),
88                   opPolicy.getName(),
89                   opPolicy.getPolicyModel().getVersion(), pdpGroupMap);
90         }
91
92         for (MicroServicePolicy msPolicy : loop.getMicroServicePolicies()) {
93             pdpGroupMap = updatePdpGroupMap(msPolicy.getPdpGroup(), msPolicy.getPdpSubgroup(),
94                     msPolicy.getName(),
95                     msPolicy.getPolicyModel().getVersion(), pdpGroupMap);
96         }
97
98         String payload = new GsonBuilder().setPrettyPrinting().create()
99               .toJson(generateActivatePdpGroupPayload(pdpGroupMap));
100         logger.info("PdpGroup policy payload: " + payload);
101         return payload;
102     }
103
104     private static HashMap<String,HashMap<String, List<JsonObject>>> updatePdpGroupMap (String pdpGroup, String pdpSubGroup, String policyName,
105         String policyModelVersion, HashMap<String,HashMap<String, List<JsonObject>>> pdpGroupMap){
106
107         JsonObject policyJson = new JsonObject();
108         policyJson.addProperty("name", policyName);
109         policyJson.addProperty("version", policyModelVersion);
110         HashMap<String, List<JsonObject>> pdpSubGroupMap;
111         List<JsonObject> policyList;
112         if (pdpGroupMap.get(pdpGroup) == null) {
113             pdpSubGroupMap = new HashMap <String, List<JsonObject>>();
114             policyList = new LinkedList<JsonObject>();
115         } else {
116             pdpSubGroupMap = pdpGroupMap.get(pdpGroup);
117             if (pdpSubGroupMap.get(pdpSubGroup) == null) {
118                 policyList = new LinkedList<JsonObject>();
119             } else {
120                 policyList = (List<JsonObject>)pdpSubGroupMap.get(pdpSubGroup);
121             }
122         }
123         policyList.add(policyJson);
124         pdpSubGroupMap.put(pdpSubGroup, policyList);
125         pdpGroupMap.put(pdpGroup, pdpSubGroupMap);
126
127         return pdpGroupMap;
128     }
129
130     private static JsonObject generateActivatePdpGroupPayload(HashMap<String,HashMap<String, List<JsonObject>>> pdpGroupMap) {
131         JsonArray payloadArray = new JsonArray();
132         for (Entry<String, HashMap<String, List<JsonObject>>> pdpGroupInfo : pdpGroupMap.entrySet()) {
133             JsonObject pdpGroupNode = new JsonObject();
134             JsonArray subPdpArray = new JsonArray();
135             pdpGroupNode.addProperty("name", pdpGroupInfo.getKey());
136             pdpGroupNode.add("deploymentSubgroups", subPdpArray);
137
138             JsonObject pdpSubGroupNode = new JsonObject();
139             subPdpArray.add(pdpSubGroupNode);
140
141             for (Entry<String, List<JsonObject>> pdpSubGroupInfo : pdpGroupInfo.getValue().entrySet()) {
142                 pdpSubGroupNode.addProperty("pdpType", pdpSubGroupInfo.getKey());
143                 pdpSubGroupNode.addProperty("action", "POST");
144
145                 JsonArray policyArray = new JsonArray();
146                 pdpSubGroupNode.add("policies", policyArray);
147
148                 for (JsonObject policy : pdpSubGroupInfo.getValue()) {
149                     policyArray.add(policy);
150                 }
151             }
152             payloadArray.add(pdpGroupNode);
153         }
154         JsonObject jsonObject = new JsonObject();
155         jsonObject.add("groups", payloadArray);
156         return jsonObject;
157     }
158
159     /**
160      * Generates the list of policy names that must be send/remove to/from active
161      * PDP group.
162      *
163      * @return A list of policy names
164      */
165     public static List<String> listPolicyNamesPdpGroup(Loop loop) {
166         List<String> policyNamesList = new ArrayList<>();
167         for (OperationalPolicy opPolicy : loop.getOperationalPolicies()) {
168             policyNamesList.add(opPolicy.getName());
169             for (String guardName : opPolicy.createGuardPolicyPayloads().keySet()) {
170                 policyNamesList.add(guardName);
171             }
172         }
173         for (MicroServicePolicy microServicePolicy : loop.getMicroServicePolicies()) {
174             policyNamesList.add(microServicePolicy.getName());
175         }
176         return policyNamesList;
177     }
178
179     private static ExternalComponentState findNewState(boolean found, boolean deployed) {
180
181         ExternalComponentState newState = NOT_SENT;
182         if (found && deployed) {
183             newState = SENT_AND_DEPLOYED;
184         } else if (found) {
185             newState = SENT;
186         } else if (deployed) {
187             newState = IN_ERROR;
188         }
189         return newState;
190     }
191
192     private static ExternalComponentState mergeStates(ExternalComponentState oldState,
193             ExternalComponentState newState) {
194         return (oldState.compareTo(newState) < 0) ? newState : oldState;
195     }
196
197     /**
198      * This is a method that expect the results of the queries getPolicy and
199      * getPolicyDeployed for a unique policy (op,guard, config, etc ...). It
200      * re-computes the global policy state for each policy results given. Therefore
201      * this method is called multiple times from the camel route and must be reset
202      * for a new global policy state retrieval. The state to compute the global
203      * policy state is stored in this class.
204      * 
205      */
206     @Override
207     public ExternalComponentState computeState(Exchange camelExchange) {
208         this.setState(mergeStates(this.getState(),
209                 findNewState((boolean) camelExchange.getIn().getExchange().getProperty("policyFound"),
210                         (boolean) camelExchange.getIn().getExchange().getProperty("policyDeployed"))));
211         return this.getState();
212     }
213 }