Improve the policy name
[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.ArrayList;
32 import java.util.HashMap;
33 import java.util.LinkedList;
34 import java.util.List;
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 regresh 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      *
79      * @return The json, payload to send
80      */
81     public static String createPoliciesPayloadPdpGroup(Loop loop) {
82         HashMap<String, HashMap<String, List<JsonObject>>> pdpGroupMap = new HashMap<>();
83         for (OperationalPolicy opPolicy : loop.getOperationalPolicies()) {
84             pdpGroupMap = updatePdpGroupMap(opPolicy.getPdpGroup(), opPolicy.getPdpSubgroup(),
85                     opPolicy.getName(),
86                     opPolicy.getPolicyModel().getVersion(), pdpGroupMap);
87         }
88
89         for (MicroServicePolicy msPolicy : loop.getMicroServicePolicies()) {
90             pdpGroupMap = updatePdpGroupMap(msPolicy.getPdpGroup(), msPolicy.getPdpSubgroup(),
91                     msPolicy.getName(),
92                     msPolicy.getPolicyModel().getVersion(), pdpGroupMap);
93         }
94
95         String payload = new GsonBuilder().setPrettyPrinting().create()
96                 .toJson(generateActivatePdpGroupPayload(pdpGroupMap));
97         logger.info("PdpGroup policy payload: " + payload);
98         return payload;
99     }
100
101     private static HashMap<String, HashMap<String, List<JsonObject>>> updatePdpGroupMap(String pdpGroup,
102                                                                                         String pdpSubGroup,
103                                                                                         String policyName,
104                                                                                         String policyModelVersion,
105                                                                                         HashMap<String, HashMap<String,
106                                                                                                 List<JsonObject>>> pdpGroupMap) {
107
108         JsonObject policyJson = new JsonObject();
109         policyJson.addProperty("name", policyName);
110         policyJson.addProperty("version", policyModelVersion);
111         HashMap<String, List<JsonObject>> pdpSubGroupMap;
112         List<JsonObject> policyList;
113         if (pdpGroupMap.get(pdpGroup) == null) {
114             pdpSubGroupMap = new HashMap<String, List<JsonObject>>();
115             policyList = new LinkedList<JsonObject>();
116         }
117         else {
118             pdpSubGroupMap = pdpGroupMap.get(pdpGroup);
119             if (pdpSubGroupMap.get(pdpSubGroup) == null) {
120                 policyList = new LinkedList<JsonObject>();
121             }
122             else {
123                 policyList = (List<JsonObject>) pdpSubGroupMap.get(pdpSubGroup);
124             }
125         }
126         policyList.add(policyJson);
127         pdpSubGroupMap.put(pdpSubGroup, policyList);
128         pdpGroupMap.put(pdpGroup, pdpSubGroupMap);
129
130         return pdpGroupMap;
131     }
132
133     private static JsonObject generateActivatePdpGroupPayload(
134             HashMap<String, HashMap<String, List<JsonObject>>> pdpGroupMap) {
135         JsonArray payloadArray = new JsonArray();
136         for (Entry<String, HashMap<String, List<JsonObject>>> pdpGroupInfo : pdpGroupMap.entrySet()) {
137             JsonObject pdpGroupNode = new JsonObject();
138             JsonArray subPdpArray = new JsonArray();
139             pdpGroupNode.addProperty("name", pdpGroupInfo.getKey());
140             pdpGroupNode.add("deploymentSubgroups", subPdpArray);
141
142             JsonObject pdpSubGroupNode = new JsonObject();
143             subPdpArray.add(pdpSubGroupNode);
144
145             for (Entry<String, List<JsonObject>> pdpSubGroupInfo : pdpGroupInfo.getValue().entrySet()) {
146                 pdpSubGroupNode.addProperty("pdpType", pdpSubGroupInfo.getKey());
147                 pdpSubGroupNode.addProperty("action", "POST");
148
149                 JsonArray policyArray = new JsonArray();
150                 pdpSubGroupNode.add("policies", policyArray);
151
152                 for (JsonObject policy : pdpSubGroupInfo.getValue()) {
153                     policyArray.add(policy);
154                 }
155             }
156             payloadArray.add(pdpGroupNode);
157         }
158         JsonObject jsonObject = new JsonObject();
159         jsonObject.add("groups", payloadArray);
160         return jsonObject;
161     }
162
163     /**
164      * Generates the list of policy names that must be send/remove to/from active
165      * PDP group.
166      *
167      * @return A list of policy names
168      */
169     public static List<String> listPolicyNamesPdpGroup(Loop loop) {
170         List<String> policyNamesList = new ArrayList<>();
171         for (OperationalPolicy opPolicy : loop.getOperationalPolicies()) {
172             policyNamesList.add(opPolicy.getName());
173             for (String guardName : opPolicy.createGuardPolicyPayloads().keySet()) {
174                 policyNamesList.add(guardName);
175             }
176         }
177         for (MicroServicePolicy microServicePolicy : loop.getMicroServicePolicies()) {
178             policyNamesList.add(microServicePolicy.getName());
179         }
180         return policyNamesList;
181     }
182
183     private static ExternalComponentState findNewState(boolean found, boolean deployed) {
184
185         ExternalComponentState newState = NOT_SENT;
186         if (found && deployed) {
187             newState = SENT_AND_DEPLOYED;
188         }
189         else if (found) {
190             newState = SENT;
191         }
192         else if (deployed) {
193             newState = IN_ERROR;
194         }
195         return newState;
196     }
197
198     private static ExternalComponentState mergeStates(ExternalComponentState oldState,
199                                                       ExternalComponentState newState) {
200         return (oldState.compareTo(newState) < 0) ? newState : oldState;
201     }
202
203     /**
204      * This is a method that expect the results of the queries getPolicy and
205      * getPolicyDeployed for a unique policy (op,guard, config, etc ...). It
206      * re-computes the global policy state for each policy results given. Therefore
207      * this method is called multiple times from the camel route and must be reset
208      * for a new global policy state retrieval. The state to compute the global
209      * policy state is stored in this class.
210      */
211     @Override
212     public ExternalComponentState computeState(Exchange camelExchange) {
213         this.setState(mergeStates(this.getState(),
214                 findNewState((boolean) camelExchange.getIn().getExchange().getProperty("policyFound"),
215                         (boolean) camelExchange.getIn().getExchange().getProperty("policyDeployed"))));
216         return this.getState();
217     }
218 }