7ea80263bd18bb3c87c97673c9ee2aa592164a2b
[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.List;
25 import java.util.Map;
26 import java.util.Optional;
27 import java.util.stream.Collectors;
28
29 import org.apache.commons.collections.CollectionUtils;
30 import org.apache.commons.collections.MapUtils;
31 import org.openecomp.sdc.be.config.ConfigurationManager;
32 import org.openecomp.sdc.be.model.ArtifactDefinition;
33 import org.openecomp.sdc.be.model.ComponentInstance;
34 import org.openecomp.sdc.be.model.ComponentParametersView;
35 import org.openecomp.sdc.be.model.Resource;
36 import org.openecomp.sdc.be.model.Service;
37 import org.openecomp.sdc.be.model.category.CategoryDefinition;
38 import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
39 import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
40 import org.openecomp.sdc.be.model.operations.api.IArtifactOperation;
41 import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation;
42 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45 import org.springframework.beans.factory.annotation.Autowired;
46 import org.springframework.stereotype.Component;
47
48 import fj.data.Either;
49
50 @Component("serviceDistributionArtifactsBuilder")
51 public class ServiceDistributionArtifactsBuilder {
52
53     private static final Logger logger = LoggerFactory.getLogger(ServiceDistributionArtifactsBuilder.class);
54
55     static final String BASE_ARTIFACT_URL = "/sdc/v1/catalog/services/%s/%s/";
56     static final String RESOURCE_ARTIFACT_URL = BASE_ARTIFACT_URL + "resources/%s/%s/artifacts/%s";
57     static final String SERVICE_ARTIFACT_URL = BASE_ARTIFACT_URL + "artifacts/%s";
58     static final String RESOURCE_INSTANCE_ARTIFACT_URL = BASE_ARTIFACT_URL + "resourceInstances/%s/artifacts/%s";
59
60     @javax.annotation.Resource
61     InterfaceLifecycleOperation interfaceLifecycleOperation;
62
63     @javax.annotation.Resource
64     IArtifactOperation artifactOperation;
65
66     @Autowired
67     ToscaOperationFacade toscaOperationFacade;
68
69     public InterfaceLifecycleOperation getInterfaceLifecycleOperation() {
70         return interfaceLifecycleOperation;
71     }
72
73     public void setInterfaceLifecycleOperation(InterfaceLifecycleOperation interfaceLifecycleOperation) {
74         this.interfaceLifecycleOperation = interfaceLifecycleOperation;
75     }
76
77     private String resolveWorkloadContext(String workloadContext) {
78         return workloadContext != null ? workloadContext :
79                 ConfigurationManager.getConfigurationManager().getConfiguration().getWorkloadContext();
80     }
81
82     public INotificationData buildResourceInstanceForDistribution(Service service, String distributionId, String workloadContext) {
83         INotificationData notificationData = new NotificationDataImpl();
84
85         notificationData.setResources(convertRIsToJsonContanier(service));
86         notificationData.setServiceName(service.getName());
87         notificationData.setServiceVersion(service.getVersion());
88         notificationData.setDistributionID(distributionId);
89         notificationData.setServiceUUID(service.getUUID());
90         notificationData.setServiceDescription(service.getDescription());
91         notificationData.setServiceInvariantUUID(service.getInvariantUUID());
92         workloadContext = resolveWorkloadContext(workloadContext);
93         if (workloadContext!=null){
94             notificationData.setWorkloadContext(workloadContext);
95         }
96         logger.debug("Before returning notification data object {}", notificationData);
97
98         return notificationData;
99     }
100
101     public INotificationData buildServiceForDistribution(INotificationData notificationData, Service service) {
102
103         notificationData.setServiceArtifacts(convertServiceArtifactsToArtifactInfo(service));
104
105         logger.debug("Before returning notification data object {}", notificationData);
106
107         return notificationData;
108     }
109
110     private List<ArtifactInfoImpl> convertServiceArtifactsToArtifactInfo(Service service) {
111
112         Map<String, ArtifactDefinition> serviceArtifactsMap = service.getDeploymentArtifacts();
113         List<ArtifactDefinition> extractedServiceArtifacts = serviceArtifactsMap.values().stream()
114                 //filters all artifacts with existing EsId
115                 .filter(ArtifactDefinition::checkEsIdExist)
116                 //collects all filtered artifacts with existing EsId to List
117                 .collect(Collectors.toList());
118
119         Optional<ArtifactDefinition> toscaTemplateArtifactOptl = exrtactToscaTemplateArtifact(service);
120         if(toscaTemplateArtifactOptl.isPresent()){
121             extractedServiceArtifacts.add(toscaTemplateArtifactOptl.get());
122         }
123
124         Optional<ArtifactDefinition> toscaCsarArtifactOptl = exrtactToscaCsarArtifact(service);
125         if(toscaCsarArtifactOptl.isPresent()){
126             extractedServiceArtifacts.add(toscaCsarArtifactOptl.get());
127         }
128
129         return ArtifactInfoImpl.convertServiceArtifactToArtifactInfoImpl(service, extractedServiceArtifacts);
130     }
131
132     private Optional<ArtifactDefinition> exrtactToscaTemplateArtifact(Service service) {
133         return service.getToscaArtifacts().values().stream()
134                 //filters TOSCA_TEMPLATE artifact
135                 .filter(e -> e.getArtifactType().equals(ArtifactTypeEnum.TOSCA_TEMPLATE.getType())).findAny();
136     }
137
138     private Optional<ArtifactDefinition> exrtactToscaCsarArtifact(Service service) {
139         return service.getToscaArtifacts().values().stream()
140                 //filters TOSCA_CSAR artifact
141                 .filter(e -> e.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())).findAny();
142     }
143
144     private List<JsonContainerResourceInstance> convertRIsToJsonContanier(Service service) {
145         List<JsonContainerResourceInstance> ret = new ArrayList<>();
146         if (service.getComponentInstances() != null) {
147             for (ComponentInstance instance : service.getComponentInstances()) {
148                 JsonContainerResourceInstance jsonContainer = new JsonContainerResourceInstance(instance, convertToArtifactsInfoImpl(service, instance));
149                 ComponentParametersView filter = new ComponentParametersView();
150                 filter.disableAll();
151                 filter.setIgnoreCategories(false);
152                 toscaOperationFacade.getToscaElement(instance.getComponentUid(), filter)
153                     .left()
154                     .bind(r->{fillJsonContainer(jsonContainer, (Resource) r); return Either.left(r);})
155                     .right()
156                     .forEach(r->logger.debug("Resource {} Invariant UUID & Categories retrieving failed", instance.getComponentUid()));
157                 ret.add(jsonContainer);
158             }
159         }
160         return ret;
161     }
162
163     private void fillJsonContainer(JsonContainerResourceInstance jsonContainer, Resource resource) {
164         jsonContainer.setResourceInvariantUUID(resource.getInvariantUUID());
165         setCategories(jsonContainer, resource.getCategories());
166     }
167
168     private List<ArtifactInfoImpl> convertToArtifactsInfoImpl(Service service, ComponentInstance resourceInstance) {
169         List<ArtifactInfoImpl> artifacts = ArtifactInfoImpl.convertToArtifactInfoImpl(service, resourceInstance, getArtifactsWithPayload(resourceInstance));
170         artifacts.stream().forEach(ArtifactInfoImpl::updateArtifactTimeout);
171         return artifacts;
172     }
173
174     private void setCategories(JsonContainerResourceInstance jsonContainer, List<CategoryDefinition> categories) {
175         if (categories != null) {
176             CategoryDefinition categoryDefinition = categories.get(0);
177
178             if (categoryDefinition != null) {
179                 jsonContainer.setCategory(categoryDefinition.getName());
180                 List<SubCategoryDefinition> subcategories = categoryDefinition.getSubcategories();
181                 if (null != subcategories) {
182                     SubCategoryDefinition subCategoryDefinition = subcategories.get(0);
183
184                     if (subCategoryDefinition != null) {
185                         jsonContainer.setSubcategory(subCategoryDefinition.getName());
186                     }
187                 }
188             }
189         }
190     }
191
192     private List<ArtifactDefinition> getArtifactsWithPayload(ComponentInstance resourceInstance) {
193         List<ArtifactDefinition> ret = new ArrayList<>();
194
195         List<ArtifactDefinition> deployableArtifacts = new ArrayList<>();
196         if (resourceInstance.getDeploymentArtifacts() != null) {
197             deployableArtifacts.addAll(resourceInstance.getDeploymentArtifacts().values());
198         }
199
200         for (ArtifactDefinition artifactDef : deployableArtifacts) {
201             if (artifactDef.checkEsIdExist()) {
202                 ret.add(artifactDef);
203             }
204         }
205
206         return ret;
207     }
208
209     /**
210      * build the URL for resource instance artifact
211      *
212      * @param    service
213      * @param    resourceInstance
214      * @param    artifactName
215      * @return    URL string
216      */
217     public static String buildResourceInstanceArtifactUrl(Service service, ComponentInstance resourceInstance,
218             String artifactName) {
219
220         String url = String.format(RESOURCE_INSTANCE_ARTIFACT_URL, service.getSystemName(), service.getVersion(),
221                 resourceInstance.getNormalizedName(), artifactName);
222
223         logger.debug("After building artifact url {}", url);
224
225         return url;
226     }
227
228     /**
229      * build the URL for resource instance artifact
230      *
231      * @param    service
232      * @param    artifactName
233      * @return    URL string
234      */
235     public static String buildServiceArtifactUrl(Service service, String artifactName) {
236
237         String url = String.format(SERVICE_ARTIFACT_URL, service.getSystemName(), service.getVersion(), artifactName);
238
239         logger.debug("After building artifact url {}", url);
240
241         return url;
242
243     }
244
245     /**
246      * Verifies that the service or at least one of its instance contains deployment artifacts
247      *
248      * @param    the service
249      * @return    boolean
250      */
251     public boolean verifyServiceContainsDeploymentArtifacts(Service service) {
252         if (MapUtils.isNotEmpty(service.getDeploymentArtifacts())) {
253             return true;
254         }
255         boolean contains = false;
256         List<ComponentInstance> resourceInstances = service.getComponentInstances();
257         if (CollectionUtils.isNotEmpty(resourceInstances)) {
258             contains = resourceInstances.stream().anyMatch(i -> isContainsPayload(i.getDeploymentArtifacts()));
259         }
260         return contains;
261     }
262
263     private boolean isContainsPayload(Map<String, ArtifactDefinition> deploymentArtifacts) {
264        return deploymentArtifacts != null && deploymentArtifacts.values().stream().anyMatch(ArtifactDefinition::checkEsIdExist);
265     }
266
267 }