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