0330a756c65b7696ed294fd9c64462e0c8d1fe83
[sdc.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.sdc.be.components.distribution.engine;
22
23 import java.util.ArrayList;
24 import java.util.Collection;
25 import java.util.List;
26 import java.util.Map;
27 import java.util.Optional;
28 import java.util.stream.Collectors;
29
30 import javax.annotation.PostConstruct;
31
32 import org.openecomp.sdc.be.config.ConfigurationManager;
33 import org.openecomp.sdc.be.model.ArtifactDefinition;
34 import org.openecomp.sdc.be.model.ComponentInstance;
35 import org.openecomp.sdc.be.model.ComponentParametersView;
36 import org.openecomp.sdc.be.model.Resource;
37 import org.openecomp.sdc.be.model.Service;
38 import org.openecomp.sdc.be.model.category.CategoryDefinition;
39 import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
40 import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
41 import org.openecomp.sdc.be.model.operations.api.IArtifactOperation;
42 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
43 import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation;
44 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47 import org.springframework.beans.factory.annotation.Autowired;
48 import org.springframework.stereotype.Component;
49
50 import fj.data.Either;
51
52 @Component("serviceDistributionArtifactsBuilder")
53 public class ServiceDistributionArtifactsBuilder {
54
55         private int defaultArtifactInstallTimeout = 60;
56
57         private static Logger logger = LoggerFactory.getLogger(ServiceDistributionArtifactsBuilder.class.getName());
58
59         final static String BASE_ARTIFACT_URL = "/sdc/v1/catalog/services/%s/%s/";
60         final static String RESOURCE_ARTIFACT_URL = BASE_ARTIFACT_URL + "resources/%s/%s/artifacts/%s";
61         final static String SERVICE_ARTIFACT_URL = BASE_ARTIFACT_URL + "artifacts/%s";
62
63         final static String RESOURCE_INSTANCE_ARTIFACT_URL = BASE_ARTIFACT_URL + "resourceInstances/%s/artifacts/%s";
64
65         @javax.annotation.Resource
66         InterfaceLifecycleOperation interfaceLifecycleOperation;
67
68         @javax.annotation.Resource
69         IArtifactOperation artifactOperation;
70         
71         @Autowired
72         ToscaOperationFacade toscaOperationFacade;
73
74         /*
75          * @javax.annotation.Resource private
76          * InformationDeployedArtifactsBusinessLogic
77          * informationDeployedArtifactsBusinessLogic;
78          */
79
80         @PostConstruct
81         private void init() {
82                 defaultArtifactInstallTimeout = ConfigurationManager.getConfigurationManager().getConfiguration()
83                                 .getDefaultHeatArtifactTimeoutMinutes();
84         }
85
86         public InterfaceLifecycleOperation getInterfaceLifecycleOperation() {
87                 return interfaceLifecycleOperation;
88         }
89
90         public void setInterfaceLifecycleOperation(InterfaceLifecycleOperation interfaceLifecycleOperation) {
91                 this.interfaceLifecycleOperation = interfaceLifecycleOperation;
92         }
93
94         public INotificationData buildResourceInstanceForDistribution(Service service, String distributionId) {
95                 INotificationData notificationData = new NotificationDataImpl();
96
97                 notificationData.setResources(convertRIToJsonContanier(service));
98                 notificationData.setServiceName(service.getName());
99                 notificationData.setServiceVersion(service.getVersion());
100                 notificationData.setDistributionID(distributionId);
101                 notificationData.setServiceUUID(service.getUUID());
102                 notificationData.setServiceDescription(service.getDescription());
103                 notificationData.setServiceInvariantUUID(service.getInvariantUUID());
104                 String workloadContext= ConfigurationManager.getConfigurationManager().getConfiguration().getWorkloadContext();
105                 if(workloadContext!=null){
106                         notificationData.setWorkloadContext(workloadContext);
107                 }
108                 logger.debug("Before returning notification data object {}", notificationData);
109
110                 return notificationData;
111
112         }
113
114         public INotificationData buildServiceForDistribution(INotificationData notificationData, Service service) {
115
116                 notificationData.setServiceArtifacts(convertServiceArtifactsToArtifactInfo(service));
117
118                 logger.debug("Before returning notification data object {}", notificationData);
119
120                 return notificationData;
121
122         }
123
124         private List<ArtifactInfoImpl> convertServiceArtifactsToArtifactInfo(Service service) {
125                 
126                 Map<String, ArtifactDefinition> serviceArtifactsMap = service.getDeploymentArtifacts();
127                 List<ArtifactDefinition> extractedServiceArtifacts = serviceArtifactsMap.values().stream()
128                                 //filters all artifacts with existing EsId
129                                 .filter(artifactDef -> artifactDef.checkEsIdExist())
130                                 //collects all filtered artifacts with existing EsId to List
131                                 .collect(Collectors.toList());
132                 
133                 Optional<ArtifactDefinition> toscaTemplateArtifactOptl = exrtactToscaTemplateArtifact(service);
134                 if(toscaTemplateArtifactOptl.isPresent()){
135                         extractedServiceArtifacts.add(toscaTemplateArtifactOptl.get());
136                 }
137                 
138                 Optional<ArtifactDefinition> toscaCsarArtifactOptl = exrtactToscaCsarArtifact(service);
139                 if(toscaCsarArtifactOptl.isPresent()){
140                         extractedServiceArtifacts.add(toscaCsarArtifactOptl.get());
141                 }
142                 
143                 List<ArtifactInfoImpl> artifacts = ArtifactInfoImpl.convertServiceArtifactToArtifactInfoImpl(service, extractedServiceArtifacts);
144                 return artifacts;
145         }
146
147         private Optional<ArtifactDefinition> exrtactToscaTemplateArtifact(Service service) {
148                 return service.getToscaArtifacts().values().stream()
149                                 //filters TOSCA_TEMPLATE artifact
150                                 .filter(e -> e.getArtifactType().equals(ArtifactTypeEnum.TOSCA_TEMPLATE.getType())).findAny();
151         }
152         
153         private Optional<ArtifactDefinition> exrtactToscaCsarArtifact(Service service) {
154                 return service.getToscaArtifacts().values().stream()
155                                 //filters TOSCA_CSAR artifact
156                                 .filter(e -> e.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())).findAny();
157         }
158
159         private List<JsonContainerResourceInstance> convertRIToJsonContanier(Service service) {
160                 List<JsonContainerResourceInstance> ret = new ArrayList<JsonContainerResourceInstance>();
161                 if (service.getComponentInstances() != null) {
162                         for (ComponentInstance resourceInstance : service.getComponentInstances()) {
163                                 String resoucreType = resourceInstance.getOriginType().getValue();
164                                 List<ArtifactDefinition> artifactsDefList = getArtifactsWithPayload(resourceInstance);
165                                 List<ArtifactInfoImpl> artifacts = ArtifactInfoImpl.convertToArtifactInfoImpl(service, resourceInstance,
166                                                 artifactsDefList);
167
168                                 String resourceInvariantUUID = null;
169                                 String resourceCategory = null;
170                                 String resourceSubcategory = null;
171
172                                 ComponentParametersView componentParametersView = new ComponentParametersView();
173                                 componentParametersView.disableAll();
174                                 componentParametersView.setIgnoreCategories(false);
175                                 Either<Resource, StorageOperationStatus> componentResponse = toscaOperationFacade
176                                                 .getToscaElement(resourceInstance.getComponentUid(), componentParametersView);
177
178                                 if (componentResponse.isRight()) {
179                                         logger.debug("Resource {} Invariant UUID & Categories retrieving failed", resourceInstance.getComponentUid());
180                                 } else {
181                                         Resource resource = componentResponse.left().value();
182                                         resourceInvariantUUID = resource.getInvariantUUID();
183
184                                         List<CategoryDefinition> categories = resource.getCategories();
185
186                                         if (categories != null) {
187                                                 CategoryDefinition categoryDefinition = categories.get(0);
188
189                                                 if (categoryDefinition != null) {
190                                                         resourceCategory = categoryDefinition.getName();
191                                                         List<SubCategoryDefinition> subcategories = categoryDefinition.getSubcategories();
192                                                         if (null != subcategories) {
193                                                                 SubCategoryDefinition subCategoryDefinition = subcategories.get(0);
194
195                                                                 if (subCategoryDefinition != null) {
196                                                                         resourceSubcategory = subCategoryDefinition.getName();
197                                                                 }
198                                                         }
199                                                 }
200                                         }
201                                 }
202
203                                 JsonContainerResourceInstance jsonContainer = new JsonContainerResourceInstance(resourceInstance, resoucreType,
204                                                 rebuildArtifactswith120TimeoutInsteadOf60(artifacts)/*TODO used to send artifacts, the function is a fix to the short timeout bug in distribution*/);
205                                 jsonContainer.setResourceInvariantUUID(resourceInvariantUUID);
206                                 jsonContainer.setCategory(resourceCategory);
207                                 jsonContainer.setSubcategory(resourceSubcategory);
208                                 ret.add(jsonContainer);
209                         }
210                 }
211                 return ret;
212         }
213
214         private List<ArtifactInfoImpl> rebuildArtifactswith120TimeoutInsteadOf60(List<ArtifactInfoImpl> artifacts) {
215                 for(ArtifactInfoImpl artifact : artifacts){
216                         if(artifact.getArtifactTimeout().equals(60)){
217                                 artifact.setArtifactTimeout(120);
218                         }
219                 }
220                 return artifacts;
221         }
222
223         private List<ArtifactDefinition> getArtifactsWithPayload(ComponentInstance resourceInstance) {
224                 List<ArtifactDefinition> ret = new ArrayList<ArtifactDefinition>();
225
226                 // List<ArtifactDefinition> informationDeployedArtifacts =
227                 // informationDeployedArtifactsBusinessLogic.getInformationalDeployedArtifactsForResourceInstance(resourceInstance);
228                 List<ArtifactDefinition> deployableArtifacts = new ArrayList<ArtifactDefinition>();
229                 // deployableArtifacts.addAll(informationDeployedArtifacts);
230                 if (resourceInstance.getDeploymentArtifacts() != null) {
231                         deployableArtifacts.addAll(resourceInstance.getDeploymentArtifacts().values());
232                 }
233
234                 for (ArtifactDefinition artifactDef : deployableArtifacts) {
235                         if (artifactDef.checkEsIdExist()) {
236                                 ret.add(artifactDef);
237                         }
238                 }
239
240                 return ret;
241         }
242
243         /**
244          * build the url for resource intance artifact
245          * 
246          * @param service
247          * @param resourceData
248          * @param artifactName
249          * @return
250          */
251         public static String buildResourceInstanceArtifactUrl(Service service, ComponentInstance resourceInstance,
252                         String artifactName) {
253
254                 String url = String.format(RESOURCE_INSTANCE_ARTIFACT_URL, service.getSystemName(), service.getVersion(),
255                                 resourceInstance.getNormalizedName(), artifactName);
256
257                 logger.debug("After building artifact url {}", url);
258
259                 return url;
260         }
261
262         /**
263          * build the url for resource intance artifact
264          * 
265          * @param service
266          * @param resourceData
267          * @param artifactName
268          * @return
269          */
270         public static String buildServiceArtifactUrl(Service service, String artifactName) {
271
272                 String url = String.format(SERVICE_ARTIFACT_URL, service.getSystemName(), service.getVersion(), artifactName);
273
274                 logger.debug("After building artifact url {}", url);
275
276                 return url;
277
278         }
279
280         /**
281          * Retrieve all deployment artifacts of all resources under a given service
282          * 
283          * @param resourceArtifactsResult
284          * @param service
285          * @param deConfiguration
286          * @return
287          */
288         public Either<Boolean, StorageOperationStatus> isServiceContainsDeploymentArtifacts(Service service) {
289
290                 Either<Boolean, StorageOperationStatus> result = Either.left(false);
291                 Map<String, ArtifactDefinition> serviseArtifactsMap = service.getDeploymentArtifacts();
292                 if (serviseArtifactsMap != null && !serviseArtifactsMap.isEmpty()) {
293                         result = Either.left(true);
294                         return result;
295                 }
296
297                 List<ComponentInstance> resourceInstances = service.getComponentInstances();
298
299                 if (resourceInstances != null) {
300                         for (ComponentInstance resourceInstance : resourceInstances) {
301
302                                 Map<String, ArtifactDefinition> deploymentArtifactsMapper = resourceInstance.getDeploymentArtifacts();
303                                 // List<ArtifactDefinition> informationDeployedArtifacts =
304                                 // informationDeployedArtifactsBusinessLogic.getInformationalDeployedArtifactsForResourceInstance(resourceInstance);
305
306                                 boolean isDeployableArtifactFound = isContainsPayload(deploymentArtifactsMapper.values());// ||
307                                                                                                                                                                                                                         // isContainsPayload(informationDeployedArtifacts);
308                                 if (isDeployableArtifactFound) {
309                                         result = Either.left(true);
310                                         break;
311                                 }
312
313                         }
314
315                 }
316
317                 return result;
318         }
319
320         private boolean isContainsPayload(Collection<ArtifactDefinition> collection) {
321                 boolean payLoadFound = collection != null && collection.stream().anyMatch(p -> p.checkEsIdExist());
322                 return payLoadFound;
323         }
324
325 }