Removal of dead code
[clamp.git] / src / main / java / org / onap / clamp / clds / client / req / policy / OperationalPolicyYamlFormatter.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP CLAMP
4  * ================================================================================
5  * Copyright (C) 2017-2018 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  * Modifications copyright (c) 2018 Nokia
21  * ===================================================================
22  *
23  */
24 package org.onap.clamp.clds.client.req.policy;
25
26 import com.att.eelf.configuration.EELFLogger;
27 import com.att.eelf.configuration.EELFManager;
28
29 import java.io.UnsupportedEncodingException;
30 import java.net.URLEncoder;
31 import java.util.ArrayList;
32 import java.util.HashMap;
33 import java.util.Iterator;
34 import java.util.List;
35 import java.util.Map;
36
37 import javax.ws.rs.BadRequestException;
38
39 import org.onap.clamp.clds.model.properties.Global;
40 import org.onap.clamp.clds.model.properties.ModelProperties;
41 import org.onap.clamp.clds.model.properties.PolicyChain;
42 import org.onap.clamp.clds.model.properties.PolicyItem;
43 import org.onap.policy.controlloop.policy.Policy;
44 import org.onap.policy.controlloop.policy.PolicyResult;
45 import org.onap.policy.controlloop.policy.Target;
46 import org.onap.policy.controlloop.policy.TargetType;
47 import org.onap.policy.controlloop.policy.builder.BuilderException;
48 import org.onap.policy.controlloop.policy.builder.ControlLoopPolicyBuilder;
49 import org.onap.policy.controlloop.policy.builder.Message;
50 import org.onap.policy.controlloop.policy.builder.Results;
51 import org.onap.policy.sdc.Resource;
52 import org.onap.policy.sdc.ResourceType;
53 import org.onap.policy.sdc.Service;
54
55 public class OperationalPolicyYamlFormatter {
56     private static final EELFLogger logger = EELFManager.getInstance().getLogger(OperationalPolicyYamlFormatter.class);
57
58     protected OperationalPolicyYamlFormatter() {
59     }
60
61     /**
62      * Format Operational OpenLoop Policy yaml.
63      *
64      * @param prop
65      * @param modelElementId
66      * @param policyChain
67      * @return
68      * @throws BuilderException
69      * @throws UnsupportedEncodingException
70      */
71     public static String formatOpenLoopYaml(ModelProperties prop, String modelElementId, PolicyChain policyChain)
72         throws BuilderException, UnsupportedEncodingException {
73         // get property objects
74         Global global = prop.getGlobal();
75         prop.setCurrentModelElementId(modelElementId);
76         prop.setPolicyUniqueId(policyChain.getPolicyId());
77         // convert values to SDC objects
78         Service service = new Service(global.getService());
79         Resource[] vfResources = convertToResources(global.getResourceVf(), ResourceType.VF);
80         // create builder
81         ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(prop.getControlName(),
82             policyChain.getTimeout(), service, vfResources);
83         // builder.setTriggerPolicy(refProp.getStringValue("op.openloop.policy"));
84         // Build the specification
85         Results results = builder.buildSpecification();
86         validate(results);
87         return URLEncoder.encode(results.getSpecification(), "UTF-8");
88     }
89
90     public static String formatYaml(ModelProperties prop, String modelElementId, PolicyChain policyChain)
91         throws BuilderException, UnsupportedEncodingException {
92         // get property objects
93         prop.setCurrentModelElementId(modelElementId);
94         prop.setPolicyUniqueId(policyChain.getPolicyId());
95
96         // create builder
97         ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(prop.getControlName(),
98             policyChain.getTimeout());
99         // process each policy
100         Map<String, Policy> policyObjMap = new HashMap<>();
101         List<PolicyItem> policyItemList = orderParentFirst(policyChain.getPolicyItems());
102         for (PolicyItem policyItem : policyItemList) {
103             String policyName = policyItem.getRecipe() + " Policy";
104             Target target = new Target();
105             target.setType(TargetType.VM);
106             // We can send target type as VM/VNF for most of recipes
107             if (policyItem.getRecipeLevel() != null && !policyItem.getRecipeLevel().isEmpty()) {
108                 target.setType(TargetType.valueOf(policyItem.getRecipeLevel()));
109             }
110             target.setResourceID(policyItem.getTargetResourceId());
111             String actor = policyItem.getActor();
112             Map<String, String> payloadMap = policyItem.getRecipePayload();
113             Policy policyObj;
114             if (policyItemList.indexOf(policyItem) == 0) {
115                 String policyDescription = policyItem.getRecipe()
116                     + " Policy - the trigger (no parent) policy - created by CLDS";
117                 policyObj = builder.setTriggerPolicy(policyName, policyDescription, actor, target,
118                     policyItem.getRecipe(), payloadMap, policyItem.getMaxRetries(), policyItem.getRetryTimeLimit());
119             } else {
120                 Policy parentPolicyObj = policyObjMap.get(policyItem.getParentPolicy());
121                 String policyDescription = policyItem.getRecipe() + " Policy - triggered conditionally by "
122                     + parentPolicyObj.getName() + " - created by CLDS";
123                 policyObj = builder.setPolicyForPolicyResult(policyName, policyDescription, actor, target,
124                     policyItem.getRecipe(), payloadMap, policyItem.getMaxRetries(), policyItem.getRetryTimeLimit(),
125                     parentPolicyObj.getId(), convertToPolicyResults(policyItem.getParentPolicyConditions()));
126                 logger.info("policyObj.id=" + policyObj.getId() + "; parentPolicyObj.id=" + parentPolicyObj.getId());
127             }
128             policyObjMap.put(policyItem.getId(), policyObj);
129         }
130         // Build the specification
131         Results results = builder.buildSpecification();
132         validate(results);
133         return URLEncoder.encode(results.getSpecification(), "UTF-8");
134     }
135
136     protected static List<PolicyItem> orderParentFirst(List<PolicyItem> inOrigList) {
137         List<PolicyItem> inList = new ArrayList<>();
138         inList.addAll(inOrigList);
139         List<PolicyItem> outList = new ArrayList<>();
140         int prevSize = 0;
141         while (!inList.isEmpty()) {
142             // check if there's a loop in the policy chain (the inList should
143             // have been reduced by at least one)
144             if (inList.size() == prevSize) {
145                 throw new BadRequestException("Operation Policy validation problem: loop in Operation Policy chain");
146             }
147             prevSize = inList.size();
148             // the following loop should remove at least one PolicyItem from the
149             // inList
150             Iterator<PolicyItem> inListItr = inList.iterator();
151             while (inListItr.hasNext()) {
152                 PolicyItem inItem = inListItr.next();
153                 // check for trigger policy (no parent)
154                 String parent = inItem.getParentPolicy();
155                 if (parent == null || parent.length() == 0) {
156                     if (!outList.isEmpty()) {
157                         throw new BadRequestException(
158                             "Operation Policy validation problem: more than one trigger policy");
159                     } else {
160                         outList.add(inItem);
161                         inListItr.remove();
162                     }
163                 } else {
164                     // check if this PolicyItem's parent has been processed
165                     for (PolicyItem outItem : outList) {
166                         if (outItem.getId().equals(parent)) {
167                             // if the inItem parent is already in the outList,
168                             // then add inItem to outList and remove from inList
169                             outList.add(inItem);
170                             inListItr.remove();
171                             break;
172                         }
173                     }
174                 }
175             }
176         }
177         return outList;
178     }
179
180     protected static void validate(Results results) {
181         if (results.isValid()) {
182             logger.info("results.getSpecification()=" + results.getSpecification());
183         } else {
184             // throw exception with error info
185             StringBuilder sb = new StringBuilder();
186             sb.append("Operation Policy validation problem: ControlLoopPolicyBuilder failed with following messages: ");
187             for (Message message : results.getMessages()) {
188                 sb.append(message.getMessage());
189                 sb.append("; ");
190             }
191             throw new BadRequestException(sb.toString());
192         }
193     }
194
195     protected static Resource[] convertToResources(List<String> stringList, ResourceType resourceType) {
196         if (stringList == null || stringList.isEmpty()) {
197             return new Resource[0];
198         }
199         return stringList.stream().map(stringElem -> new Resource(stringElem, resourceType)).toArray(Resource[]::new);
200     }
201
202     protected static PolicyResult[] convertToPolicyResults(List<String> prList) {
203         if (prList == null || prList.isEmpty()) {
204             return new PolicyResult[0];
205         }
206         return prList.stream().map(PolicyResult::toResult).toArray(PolicyResult[]::new);
207     }
208
209 }