1fc3608203b05373442f6936eb7287b9e6048d01
[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      * Format Operational OpenLoop Policy yaml.
62      *
63      * @param prop
64      * @param modelElementId
65      * @param policyChain
66      * @return
67      * @throws BuilderException
68      * @throws UnsupportedEncodingException
69      */
70     public static String formatOpenLoopYaml(ModelProperties prop, String modelElementId,
71         PolicyChain policyChain) throws BuilderException, UnsupportedEncodingException {
72         // get property objects
73         Global global = prop.getGlobal();
74         prop.setCurrentModelElementId(modelElementId);
75         prop.setPolicyUniqueId(policyChain.getPolicyId());
76         // convert values to SDC objects
77         Service service = new Service(global.getService());
78         Resource[] vfResources = convertToResources(global.getResourceVf(), ResourceType.VF);
79         // create builder
80         ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(prop.getControlName(),
81             policyChain.getTimeout(), service, vfResources);
82         // builder.setTriggerPolicy(refProp.getStringValue("op.openloop.policy"));
83         // Build the specification
84         Results results = builder.buildSpecification();
85         validate(results);
86         return URLEncoder.encode(results.getSpecification(), "UTF-8");
87     }
88
89     public static String formatYaml(ModelProperties prop, String modelElementId,
90         PolicyChain policyChain) throws BuilderException, UnsupportedEncodingException {
91         // get property objects
92         Global global = prop.getGlobal();
93         prop.setCurrentModelElementId(modelElementId);
94         prop.setPolicyUniqueId(policyChain.getPolicyId());
95         // convert values to SDC objects
96         Service service = new Service(global.getService());
97         Resource[] vfResources = convertToResources(global.getResourceVf(), ResourceType.VF);
98         Resource[] vfcResources = convertToResources(global.getResourceVfc(), ResourceType.VFC);
99         // create builder
100         ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(prop.getControlName(),
101             policyChain.getTimeout(), service, vfResources);
102         builder.addResource(vfcResources);
103         // process each policy
104         Map<String, Policy> policyObjMap = new HashMap<>();
105         List<PolicyItem> policyItemList = orderParentFirst(policyChain.getPolicyItems());
106         for (PolicyItem policyItem : policyItemList) {
107             String policyName = policyItem.getRecipe() + " Policy";
108             Target target = new Target();
109             target.setType(TargetType.VM);
110             // We can send target type as VM/VNF for most of recipes
111             if (policyItem.getRecipeLevel() != null && !policyItem.getRecipeLevel().isEmpty()) {
112                 target.setType(TargetType.valueOf(policyItem.getRecipeLevel()));
113             }
114             target.setResourceID(policyItem.getTargetResourceId());
115             String actor = policyItem.getActor();
116             Map<String, String> payloadMap = policyItem.getRecipePayload();
117             Policy policyObj;
118             if (policyItemList.indexOf(policyItem) == 0) {
119                 String policyDescription = policyItem.getRecipe()
120                     + " Policy - the trigger (no parent) policy - created by CLDS";
121                 policyObj = builder.setTriggerPolicy(policyName, policyDescription, actor, target,
122                     policyItem.getRecipe(), payloadMap, policyItem.getMaxRetries(), policyItem.getRetryTimeLimit());
123             } else {
124                 Policy parentPolicyObj = policyObjMap.get(policyItem.getParentPolicy());
125                 String policyDescription = policyItem.getRecipe() + " Policy - triggered conditionally by "
126                     + parentPolicyObj.getName() + " - created by CLDS";
127                 policyObj = builder.setPolicyForPolicyResult(policyName, policyDescription, actor, target,
128                     policyItem.getRecipe(), payloadMap, policyItem.getMaxRetries(), policyItem.getRetryTimeLimit(),
129                     parentPolicyObj.getId(), convertToPolicyResults(policyItem.getParentPolicyConditions()));
130                 logger.info("policyObj.id=" + policyObj.getId() + "; parentPolicyObj.id=" + parentPolicyObj.getId());
131             }
132             policyObjMap.put(policyItem.getId(), policyObj);
133         }
134         // Build the specification
135         Results results = builder.buildSpecification();
136         validate(results);
137         return URLEncoder.encode(results.getSpecification(), "UTF-8");
138     }
139
140     protected static List<PolicyItem> orderParentFirst(List<PolicyItem> inOrigList) {
141         List<PolicyItem> inList = new ArrayList<>();
142         inList.addAll(inOrigList);
143         List<PolicyItem> outList = new ArrayList<>();
144         int prevSize = 0;
145         while (!inList.isEmpty()) {
146             // check if there's a loop in the policy chain (the inList should
147             // have been reduced by at least one)
148             if (inList.size() == prevSize) {
149                 throw new BadRequestException("Operation Policy validation problem: loop in Operation Policy chain");
150             }
151             prevSize = inList.size();
152             // the following loop should remove at least one PolicyItem from the
153             // inList
154             Iterator<PolicyItem> inListItr = inList.iterator();
155             while (inListItr.hasNext()) {
156                 PolicyItem inItem = inListItr.next();
157                 // check for trigger policy (no parent)
158                 String parent = inItem.getParentPolicy();
159                 if (parent == null || parent.length() == 0) {
160                     if (!outList.isEmpty()) {
161                         throw new BadRequestException(
162                             "Operation Policy validation problem: more than one trigger policy");
163                     } else {
164                         outList.add(inItem);
165                         inListItr.remove();
166                     }
167                 } else {
168                     // check if this PolicyItem's parent has been processed
169                     for (PolicyItem outItem : outList) {
170                         if (outItem.getId().equals(parent)) {
171                             // if the inItem parent is already in the outList,
172                             // then add inItem to outList and remove from inList
173                             outList.add(inItem);
174                             inListItr.remove();
175                             break;
176                         }
177                     }
178                 }
179             }
180         }
181         return outList;
182     }
183
184     protected static void validate(Results results) {
185         if (results.isValid()) {
186             logger.info("results.getSpecification()=" + results.getSpecification());
187         } else {
188             // throw exception with error info
189             StringBuilder sb = new StringBuilder();
190             sb.append("Operation Policy validation problem: ControlLoopPolicyBuilder failed with following messages: ");
191             for (Message message : results.getMessages()) {
192                 sb.append(message.getMessage());
193                 sb.append("; ");
194             }
195             throw new BadRequestException(sb.toString());
196         }
197     }
198
199
200     protected static Resource[] convertToResources(List<String> stringList, ResourceType resourceType) {
201         if (stringList == null || stringList.isEmpty()) {
202             return new Resource[0];
203         }
204         return stringList.stream().map(stringElem -> new Resource(stringElem, resourceType)).toArray(Resource[]::new);
205     }
206
207     protected static PolicyResult[] convertToPolicyResults(List<String> prList) {
208         if (prList == null || prList.isEmpty()) {
209             return new PolicyResult[0];
210         }
211         return prList.stream().map(PolicyResult::toResult).toArray(PolicyResult[]::new);
212     }
213
214 }