a73138766ae59023c707617093aae2d08df13ece
[policy/distribution.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2018 Ericsson. All rights reserved.
4  *  Copyright (C) 2019 Nordix Foundation.
5  * ================================================================================
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *
18  * SPDX-License-Identifier: Apache-2.0
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.distribution.reception.decoding.pdpx;
23
24 import com.google.common.collect.ImmutableMap;
25 import com.google.gson.Gson;
26 import com.google.gson.GsonBuilder;
27 import com.google.gson.reflect.TypeToken;
28
29 import java.util.ArrayList;
30 import java.util.HashMap;
31 import java.util.List;
32 import java.util.Map;
33 import java.util.regex.Matcher;
34 import java.util.regex.Pattern;
35
36 import org.onap.policy.distribution.reception.decoding.PolicyDecodingException;
37 import org.onap.sdc.tosca.parser.api.ISdcCsarHelper;
38 import org.onap.sdc.toscaparser.api.CapabilityAssignment;
39 import org.onap.sdc.toscaparser.api.CapabilityAssignments;
40 import org.onap.sdc.toscaparser.api.NodeTemplate;
41 import org.onap.sdc.toscaparser.api.RequirementAssignment;
42 import org.onap.sdc.toscaparser.api.RequirementAssignments;
43 import org.onap.sdc.toscaparser.api.elements.Metadata;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46
47 /**
48  * Extract concerned info from NodeTemplate, currently ONLY HPA Feature.
49  *
50  * @author Libo Zhu (libo.zhu@intel.com)
51  */
52 public class ExtractFromNode {
53
54     private static final Logger LOGGER = LoggerFactory.getLogger(ExtractFromNode.class);
55
56     private static final String CONFIGURATION_VALUE = "configurationValue";
57     private static final String VDU_TYPE = "tosca.nodes.nfv.Vdu.Compute";
58     private static final String VDU_CP_TYPE = "tosca.nodes.nfv.VduCp";
59     private static final String VIRTUAL_MEM_SIZE_PATH = "virtual_memory#virtual_mem_size";
60     private static final String NUM_VIRTUAL_CPU_PATH = "virtual_cpu#num_virtual_cpu";
61     private static final String CPU_ARCHITECTURE_PATH = "virtual_cpu#cpu_architecture";
62     private static final String MEMORY_PAGE_SIZE_PATH = "virtual_memory#vdu_mem_requirements#memoryPageSize";
63     private static final String NETWORK_INTERFACE_TYPE_PATH =
64             "virtual_network_interface_requirements#network_interface_requirements#interfaceType";
65     private static final String NETWORK_PCI_PATH =
66             "virtual_network_interface_requirements#nic_io_requirements#logical_node_requirements";
67     private static final String BASIC_CAPABILITIES_HPA_FEATURE = "basicCapabilities";
68     private static final String HUGE_PAGES_HPA_FEATURE = "hugePages";
69     private static final Map<String, String> NETWORK_HPA_FEATURE_MAP =
70             ImmutableMap.of("SR-IOV", "sriovNICNetwork", "PCI-Passthrough", "pciePassthrough");
71     private static final Pattern PATTERN = Pattern.compile("(\\D*)(\\d+)(\\D*)");
72     private ISdcCsarHelper sdcCsarHelper;
73     final Gson gson = new GsonBuilder().serializeNulls().setPrettyPrinting().disableHtmlEscaping().create();
74
75     public void setSdcCsarHelper(final ISdcCsarHelper sdcCsarHelper) {
76         this.sdcCsarHelper = sdcCsarHelper;
77     }
78
79     /**
80      * ExtractInfo from VNF , each VNF may includes more than one VDUs and CPs return new generated PdpxPolicy if it has
81      * got Hpa feature info or else return null.
82      *
83      * @param node the NodeTemplate
84      *
85      * @return the extracted info from input node
86      *
87      * @throws PolicyDecodingException if extract fails
88      */
89     public Content extractInfo(final NodeTemplate node) throws PolicyDecodingException {
90         final Metadata metaData = sdcCsarHelper.getNodeTemplateMetadata(node);
91         final Metadata metaDataOfService = sdcCsarHelper.getServiceMetadata();
92         LOGGER.debug("the meta data of this nodetemplate = {}", metaData);
93         final List<NodeTemplate> lnodeChild = sdcCsarHelper.getNodeTemplateChildren(node);
94         LOGGER.debug("the size of lnodeChild = {}", lnodeChild.size());
95
96         // Store all the VDUs under one VNF
97         final List<NodeTemplate> lnodeVdu = new ArrayList<>();
98         // Store all the Cps under one VNF
99         final List<NodeTemplate> lnodeVduCp = new ArrayList<>();
100         for (final NodeTemplate nodeChild : lnodeChild) {
101             final String type = sdcCsarHelper.getTypeOfNodeTemplate(nodeChild);
102             LOGGER.debug("the type of this nodeChild = {}", type);
103             LOGGER.debug("the meta data of this nodeChild = {}", sdcCsarHelper.getNodeTemplateMetadata(nodeChild));
104             if (type.equalsIgnoreCase(VDU_TYPE)) {
105                 lnodeVdu.add(nodeChild);
106             } else if (type.equalsIgnoreCase(VDU_CP_TYPE)) {
107                 lnodeVduCp.add(nodeChild);
108             }
109         }
110         LOGGER.debug("the size of vdu is = {}", lnodeVdu.size());
111         LOGGER.debug("the size of cp is = {}", lnodeVduCp.size());
112
113         final Content content = new Content();
114         content.getResources().add(metaData.getValue("name"));
115         content.getServices().add(metaDataOfService.getValue("name"));
116         content.setIdentity(content.getPolicyType() + "_" + metaData.getValue("name"));
117         extractInfoVdu(lnodeVdu, content);
118         extractInfoVduCp(lnodeVduCp, content);
119         if (content.getFlavorFeatures().isEmpty()) {
120             return null;
121         }
122         return content;
123     }
124
125
126     /**
127      * ExtractInfofromVdu, supported hpa features, All under the capability of tosca.nodes.nfv.Vdu.Compute.
128      *
129      * @param lnodeVdu the list of Vdu node
130      *
131      * @param content to be change based on lnodeVdu
132      */
133     public void extractInfoVdu(final List<NodeTemplate> lnodeVdu, final Content content) {
134         // each VDU <=> FlavorFeature
135         for (final NodeTemplate node : lnodeVdu) {
136             final Attribute flavorAttribute = new Attribute();
137             flavorAttribute.setAttributeName("flavorName");
138             flavorAttribute.setAttributeValue("");
139             final Directive flavorDirective = new Directive();
140             flavorDirective.setType("flavor_directives");
141             flavorDirective.getAttributes().add(flavorAttribute);
142             final FlavorFeature flavorFeature = new FlavorFeature();
143             flavorFeature.setId(node.toString());
144             LOGGER.debug("the name of node = {}", node);
145             flavorFeature.getDirectives().add(flavorDirective);
146
147             final CapabilityAssignments capabilityAssignments = sdcCsarHelper.getCapabilitiesOf(node);
148             final CapabilityAssignment capabilityAssignment =
149                     capabilityAssignments.getCapabilityByName("virtual_compute");
150             if (capabilityAssignment != null) {
151                 generateBasicCapability(capabilityAssignment, flavorFeature);
152                 generateHugePages(capabilityAssignment, flavorFeature);
153             }
154             content.getFlavorFeatures().add(flavorFeature);
155         }
156     }
157
158     /**
159      * GenerateBasicCapability, supported hpa features, All under the capability of tosca.nodes.nfv.Vdu.Compute.
160      *
161      * @param capabilityAssignment represents the capability of node
162      *
163      * @param flavorFeature represents all the features of specified flavor
164      */
165     private void generateBasicCapability(final CapabilityAssignment capabilityAssignment,
166             final FlavorFeature flavorFeature) {
167         // the format is xxx MB/GB like 4096 MB
168         final String virtualMemSize =
169                 sdcCsarHelper.getCapabilityPropertyLeafValue(capabilityAssignment, VIRTUAL_MEM_SIZE_PATH);
170         if (virtualMemSize != null) {
171             LOGGER.debug("the virtualMemSize = {}", virtualMemSize);
172             final HpaFeatureAttribute hpaFeatureAttribute =
173                     generateHpaFeatureAttribute("virtualMemSize", virtualMemSize);
174             final FlavorProperty flavorProperty = new FlavorProperty();
175             flavorProperty.setHpaFeature(BASIC_CAPABILITIES_HPA_FEATURE);
176             flavorProperty.getHpaFeatureAttributes().add(hpaFeatureAttribute);
177             flavorFeature.getFlavorProperties().add(flavorProperty);
178         }
179
180         // the format is int like 2
181         final String numVirtualCpu =
182                 sdcCsarHelper.getCapabilityPropertyLeafValue(capabilityAssignment, NUM_VIRTUAL_CPU_PATH);
183         if (numVirtualCpu != null) {
184             LOGGER.debug("the numVirtualCpu = {}", numVirtualCpu);
185             final HpaFeatureAttribute hpaFeatureAttribute = generateHpaFeatureAttribute("numVirtualCpu", numVirtualCpu);
186             final String cpuArchitecture =
187                     sdcCsarHelper.getCapabilityPropertyLeafValue(capabilityAssignment, CPU_ARCHITECTURE_PATH);
188             final FlavorProperty flavorProperty = new FlavorProperty();
189             flavorProperty.setHpaFeature(BASIC_CAPABILITIES_HPA_FEATURE);
190             if (cpuArchitecture != null) {
191                 flavorProperty.setArchitecture(cpuArchitecture);
192             }
193             flavorProperty.getHpaFeatureAttributes().add(hpaFeatureAttribute);
194             flavorFeature.getFlavorProperties().add(flavorProperty);
195         }
196     }
197
198     /**
199      * GenerateHpaFeatureAttribute based on the value of featureValue. the format: "hpa-attribute-key": "pciVendorId",
200      * "hpa-attribute-value": "1234", "operator": "=", "unit": "xxx".
201      *
202      * @param hpaAttributeKey get from the high layer tosca DM
203      *
204      * @param featureValue get from the high layer tosca DM
205      *
206      */
207     private HpaFeatureAttribute generateHpaFeatureAttribute(final String hpaAttributeKey, final String featureValue) {
208         // based on input featureValue, return back a suitable hpaFeatureAttribute
209         final HpaFeatureAttribute hpaFeatureAttribute = new HpaFeatureAttribute();
210         hpaFeatureAttribute.setHpaAttributeKey(hpaAttributeKey);
211         final String modifiedValue = featureValue.replace(" ", "");
212         final Matcher matcher = PATTERN.matcher(modifiedValue);
213         if (matcher.find()) {
214             final String matcher1 = matcher.group(1);
215             final String matcher2 = matcher.group(2);
216             final String matcher3 = matcher.group(3);
217             LOGGER.debug("operator {} , value = {} , unit = {}", matcher1, matcher2, matcher3);
218             if (matcher.group(1).length() == 0) {
219                 hpaFeatureAttribute.setOperator("=");
220             } else {
221                 hpaFeatureAttribute.setOperator(matcher1);
222             }
223             hpaFeatureAttribute.setHpaAttributeValue(matcher2);
224             hpaFeatureAttribute.setUnit(matcher3);
225         }
226         return hpaFeatureAttribute;
227     }
228
229     /**
230      * GenerateHugePages, supported hpa features, All under the capability of tosca.nodes.nfv.Vdu.Compute. The format is
231      * a map like: {"schemaVersion": "0", "schemaSelector": "", "hardwarePlatform": "generic", "mandatory": "true",
232      * "configurationValue": "2 MB"}
233      *
234      * @param capabilityAssignment represents the capability of node
235      *
236      * @param flavorFeature represents all the features of specified flavor
237      */
238     private void generateHugePages(final CapabilityAssignment capabilityAssignment, final FlavorFeature flavorFeature) {
239         final String memoryPageSize =
240                 sdcCsarHelper.getCapabilityPropertyLeafValue(capabilityAssignment, MEMORY_PAGE_SIZE_PATH);
241         LOGGER.debug("the memoryPageSize = {}", memoryPageSize);
242         if (memoryPageSize != null) {
243             final Map<String, String> retMap =
244                     gson.fromJson(memoryPageSize, new TypeToken<HashMap<String, String>>() {}.getType());
245             LOGGER.debug("the retMap = {}", retMap);
246             final String memoryPageSizeValue = retMap.get(CONFIGURATION_VALUE);
247             final String mandatory = retMap.get("mandatory");
248             if (memoryPageSizeValue == null) {
249                 return;
250             }
251             final HpaFeatureAttribute hpaFeatureAttribute =
252                     generateHpaFeatureAttribute("memoryPageSize", memoryPageSizeValue);
253             final FlavorProperty flavorProperty = new FlavorProperty();
254             flavorProperty.setHpaFeature(HUGE_PAGES_HPA_FEATURE);
255             if (mandatory != null) {
256                 flavorProperty.setMandatory(mandatory);
257             }
258             flavorProperty.getHpaFeatureAttributes().add(hpaFeatureAttribute);
259             flavorFeature.getFlavorProperties().add(flavorProperty);
260         }
261     }
262
263     /**
264      * ExtractInfoVduCp, supported hpa features, under the virtual_network_interface_requirements of
265      * tosca.nodes.nfv.VduCp.
266      *
267      * @param lnodeVduCp the list of VduCp node
268      *
269      * @param content to be change based on lnodeVduCp
270      * @throws PolicyDecodingException if extract CP fails
271      */
272     public void extractInfoVduCp(final List<NodeTemplate> lnodeVduCp, final Content content)
273             throws PolicyDecodingException {
274         // each CP will binds to a VDU so need the vdu flavor map info.
275         final Map<String, FlavorFeature> vduFlavorMap = new HashMap<>();
276         for (final FlavorFeature flavorFeature : content.getFlavorFeatures()) {
277             LOGGER.debug("the id = {}", flavorFeature.getId());
278             vduFlavorMap.put(flavorFeature.getId(), flavorFeature);
279         }
280         parseNodeVduCp(lnodeVduCp, vduFlavorMap);
281     }
282
283     /**
284      * Parse the VduCp list.
285      *
286      * @param lnodeVduCp the lnodeVduCp
287      * @param vduFlavorMap the vduFlavorMap
288      * @throws PolicyDecodingException if any error occurs
289      */
290     private void parseNodeVduCp(final List<NodeTemplate> lnodeVduCp, final Map<String, FlavorFeature> vduFlavorMap)
291             throws PolicyDecodingException {
292         for (final NodeTemplate node : lnodeVduCp) {
293             final String interfaceType =
294                     sdcCsarHelper.getNodeTemplatePropertyLeafValue(node, NETWORK_INTERFACE_TYPE_PATH);
295             LOGGER.debug("the interfaceType = {}", interfaceType);
296             Map<String, Object> retMap = new HashMap<>();
297             if (interfaceType != null) {
298                 retMap = gson.fromJson(interfaceType, new TypeToken<HashMap<String, Object>>() {}.getType());
299                 LOGGER.debug("the retMap = {}", retMap);
300             }
301
302             String networkHpaFeature;
303             if (retMap.containsKey(CONFIGURATION_VALUE)
304                     && NETWORK_HPA_FEATURE_MAP.containsKey(retMap.get(CONFIGURATION_VALUE).toString())) {
305                 final String interfaceTypeValue = retMap.get(CONFIGURATION_VALUE).toString();
306                 networkHpaFeature = NETWORK_HPA_FEATURE_MAP.get(interfaceTypeValue);
307                 LOGGER.debug(" the networkHpaFeature is = {}", networkHpaFeature);
308             } else {
309                 LOGGER.debug(" no networkHpaFeature defined in interfaceType");
310                 continue;
311             }
312
313             final RequirementAssignments requriements =
314                     sdcCsarHelper.getRequirementsOf(node).getRequirementsByName("virtual_binding");
315             for (final RequirementAssignment requriement : requriements.getAll()) {
316                 final String nodeTemplateName = requriement.getNodeTemplateName();
317                 LOGGER.debug("getNodeTemplateName = {}", nodeTemplateName);
318                 if (nodeTemplateName == null) {
319                     continue;
320                 }
321                 if (!vduFlavorMap.containsKey(nodeTemplateName)) {
322                     throw new PolicyDecodingException("vdu Flavor Map should contains the key " + nodeTemplateName);
323                 }
324                 generateNetworkFeature(networkHpaFeature, node, vduFlavorMap.get(nodeTemplateName));
325             }
326         }
327     }
328
329     /**
330      * GenerateNetworkFeature, all pci feature are grouped into FlavorFeature together. The format is a map like:
331      * {"schemaVersion": "0", "schemaSelector": "", "hardwarePlatform": "generic", "mandatory": "true",
332      * "configurationValue": "2 MB"}
333      *
334      * @param networkHpaFeature represents the specified Hpa feature
335      * @param node represents the CP Node
336      * @param flavorFeature represents all the features of specified flavor
337      */
338     private void generateNetworkFeature(final String networkHpaFeature, final NodeTemplate node,
339             final FlavorFeature flavorFeature) {
340         final FlavorProperty flavorProperty = new FlavorProperty();
341         flavorProperty.setHpaFeature(networkHpaFeature);
342         final String[] pciKeys = { "pciVendorId", "pciDeviceId", "pciNumDevices", "physicalNetwork" };
343         for (final String pciKey : pciKeys) {
344             LOGGER.debug("the pciKey = {}", pciKey);
345             final String pciKeyPath = NETWORK_PCI_PATH + "#" + pciKey;
346             final String pciValue = sdcCsarHelper.getNodeTemplatePropertyLeafValue(node, pciKeyPath);
347             if (pciValue != null) {
348                 LOGGER.debug("the pciValue = {}", pciValue);
349                 final Map<String, String> retMap =
350                         gson.fromJson(pciValue, new TypeToken<HashMap<String, String>>() {}.getType());
351                 final String pciConfigValue = retMap.get(CONFIGURATION_VALUE);
352                 if (pciConfigValue == null) {
353                     return;
354                 }
355                 final HpaFeatureAttribute hpaFeatureAttribute = generateHpaFeatureAttribute(pciKey, pciConfigValue);
356                 flavorProperty.getHpaFeatureAttributes().add(hpaFeatureAttribute);
357             }
358         }
359         flavorFeature.getFlavorProperties().add(flavorProperty);
360     }
361 }