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