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