Refactor Onboarding Translator code
[sdc.git] / openecomp-be / lib / openecomp-sdc-translator-lib / openecomp-sdc-translator-core / src / main / java / org / openecomp / sdc / translator / services / heattotosca / impl / resourcetranslation / ResourceTranslationNovaServerGroupsImpl.java
1 /*
2  * Copyright © 2016-2018 European Support Limited
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation;
18
19 import java.util.ArrayList;
20 import java.util.Arrays;
21 import java.util.Collections;
22 import java.util.List;
23 import java.util.Map;
24 import java.util.Objects;
25 import java.util.Optional;
26
27 import org.apache.commons.collections4.CollectionUtils;
28 import org.onap.sdc.tosca.datatypes.model.GroupDefinition;
29 import org.onap.sdc.tosca.datatypes.model.PolicyDefinition;
30 import org.openecomp.sdc.heat.datatypes.model.Resource;
31 import org.openecomp.sdc.heat.services.HeatConstants;
32 import org.openecomp.sdc.tosca.datatypes.ToscaGroupType;
33 import org.openecomp.sdc.tosca.datatypes.ToscaPolicyType;
34 import org.openecomp.sdc.tosca.datatypes.ToscaTopologyTemplateElements;
35 import org.openecomp.sdc.tosca.services.DataModelUtil;
36 import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo;
37 import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter;
38
39 public class ResourceTranslationNovaServerGroupsImpl extends ResourceTranslationBase {
40     private static final String AFFINITY = "affinity";
41     private static final String ANTI_AFFINITY = "anti-affinity";
42     private static final List<String> supportedPolicies = Arrays.asList(AFFINITY, ANTI_AFFINITY);
43
44     @Override
45     protected String generateTranslatedId(TranslateTo translateTo) {
46         return isEssentialRequirementsValid(translateTo) ? getTranslatedGroupId(
47                 translateTo.getResourceId()) : null;
48     }
49
50     @Override
51     protected boolean isEssentialRequirementsValid(TranslateTo translateTo) {
52         return validatePolicyType(translateTo);
53     }
54
55     @Override
56     protected Optional<ToscaTopologyTemplateElements> getTranslatedToscaTopologyElement(
57             TranslateTo translateTo) {
58         if (isEssentialRequirementsValid(translateTo)) {
59             return Optional.of(ToscaTopologyTemplateElements.GROUP);
60         } else {
61             return Optional.empty();
62         }
63     }
64
65     private boolean validatePolicyType(TranslateTo translateTo) {
66         Map<String, Object> properties = translateTo.getResource().getProperties();
67         if (Objects.isNull(properties)
68                 || Objects.isNull(properties.get(HeatConstants.SERVER_GROUP_POLICIES_PROPERTY_NAME))) {
69             return true;
70         }
71
72         Object policies = properties.get(HeatConstants.SERVER_GROUP_POLICIES_PROPERTY_NAME);
73         if (!(policies instanceof List)) {
74             return false;
75         }
76
77         for (Object policy : (List) policies) {
78             if (!isValidPolicyType(policy, translateTo.getResourceId(), translateTo.getResource())) {
79                 return false;
80             }
81         }
82         return true;
83     }
84
85     private boolean isValidPolicyType(Object policy, String resourceId, Resource resource) {
86         if (!(policy instanceof String)) {
87             return false;
88         }
89
90         if (!supportedPolicies.contains(policy)) {
91             String unsupportedPolicy = policy.toString();
92             logger.warn("Resource '{}'({})  contains unsupported policy '{}'. This resource is been ignored during "
93                     + "the translation", resourceId, resource.getType(), unsupportedPolicy);
94             return false;
95         }
96
97         return true;
98     }
99
100     @Override
101     protected void translate(TranslateTo translateTo) {
102         String resourceId = translateTo.getResourceId();
103         List<String> toscaPolicyTypes = getToscaPolicies(translateTo.getResource(), resourceId);
104         if (!CollectionUtils.isEmpty(toscaPolicyTypes)) {
105             String translatedGroupId = addGroupToTopology(translateTo, resourceId);
106             addPoliciesToTopology(translateTo, translatedGroupId, toscaPolicyTypes);
107         }
108     }
109
110     private void addPoliciesToTopology(TranslateTo translateTo, String policyTargetEntityId,
111                                        List<String> toscaPolicyTypes) {
112         logger.info("******** Start creating policies for resource '%s' ********",
113                 translateTo.getResourceId());
114         for (int i = 0; i < toscaPolicyTypes.size(); i++) {
115             String policy = toscaPolicyTypes.get(i);
116             logger.info("******** Creating policy '%s' ********", policy);
117             PolicyDefinition policyDefinition = new PolicyDefinition();
118             policyDefinition.setType(policy);
119             policyDefinition.setTargets(Collections.singletonList(policyTargetEntityId));
120             policyDefinition.setProperties(TranslatorHeatToToscaPropertyConverter
121                     .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(),
122                             translateTo.getResourceId(), translateTo.getResource().getProperties(),
123                             policyDefinition.getProperties(), translateTo.getHeatFileName(),
124                             translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(),
125                             policyDefinition, translateTo.getContext()));
126             policyDefinition.getProperties().put(
127                     policy.equals(ToscaPolicyType.PLACEMENT_ANTILOCATE) ? "container_type"
128                             : AFFINITY, "host");
129             String policyId = getTranslatedPolicyId(translateTo, toscaPolicyTypes, i);
130             DataModelUtil
131                     .addPolicyDefinition(translateTo.getServiceTemplate(), policyId, policyDefinition);
132             logger.info("******** Policy '%s' created ********", policy);
133         }
134
135         logger
136                 .info("******** All policies for resource '%s' created successfully ********",
137                         translateTo.getResourceId());
138     }
139
140     private String getTranslatedPolicyId(TranslateTo translateTo, List<String> toscaPolicyTypes,
141                                          int policyIndex) {
142         return translateTo.getResourceId() + (toscaPolicyTypes.size() > 1 ? policyIndex : "")
143                 + "_policy";
144     }
145
146     private String addGroupToTopology(TranslateTo translateTo, String resourceId) {
147         logger.info("******** Start creating group for resource '%s' ********", resourceId);
148         GroupDefinition group = new GroupDefinition();
149         group.setMembers(new ArrayList<>());
150         group.setType(ToscaGroupType.NATIVE_ROOT);
151         String translatedGroupId = getTranslatedGroupId(resourceId);
152         DataModelUtil
153                 .addGroupDefinitionToTopologyTemplate(translateTo.getServiceTemplate(),
154                         translatedGroupId, group);
155         logger.info("******** Creating group '%s' for resource '%s' ********", resourceId, resourceId);
156         return translatedGroupId;
157     }
158
159     private String getTranslatedGroupId(String resourceId) {
160         return resourceId + "_group";
161     }
162
163     private List<String> getToscaPolicies(Resource resource, String resourceId) {
164         Map<String, Object> properties = resource.getProperties();
165         if (Objects.isNull(properties)
166                 || Objects.isNull(properties.get(HeatConstants.SERVER_GROUP_POLICIES_PROPERTY_NAME))) {
167             return Collections.singletonList(ToscaPolicyType.PLACEMENT_ANTILOCATE);
168         }
169
170         List<Object> policies = (List) properties.get(HeatConstants.SERVER_GROUP_POLICIES_PROPERTY_NAME);
171         List<String> retList = new ArrayList<>();
172         policies.forEach(policy -> {
173             if (isValidPolicyType(policy, resourceId, resource)) {
174                 retList.add(getToscaPolicyByHotPolicy(policy));
175             }
176         });
177         return retList;
178     }
179
180     private String getToscaPolicyByHotPolicy(Object policy) {
181         if (Objects.equals(policy, AFFINITY)) {
182             return ToscaPolicyType.PLACEMENT_COLOCATE;
183         } else {
184             return ToscaPolicyType.PLACEMENT_ANTILOCATE;
185         }
186     }
187
188 }