Raise JUnit coverage asdctool
[sdc.git] / asdctool / src / main / java / org / openecomp / sdc / asdctool / migration / tasks / mig1710 / UpgradeMigration1710.java
1 package org.openecomp.sdc.asdctool.migration.tasks.mig1710;
2
3 import java.util.ArrayList;
4 import java.util.EnumMap;
5 import java.util.HashMap;
6 import java.util.List;
7 import java.util.Map;
8 import java.util.Optional;
9 import java.util.function.Predicate;
10 import java.util.stream.Collectors;
11
12 import org.apache.commons.collections.CollectionUtils;
13 import org.apache.commons.collections.MapUtils;
14 import org.apache.commons.lang3.StringUtils;
15 import org.openecomp.sdc.asdctool.migration.core.task.MigrationResult;
16 import org.openecomp.sdc.asdctool.migration.core.task.PostMigration;
17 import org.openecomp.sdc.asdctool.migration.tasks.handlers.XlsOutputHandler;
18 import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
19 import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic;
20 import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
21 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
22 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction.LifecycleChanceActionEnum;
23 import org.openecomp.sdc.be.config.ConfigurationManager;
24 import org.openecomp.sdc.be.dao.api.ActionStatus;
25 import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
26 import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
27 import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
28 import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
29 import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
30 import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
31 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
32 import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
33 import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
34 import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
35 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
36 import org.openecomp.sdc.be.impl.ComponentsUtils;
37 import org.openecomp.sdc.be.model.ComponentInstance;
38 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
39 import org.openecomp.sdc.be.model.ComponentParametersView;
40 import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
41 import org.openecomp.sdc.be.model.LifecycleStateEnum;
42 import org.openecomp.sdc.be.model.Resource;
43 import org.openecomp.sdc.be.model.User;
44 import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
45 import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
46 import org.openecomp.sdc.be.model.operations.api.IUserAdminOperation;
47 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
48 import org.openecomp.sdc.be.model.operations.impl.CsarOperation;
49 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
50 import org.openecomp.sdc.exception.ResponseFormat;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53 import org.springframework.beans.factory.annotation.Autowired;
54
55 import com.google.common.collect.Lists;
56
57 import fj.data.Either;
58
59 //@Component
60 public class UpgradeMigration1710 implements PostMigration {
61         
62         private static final String SERVICE_UUID_RPOPERTY = "providing_service_uuid";
63         
64         private static final String SERVICE_INVARIANT_UUID_RPOPERTY = "providing_service_invariant_uuid";
65         
66     private static final String UNKNOWN = "UNKNOWN";
67
68     private static final String CHECKOUT_MESSAGE = "checkout upon upgrade migration";
69
70     private static final String FAILED_TO_CHANGE_STATE_OF_COMPONENT = "Failed to change state of component with name {}, invariantUUID {}, version {} to {}. ";
71
72     private static final String FAILED_TO_UPGRADE_COMPONENT = "Failed to upgrade {} with name {}, invariantUUID {}, version {}. Operation {}. The reason for failure: {}. ";
73
74     private static final String UPGRADE_COMPONENT_SUCCEEDED = "Upgrade of {} with name {}, invariantUUID {}, version {} finished successfully. ";
75
76     private static final String UPGRADE_VFS_FAILED = "Upgrade VFs upon upgrade migration 1710 process failed. ";
77
78     private static final Logger LOGGER = LoggerFactory.getLogger(UpgradeMigration1710.class);
79
80     @Autowired
81     private TitanDao titanDao;
82
83     @Autowired
84     private ToscaOperationFacade toscaOperationFacade;
85
86     @Autowired
87     private LifecycleBusinessLogic lifecycleBusinessLogic;
88
89     @Autowired
90     private IUserAdminOperation userAdminOperation;
91
92     @Autowired
93     private ResourceBusinessLogic resourceBusinessLogic;
94
95     @Autowired
96     private CsarOperation csarOperation;
97
98     @Autowired
99     private ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
100
101     @Autowired
102     private ComponentsUtils componentsUtils;
103
104     private XlsOutputHandler outputHandler = new XlsOutputHandler("COMPONENT TYPE", "COMPONENT NAME", "COMPONENT UUID", "COMPONENT UNIQUE_ID", "UPGRADE STATUS", "DESCRIPTION");
105
106     private User user = null;
107
108     private final LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction(CHECKOUT_MESSAGE, LifecycleChanceActionEnum.UPGRADE_MIGRATION);
109
110     private final Map<String, GraphVertex> latestGenericTypes = new HashMap<>();
111
112     private final Map<String, String> latestOriginResourceVersions = new HashMap<>();
113     
114     private final List<String> proxyServiceContainers = new ArrayList<>();
115     
116     private final List<String> vfAllottedResources = new ArrayList<>();
117     
118     private final List<String> allottedVfContainers = new ArrayList<>();
119
120     private boolean isVfcUpgradeRequired = false;
121
122     private boolean skipIfUpgradeVfFailed = true;
123
124     /***********************************************/
125
126     @Override
127     public String description() {
128         return "Upgrade migration 1710 - post migration task, which is dedicated to upgrade all latest certified (and not checked out) Node types, VFs and Services. ";
129     }
130
131     private enum UpgradeStatus {
132         UPGRADED,
133         NOT_UPGRADED
134     }
135
136     @Override
137     public MigrationResult migrate() {
138         LOGGER.info("Starting upgrade migration 1710 process. ");
139         MigrationResult migrationResult = new MigrationResult();
140
141         boolean result = true;
142         try {
143             isVfcUpgradeRequired = !ConfigurationManager.getConfigurationManager().getConfiguration().getSkipUpgradeVSPsFlag();
144             skipIfUpgradeVfFailed = ConfigurationManager.getConfigurationManager().getConfiguration().getSkipUpgradeFailedVfs();
145             final String userId = ConfigurationManager.getConfigurationManager().getConfiguration().getAutoHealingOwner();
146
147             Either<User, ActionStatus> userReq = userAdminOperation.getUserData(userId, false);
148             if (userReq.isRight()) {
149                 result = false;
150                 LOGGER.error("Upgrade migration failed. User {} resolve failed: {} ", userId, userReq.right().value());
151             } else {
152                 user = userReq.left().value();
153                 LOGGER.info("User {} will perform upgrade operation", user.getUserId());
154             }
155             if (result) {
156                 result = upgradeNodeTypes();
157             }
158             if (result) {
159                 result = upgradeVFs();
160             }
161             if (result) {
162                 upgradeServices();
163             }
164             if(result){
165                 upgradeProxyServiceContainers();
166             }
167             if(result){
168                 upgradeAllottedVFs();
169             }
170             if(result){
171                 upgradeAllottedVfContainers();
172             }
173         } catch (Exception e) {
174             result = false;
175             LOGGER.error("Error occurred {}. ", e);
176         } finally {
177             if (result) {
178                 LOGGER.info("Upgrade migration 1710 has been successfully finished. ");
179                 titanDao.commit();
180                 migrationResult.setMigrationStatus(MigrationResult.MigrationStatus.COMPLETED);
181             } else {
182                 LOGGER.info("Upgrade migration 1710 was failed. ");
183                 titanDao.rollback();
184                 migrationResult.setMigrationStatus(MigrationResult.MigrationStatus.FAILED);
185             }
186             outputHandler.writeOutput();
187         }
188         return migrationResult;
189     }
190
191     private void upgradeAllottedVfContainers() {
192         LOGGER.info("Starting upgrade proxy {} service containers upon upgrade migration 1710 process. ", allottedVfContainers.size());
193         for(String currUid : allottedVfContainers){
194                 upgradeServiceAndCommitIfNeeded(currUid,  component -> true);
195         }
196         }
197
198         private StorageOperationStatus upgradeServices() {
199         LOGGER.info("Starting upgrade services upon upgrade migration 1710 process. ");
200         Either<List<String>, TitanOperationStatus> getServicesRes = getAllLatestCertifiedComponentUids(VertexTypeEnum.TOPOLOGY_TEMPLATE, ComponentTypeEnum.SERVICE);
201         if (getServicesRes.isRight()) {
202             return StorageOperationStatus.GENERAL_ERROR;
203         }
204         for (String currUid : getServicesRes.left().value()) {
205             upgradeServiceAndCommitIfNeeded(currUid, this::shouldUpgrade);
206         }
207         return StorageOperationStatus.OK;
208     }
209
210     private void upgradeServiceAndCommitIfNeeded(String currUid, Predicate<org.openecomp.sdc.be.model.Component> shouldUpgrade) {
211         boolean result = true;
212         try {
213             result = handleService(currUid, shouldUpgrade);
214         } catch (Exception e) {
215             result = false;
216             LOGGER.error("Failed to upgrade Service with uniqueId {} due to a reason {}. ", currUid, e);
217         }
218         finally {
219             if (result) {
220                 titanDao.commit();
221             }
222             else {
223                 titanDao.rollback();
224             }
225         }
226     }
227     
228     private void upgradeProxyServiceContainers() {
229         LOGGER.info("Starting upgrade proxy service containers upon upgrade migration 1710 process. ");
230         for(String currUid : proxyServiceContainers){
231                 upgradeServiceAndCommitIfNeeded(currUid,  component -> true);
232         }
233         }
234
235     private boolean handleService(String uniqueId, Predicate<org.openecomp.sdc.be.model.Component> shouldUpgrade) {
236         LOGGER.info("Starting upgrade Service with uniqueId {} upon upgrade migration 1710 process. ", uniqueId);
237         Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getServiceRes = toscaOperationFacade.getToscaElement(uniqueId);
238         if(getServiceRes.isRight()){
239             LOGGER.error("Failed to upgrade service with uniqueId {} due to {}. ", uniqueId, getServiceRes.right().value());
240             outputHandler.addRecord(ComponentTypeEnum.SERVICE.name(), UNKNOWN, UNKNOWN, uniqueId, MigrationResult.MigrationStatus.FAILED.name(), getServiceRes.right().value());
241             return false;
242         }
243         String derivedFromGenericType =  getServiceRes.left().value().getDerivedFromGenericType();
244         LOGGER.debug("derivedFromGenericType: {}", derivedFromGenericType );
245         if (derivedFromGenericType == null) {
246             //malformed field value, upgrade required
247             return upgradeService(getServiceRes.left().value());
248         }
249         if(!latestGenericTypes.containsKey(derivedFromGenericType)){
250             Either<List<GraphVertex>, TitanOperationStatus> getDerivedRes = findDerivedResources(derivedFromGenericType);
251             if(getDerivedRes.isRight()){
252                 LOGGER.error(FAILED_TO_UPGRADE_COMPONENT, getServiceRes.left().value().getComponentType().getValue(), getServiceRes.left().value().getName(), getServiceRes.left().value().getInvariantUUID(), getServiceRes.left().value().getVersion(), "findDerivedResources", getDerivedRes.right().value());
253                 outputHandler.addRecord( getServiceRes.left().value().getComponentType().name(),getServiceRes.left().value().getName(), getServiceRes.left().value().getInvariantUUID(), getServiceRes.left().value().getUniqueId(), MigrationResult.MigrationStatus.FAILED.name(), getDerivedRes.right().value());
254                 return false;
255             }
256             latestGenericTypes.put(derivedFromGenericType, getDerivedRes.left().value().get(0));
257         }
258         if(latestVersionExists(latestGenericTypes.get(derivedFromGenericType), getServiceRes.left().value().getDerivedFromGenericVersion())){
259             return upgradeService(getServiceRes.left().value());
260         }
261         if(!collectLatestOriginResourceVersions(getServiceRes.left().value())){
262             return false;
263         }
264         if(shouldUpgrade.test(getServiceRes.left().value())){
265             return upgradeService(getServiceRes.left().value());
266         }
267         outputHandler.addRecord(getServiceRes.left().value().getComponentType().name(), getServiceRes.left().value().getName(), getServiceRes.left().value().getInvariantUUID(), getServiceRes.left().value().getUniqueId(), MigrationResult.MigrationStatus.COMPLETED.name(), UpgradeStatus.NOT_UPGRADED);
268         return true;
269     }
270
271     private boolean collectLatestOriginResourceVersions(org.openecomp.sdc.be.model.Component component) {
272         if (CollectionUtils.isNotEmpty(component.getComponentInstances())) {
273             for (ComponentInstance instance : component.getComponentInstances()) {
274                 if (instance.getOriginType() != OriginTypeEnum.ServiceProxy && !latestOriginResourceVersions.containsKey(instance.getToscaComponentName()) && !addComponent(component, instance)) {
275                     return false;
276                 }
277             }
278         }
279         return true;
280     }
281
282         private boolean addComponent(org.openecomp.sdc.be.model.Component component, ComponentInstance instance) {
283                 VertexTypeEnum vertexType = ModelConverter.getVertexType(instance.getOriginType().name());
284                 Either<Resource, StorageOperationStatus> getOriginRes = toscaOperationFacade.getLatestCertifiedByToscaResourceName(instance.getToscaComponentName(), vertexType, JsonParseFlagEnum.ParseMetadata);
285                 if (getOriginRes.isRight()) {
286                     LOGGER.error(FAILED_TO_UPGRADE_COMPONENT, component.getComponentType().getValue(), component.getName(), component.getInvariantUUID(), component.getVersion(), "toscaOperationFacade.getLatestCertifiedByToscaResourceName", getOriginRes.right().value());
287                     outputHandler.addRecord(component.getComponentType().name(), component.getName(), component.getInvariantUUID(), component.getUniqueId(), MigrationResult.MigrationStatus.FAILED.name(), getOriginRes.right().value());
288                     return false;
289                 }
290                 latestOriginResourceVersions.put(instance.getToscaComponentName(), getOriginRes.left().value().getVersion());
291                 return true;
292         }
293
294     private boolean shouldUpgrade(org.openecomp.sdc.be.model.Component component) {
295         boolean shouldUpgrade = false;
296         if(CollectionUtils.isNotEmpty(component.getComponentInstances())){
297             for(ComponentInstance instance : component.getComponentInstances()){
298                 if(instance.getOriginType() == OriginTypeEnum.ServiceProxy){
299                     LOGGER.info("The service with name {}, invariantUUID {}, version {}, contains Service proxy instance {}, than the service should be upgraded in the end of the upgrading proccess. ", component.getName(), component.getInvariantUUID(), component.getVersion(), instance.getName());
300                     proxyServiceContainers.add(component.getUniqueId());
301                     shouldUpgrade = false;
302                     break;
303                 }
304                 if(isAllottedResource(instance.getActualComponentUid())){
305                         allottedVfContainers.add(component.getUniqueId());
306                 }
307                 if(isGreater(latestOriginResourceVersions.get(instance.getToscaComponentName()), instance.getComponentVersion())){
308                     LOGGER.info("The service with name {}, invariantUUID {}, version {}, contains instance {} from outdated version of origin {} {} , than the service should be upgraded. ", component.getName(), component.getInvariantUUID(), component.getVersion(), instance.getName(), instance.getComponentName(), instance.getComponentVersion());
309                     shouldUpgrade = true;
310                 }
311             }
312         }
313         return shouldUpgrade;
314     }
315
316     private boolean upgradeService(org.openecomp.sdc.be.model.Component service) {
317         String serviceName = service.getName();
318         String serviceUuid = service.getUUID();
319         LOGGER.info("Starting upgrade Service with name {}, invariantUUID {}, version {} upon upgrade migration 1710 process. ", serviceName, service.getInvariantUUID(), service.getVersion());
320         LOGGER.info("Starting to perform check out of service {}. ", serviceName);
321         Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> checkouRes = lifecycleBusinessLogic.changeComponentState(service.getComponentType(), service.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT, changeInfo, true, false);
322         if (checkouRes.isRight()) {
323             LOGGER.error(FAILED_TO_UPGRADE_COMPONENT, service.getComponentType().getValue(), serviceName, service.getInvariantUUID(), service.getVersion(), "lifecycleBusinessLogic.changeComponentState", checkouRes.right().value().getFormattedMessage());
324             outputHandler.addRecord(service.getComponentType().name(), serviceName, serviceUuid, service.getUniqueId(), MigrationResult.MigrationStatus.FAILED.name(), checkouRes.right().value().getFormattedMessage());
325             return false;
326         }
327         Either<org.openecomp.sdc.be.model.Component, ResponseFormat> updateCompositionRes = updateComposition(checkouRes.left().value());
328         if (updateCompositionRes.isRight()) {
329             LOGGER.error(FAILED_TO_UPGRADE_COMPONENT, service.getComponentType().getValue(), serviceName, service.getInvariantUUID(), service.getVersion(), "updateComposition", updateCompositionRes.right().value().getFormattedMessage());
330             outputHandler.addRecord(checkouRes.left().value().getComponentType().name(), checkouRes.left().value().getName(), checkouRes.left().value().getUUID(), checkouRes.left().value().getUniqueId(), MigrationResult.MigrationStatus.FAILED.name(), updateCompositionRes.right().value().getFormattedMessage());
331             return false;
332         }
333         Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> certifyRes = performFullCertification(checkouRes.left().value());
334         if (certifyRes.isRight()) {
335             LOGGER.error(FAILED_TO_UPGRADE_COMPONENT, service.getComponentType().getValue(), serviceName, service.getInvariantUUID(), service.getVersion(), "performFullCertification", certifyRes.right().value().getFormattedMessage());
336             outputHandler.addRecord(checkouRes.left().value().getComponentType().name(), checkouRes.left().value().getName(), checkouRes.left().value().getInvariantUUID(), checkouRes.left().value().getUniqueId(), MigrationResult.MigrationStatus.FAILED.name(), certifyRes.right().value().getFormattedMessage());
337             return false;
338         }
339         outputHandler.addRecord(checkouRes.left().value().getComponentType().name(), checkouRes.left().value().getName(), serviceUuid, checkouRes.left().value().getUniqueId(), MigrationResult.MigrationStatus.COMPLETED.name(), UpgradeStatus.UPGRADED);
340         return true;
341     }
342
343     private Either<org.openecomp.sdc.be.model.Component, ResponseFormat> updateComposition(org.openecomp.sdc.be.model.Component component) {
344         Either<ComponentInstance, ResponseFormat> upgradeInstanceRes;
345         for (ComponentInstance instance : component.getComponentInstances()) {
346             upgradeInstanceRes = upgradeInstance(component, instance);
347             if (upgradeInstanceRes.isRight()) {
348                 LOGGER.error(FAILED_TO_UPGRADE_COMPONENT, component.getComponentType().getValue(), component.getName(), component.getInvariantUUID(), component.getVersion(), "upgradeInstance", upgradeInstanceRes.right().value().getFormattedMessage());
349                 outputHandler.addRecord(component.getComponentType().name(), component.getName(), component.getUUID(), component.getUniqueId(), MigrationResult.MigrationStatus.FAILED.name(), upgradeInstanceRes.right().value().getFormattedMessage());
350                 return Either.right(upgradeInstanceRes.right().value());
351             }
352         }
353         return Either.left(component);
354     }
355
356     private Either<ComponentInstance, ResponseFormat> upgradeInstance(org.openecomp.sdc.be.model.Component component, ComponentInstance instance) {
357         LOGGER.info("Starting upgrade {} instance {} upon upgrade migration 1710 process. ", component.getComponentType().getValue(), instance.getName());
358         ComponentInstance newComponentInstance = new ComponentInstance(instance);
359         if (instance.getOriginType() == OriginTypeEnum.ServiceProxy) {
360             return upgradeServiceProxyInstance(component, instance, newComponentInstance);
361         }
362         return upgradeResourceInstance(component, instance, newComponentInstance);
363     }
364
365     private Either<ComponentInstance, ResponseFormat> upgradeResourceInstance(org.openecomp.sdc.be.model.Component component, ComponentInstance instance, ComponentInstance newComponentInstance) {
366
367         LOGGER.info("Starting upgrade {} instance {} upon upgrade migration 1710 process. ", component.getComponentType().getValue(), instance.getName());
368         Either<ComponentInstance, ResponseFormat> upgradeInstanceRes = null;
369         VertexTypeEnum vertexType = ModelConverter.getVertexType(instance.getOriginType().name());
370         Either<Resource, StorageOperationStatus> getOriginRes = toscaOperationFacade.getLatestCertifiedByToscaResourceName(instance.getToscaComponentName(), vertexType, JsonParseFlagEnum.ParseMetadata);
371         if(getOriginRes.isRight()){
372             LOGGER.info("Upgrade of {} instance {} upon upgrade migration 1710 process failed due to a reason {}. ",
373                     component.getComponentType().getValue(), instance.getName(), getOriginRes.right().value());
374             upgradeInstanceRes = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getOriginRes.right().value(), instance.getOriginType().getComponentType())));
375         }
376         if(upgradeInstanceRes == null){
377                 newComponentInstance.setComponentName(getOriginRes.left().value().getName());
378                 newComponentInstance.setComponentUid(getOriginRes.left().value().getUniqueId());
379                 newComponentInstance.setComponentVersion(getOriginRes.left().value().getVersion());
380                 newComponentInstance.setToscaComponentName(((Resource)getOriginRes.left().value()).getToscaResourceName());
381                 if(isGreater(getOriginRes.left().value().getVersion(), instance.getComponentVersion())){
382                         upgradeInstanceRes = changeAssetVersion(component, instance, newComponentInstance);
383                 }
384                 if((upgradeInstanceRes == null || upgradeInstanceRes.isLeft()) && isAllottedResource(instance.getComponentUid()) && MapUtils.isNotEmpty(component.getComponentInstancesProperties())){
385                         ComponentInstance instanceToUpdate = upgradeInstanceRes == null ? instance : upgradeInstanceRes.left().value();
386                         upgradeInstanceRes = Either.left(updateServiceUuidProperty(component, instanceToUpdate, component.getComponentInstancesProperties().get(instance.getUniqueId())));
387                 }
388         }
389         //upgrade nodes contained by CVFC
390         if(upgradeInstanceRes == null && isVfcUpgradeRequired && newComponentInstance.getOriginType() == OriginTypeEnum.CVFC &&
391                                                     !upgradeVf(getOriginRes.left().value().getUniqueId(), false)) {
392                 upgradeInstanceRes = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
393         }
394         if(upgradeInstanceRes == null){
395                 upgradeInstanceRes = Either.left(instance);
396         }
397         LOGGER.info("Upgrade of {} instance {} upon upgrade migration 1710 process finished successfully. ",
398                             component.getComponentType().getValue(), instance.getName());
399         return upgradeInstanceRes;
400     }
401
402     private ComponentInstance updateServiceUuidProperty(org.openecomp.sdc.be.model.Component component, ComponentInstance instance, List<ComponentInstanceProperty> instanceProperties){
403         if(isAllottedResource(instance.getComponentUid()) && instanceProperties != null){
404                 Optional<ComponentInstanceProperty> propertyUuid =      instanceProperties.stream().filter(p->p.getName().equals(SERVICE_UUID_RPOPERTY)).findFirst();
405                 Optional<ComponentInstanceProperty> propertyInvariantUuid = instanceProperties.stream().filter(p->p.getName().equals(SERVICE_INVARIANT_UUID_RPOPERTY)).findFirst();
406                 if(propertyUuid.isPresent() && propertyInvariantUuid.isPresent()){
407                         String serviceInvariantUUID = propertyInvariantUuid.get().getValue();
408                         Either<List<GraphVertex>, TitanOperationStatus> getLatestOriginServiceRes = getLatestCertifiedService(serviceInvariantUUID);
409                     if (getLatestOriginServiceRes.isRight()) {
410                         return instance;
411                     }
412                     propertyUuid.get().setValue((String) getLatestOriginServiceRes.left().value().get(0).getJsonMetadataField(JsonPresentationFields.UUID));
413                         componentInstanceBusinessLogic.createOrUpdatePropertiesValues(component.getComponentType(), component.getUniqueId(), instance.getUniqueId(), Lists.newArrayList(propertyUuid.get()), user.getUserId())
414                         .right()
415                         .forEach(e -> LOGGER.debug("Failed to update property {} of the instance {} of the component {}. ", SERVICE_UUID_RPOPERTY, instance.getUniqueId(), component.getName()));
416                 }
417         }
418         return instance;
419         }
420     
421     private boolean isAllottedResource(String uniqueId){
422         ComponentParametersView filters = new ComponentParametersView(true);
423         filters.setIgnoreCategories(false);
424         Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getResourceRes = toscaOperationFacade.getToscaElement(uniqueId, filters);
425         if(getResourceRes.isRight()){
426                 return false;
427         }
428         if(getResourceRes.left().value().getCategories() != null && getResourceRes.left().value().getCategories().get(0)!= null){
429                 return "Allotted Resource".equals(getResourceRes.left().value().getCategories().get(0).getName());
430         }
431         return false;
432     }
433     
434     private boolean isAllottedVf(org.openecomp.sdc.be.model.Component component){
435         if(component.getComponentType() != ComponentTypeEnum.RESOURCE){
436                 return false;
437         }
438         if(((Resource)component).getResourceType() != ResourceTypeEnum.VF){
439                 return false;
440         }
441         return isAllottedResource(component.getUniqueId());
442     }
443     
444     private Either<ComponentInstance, ResponseFormat> upgradeServiceProxyInstance(org.openecomp.sdc.be.model.Component component, ComponentInstance instance, ComponentInstance newComponentInstance) {
445         Either<List<GraphVertex>, TitanOperationStatus> getLatestOriginServiceRes = getLatestCertifiedService(instance.getSourceModelInvariant());
446         if (getLatestOriginServiceRes.isRight()) {
447             return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertTitanStatusToStorageStatus(getLatestOriginServiceRes.right().value()), instance.getOriginType().getComponentType())));
448         }
449         newComponentInstance.setComponentVersion((String) getLatestOriginServiceRes.left().value().get(0).getJsonMetadataField(JsonPresentationFields.VERSION));
450         newComponentInstance.setSourceModelUid((String) getLatestOriginServiceRes.left().value().get(0).getJsonMetadataField(JsonPresentationFields.UNIQUE_ID));
451         newComponentInstance.setSourceModelName((String) getLatestOriginServiceRes.left().value().get(0).getJsonMetadataField(JsonPresentationFields.NAME));
452         newComponentInstance.setSourceModelUuid((String) getLatestOriginServiceRes.left().value().get(0).getJsonMetadataField(JsonPresentationFields.UUID));
453         return changeAssetVersion(component, instance, newComponentInstance);
454     }
455
456     private Either<List<GraphVertex>, TitanOperationStatus> getLatestCertifiedService(String invariantUUID) {
457
458         Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
459         propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
460         propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
461         propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
462         propertiesToMatch.put(GraphPropertyEnum.INVARIANT_UUID, invariantUUID);
463         Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
464         propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
465         return titanDao.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseMetadata);
466     }
467
468     private Either<ComponentInstance, ResponseFormat> changeAssetVersion(org.openecomp.sdc.be.model.Component containerComponent, ComponentInstance instance, ComponentInstance newComponentInstance) {
469         return componentInstanceBusinessLogic.changeComponentInstanceVersion(ComponentTypeEnum.SERVICE_PARAM_NAME, containerComponent.getUniqueId(), instance.getUniqueId(), user.getUserId(), newComponentInstance);
470     }
471
472     private boolean upgradeNodeTypes() {
473         LOGGER.info("Starting upgrade node types upon upgrade migration 1710 process. ");
474         String toscaConformanceLevel = ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel();
475         Map<String, List<String>> resourcesForUpgrade = ConfigurationManager.getConfigurationManager().getConfiguration().getResourcesForUpgrade();
476         Map<String, org.openecomp.sdc.be.model.Component> upgradedNodeTypesMap = new HashMap<>();
477         List<String> nodeTypes;
478         if (resourcesForUpgrade.containsKey(toscaConformanceLevel)) {
479             nodeTypes = resourcesForUpgrade.get(toscaConformanceLevel);
480             if (nodeTypes != null && !nodeTypes.isEmpty()) {
481                 Either<List<String>, TitanOperationStatus> getRes = getAllLatestCertifiedComponentUids(VertexTypeEnum.NODE_TYPE, ComponentTypeEnum.RESOURCE);
482                 if (getRes.isRight()) {
483                     return false;
484                 }
485                 List<String> allNodeTypes = getRes.left().value();
486
487                 for (String toscaResourceName : nodeTypes) {
488                     Either<List<GraphVertex>, StorageOperationStatus> status = getLatestByName(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName);
489                     if (status.isRight()) {
490                         LOGGER.error("Failed to find node type {} ", toscaResourceName);
491                         return false;
492                     }
493                     List<GraphVertex> vList = status.left().value();
494                     for (GraphVertex vertex : vList) {
495                         StorageOperationStatus updateRes = upgradeNodeType(vertex, upgradedNodeTypesMap, allNodeTypes, nodeTypes);
496                         if (updateRes != StorageOperationStatus.OK) {
497                             return false;
498                         }
499                     }
500                 }
501             }
502         }
503         return true;
504     }
505
506     private boolean upgradeVFs() {
507         return upgradeVFs(false);
508     }
509     
510     private boolean upgradeAllottedVFs() {
511         LOGGER.info("Starting upgrade {} allotted Vfs with upon upgrade migration 1710 process. ", vfAllottedResources.size());
512         return upgradeVFs(true);
513     }
514     
515     private boolean upgradeVFs(boolean allottedVfsUpgrade) {
516         LOGGER.info("Starting upgrade VFs upon upgrade migration 1710 process. ");
517         Either<List<String>, TitanOperationStatus> getVfsRes = getAllLatestCertifiedComponentUids(VertexTypeEnum.TOPOLOGY_TEMPLATE, ComponentTypeEnum.RESOURCE);
518         if (getVfsRes.isRight()) {
519             LOGGER.info(UPGRADE_VFS_FAILED);
520             return false;
521         }
522         for (String currUid : getVfsRes.left().value()) {
523             boolean result = true;
524             try {
525                 result = upgradeVf(currUid, allottedVfsUpgrade);
526                 if (!result && !skipIfUpgradeVfFailed) {
527                     return false;
528                 }
529             } catch (Exception e) {
530                 LOGGER.error("The exception {} occured upon upgrade VFs. ", e);
531                 result = false;
532                 if (!skipIfUpgradeVfFailed) {
533                    return false;
534                 }
535             }
536             finally {
537                 if (!result) {
538                     LOGGER.error("Failed to upgrade RESOURCE with uniqueId {} ", currUid);
539                     titanDao.rollback();
540                 }
541                 else {
542                     LOGGER.info("RESOURCE upgrade finished successfully: uniqueId {} ", currUid);
543                     titanDao.commit();
544                 }
545             }
546         }
547         LOGGER.info("Upgrade VFs upon upgrade migration 1710 process finished successfully. ");
548         return true;
549     }
550
551     private boolean upgradeVf(String uniqueId, boolean allottedVfsUpgrade) {
552         LOGGER.info("Starting upgrade VF with uniqueId {} upon upgrade migration 1710 process. ", uniqueId);
553         Either<String, StorageOperationStatus> latestVersionRes;
554         Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getRes = toscaOperationFacade.getToscaElement(uniqueId);
555         if (getRes.isRight()) {
556             LOGGER.debug("Failed to fetch VF with uniqueId {} upon upgrade migration 1710 process. ", uniqueId);
557             outputHandler.addRecord(ComponentTypeEnum.RESOURCE.name(), UNKNOWN, UNKNOWN, uniqueId, MigrationResult.MigrationStatus.FAILED.name(), getRes.right().value());
558             return false;
559         }
560         if(!allottedVfsUpgrade && isAllottedVf(getRes.left().value())){
561                 vfAllottedResources.add(uniqueId);
562                 return true;
563         }
564         if (StringUtils.isNotEmpty(getRes.left().value().getCsarUUID())) {
565             LOGGER.info("Going to fetch the latest version of VSP with csarUUID {} upon upgrade migration 1710 process. ", getRes.left().value().getCsarUUID());
566             latestVersionRes = csarOperation.getCsarLatestVersion(getRes.left().value().getCsarUUID(), user);
567             if (latestVersionRes.isRight()) {
568                 LOGGER.debug("Failed to fetch the latest version of VSP with csarUUID {} upon upgrade migration 1710 process. ", getRes.left().value().getCsarUUID());
569                 outputHandler.addRecord(getRes.left().value().getComponentType().name(), getRes.left().value().getName(), getRes.left().value().getUUID(), getRes.left().value().getUniqueId(), MigrationResult.MigrationStatus.FAILED.name(), latestVersionRes.right().value());
570                 return false;
571             }
572             if (isGreater(latestVersionRes.left().value(), getRes.left().value().getCsarVersion())) {
573                 return upgradeVfWithLatestVsp(getRes.left().value(), latestVersionRes);
574             }
575             if (!isVfcUpgradeRequired) {
576                 LOGGER.warn("Warning: No need to upgrade VF with name {}, invariantUUID {}, version {} and VSP version {}. No new version of VSP. ", getRes.left().value().getName(), getRes.left().value().getInvariantUUID(), getRes.left().value().getVersion(), getRes.left().value().getCsarVersion());
577             }
578         }
579         return upgradeComponentWithLatestGeneric(getRes.left().value());
580     }
581
582     private boolean upgradeVfWithLatestVsp(org.openecomp.sdc.be.model.Component vf, Either<String, StorageOperationStatus> latestVersionRes) {
583         LOGGER.info("Starting upgrade vf with name {}, invariantUUID {}, version {} and latest VSP version {} upon upgrade migration 1710 process. ", vf.getName(), vf.getInvariantUUID(), vf.getVersion(), latestVersionRes.left().value());
584         LOGGER.info("Starting to perform check out of vf with name {}, invariantUUID {}, version {}. ", vf.getName(), vf.getInvariantUUID(), vf.getVersion());
585         Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> checkouRes = lifecycleBusinessLogic.changeComponentState(vf.getComponentType(), vf.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT, changeInfo, true, false);
586         if (checkouRes.isRight()) {
587             outputHandler.addRecord(vf.getComponentType().name(), vf.getName(), vf.getUUID(), vf.getUniqueId(), MigrationResult.MigrationStatus.FAILED.name(), checkouRes.right().value().getFormattedMessage());
588             return false;
589         }
590         LOGGER.info("Starting update vf with name {}, invariantUUID {}, version {} and latest VSP {}. ", vf.getName(), vf.getInvariantUUID(), vf.getVersion(), latestVersionRes.left().value());
591         Resource resourceToUpdate = new Resource(((Resource) checkouRes.left().value()).getComponentMetadataDefinition());
592         resourceToUpdate.setDerivedFromGenericType(((Resource) checkouRes.left().value()).getDerivedFromGenericType());
593         resourceToUpdate.setDerivedFromGenericVersion(((Resource) checkouRes.left().value()).getDerivedFromGenericVersion());
594         resourceToUpdate.setCsarVersion(Double.toString(Double.parseDouble(latestVersionRes.left().value())));
595         Either<Resource, ResponseFormat> updateResourceFromCsarRes = resourceBusinessLogic.validateAndUpdateResourceFromCsar(resourceToUpdate, user, null, null, resourceToUpdate.getUniqueId());
596         if (updateResourceFromCsarRes.isRight()) {
597             outputHandler.addRecord(resourceToUpdate.getComponentType().name(), resourceToUpdate.getName(), resourceToUpdate.getUUID(), resourceToUpdate.getUniqueId(), MigrationResult.MigrationStatus.FAILED.name(), updateResourceFromCsarRes.right().value().getFormattedMessage());
598             LOGGER.info("Failed to update vf with name {}, invariantUUID {}, version {} and latest VSP {}. ", vf.getName(), vf.getInvariantUUID(), vf.getVersion(), latestVersionRes.left().value());
599             return false;
600         }
601         Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> certifyRes = performFullCertification(checkouRes.left().value());
602         if (certifyRes.isRight()) {
603             LOGGER.info(FAILED_TO_CHANGE_STATE_OF_COMPONENT, checkouRes.left().value().getName(), checkouRes.left().value().getInvariantUUID(), checkouRes.left().value().getVersion(), LifeCycleTransitionEnum.CERTIFY);
604             outputHandler.addRecord(checkouRes.left().value().getComponentType().name(), checkouRes.left().value().getName(), checkouRes.left().value().getInvariantUUID(), checkouRes.left().value().getUniqueId(), MigrationResult.MigrationStatus.FAILED.name(), certifyRes.right().value().getFormattedMessage());
605             return false;
606         }
607         LOGGER.info("Full certification of vf with name {}, invariantUUID {}, version {} finished . ", vf.getName(), vf.getInvariantUUID(), vf.getVersion(), latestVersionRes.left().value());
608         outputHandler.addRecord(certifyRes.left().value().getComponentType().name(), certifyRes.left().value().getName(), certifyRes.left().value().getUUID(), certifyRes.left().value().getUniqueId(), MigrationResult.MigrationStatus.COMPLETED.name(), UpgradeStatus.UPGRADED);
609         return true;
610     }
611
612     private boolean upgradeComponentWithLatestGeneric(org.openecomp.sdc.be.model.Component component) {
613         String derivedFromGenericType = component.getDerivedFromGenericType();
614         String derivedFromGenericVersion = component.getDerivedFromGenericVersion();
615         org.openecomp.sdc.be.model.Component updatedComponent = component;
616         if (StringUtils.isNotEmpty(derivedFromGenericType) && !latestGenericTypes.containsKey(derivedFromGenericType)) {
617             LOGGER.info("Starting upgrade vf with name {}, invariantUUID {}, version {}, latest derived from generic type {}, latest derived from generic version {}. ", component.getName(), component.getInvariantUUID(), component.getVersion(), derivedFromGenericType, derivedFromGenericVersion);
618             LOGGER.info("Starting to fetch latest generic node type {}. ", derivedFromGenericType);
619             Either<List<GraphVertex>, TitanOperationStatus> getDerivedRes = findDerivedResources(derivedFromGenericType);
620             if (getDerivedRes.isRight()) {
621                 outputHandler.addRecord(component.getComponentType().name(), component.getName(), component.getInvariantUUID(), component.getUniqueId(), MigrationResult.MigrationStatus.FAILED.name(), getDerivedRes.right().value());
622                 LOGGER.info("Failed to upgrade component with name {}, invariantUUID {}, version {} and latest generic. Status is {}. ", component.getName(), component.getInvariantUUID(), component.getVersion(), derivedFromGenericType);
623                 return false;
624             }
625             latestGenericTypes.put(derivedFromGenericType, getDerivedRes.left().value().get(0));
626         }
627         if (StringUtils.isEmpty(derivedFromGenericType) ||
628                 latestVersionExists(latestGenericTypes.get(derivedFromGenericType), derivedFromGenericVersion) ||
629                 isVfcUpgradeRequired) {
630             if (StringUtils.isNotEmpty(derivedFromGenericType))
631                 LOGGER.info("Newer version {} of derived from generic type {} exists. ", latestGenericTypes.get(derivedFromGenericType).getJsonMetadataField(JsonPresentationFields.VERSION), derivedFromGenericType);
632             else
633                 LOGGER.info("The vf resource with name {}, invariantUUID {}, version {},  has an empty derivedFromGenericType field. ", component.getName(), component.getInvariantUUID(), component.getVersion());
634
635             LOGGER.info("Starting to perform check out of vf with name {}, invariantUUID {}, version {}. ", component.getName(), component.getInvariantUUID(), component.getVersion());
636             Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> checkouRes = lifecycleBusinessLogic.changeComponentState(component.getComponentType(), component.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT, changeInfo, true, false);
637             if (checkouRes.isRight()) {
638                 LOGGER.info(FAILED_TO_CHANGE_STATE_OF_COMPONENT, component.getName(), component.getInvariantUUID(), component.getVersion(), LifeCycleTransitionEnum.CHECKOUT);
639                 outputHandler.addRecord(component.getComponentType().name(), component.getName(), component.getInvariantUUID(), component.getUniqueId(), MigrationResult.MigrationStatus.FAILED.name(), checkouRes.right().value().getFormattedMessage());
640                 return false;
641             }
642             //update included VFCs, if it is required as per configuration
643             if (CollectionUtils.isNotEmpty(checkouRes.left().value().getComponentInstances())) {
644                 LOGGER.info("VFC upgrade is required: updating components of vf with name {}, invariantUUID {}, version {}. ", component.getName(), component.getInvariantUUID(), component.getVersion());
645                 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> updateCompositionRes =
646                         updateComposition(checkouRes.left().value());
647                 if (updateCompositionRes.isRight()) {
648                     LOGGER.error(FAILED_TO_UPGRADE_COMPONENT, checkouRes.left().value().getComponentType().name(), checkouRes.left().value().getName(), checkouRes.left().value().getInvariantUUID(), checkouRes.left().value().getVersion(), "updateComposition", updateCompositionRes.right().value().getFormattedMessage());
649                     outputHandler.addRecord(checkouRes.left().value().getComponentType().name(), checkouRes.left().value().getName(), checkouRes.left().value().getUUID(), checkouRes.left().value().getUniqueId(), MigrationResult.MigrationStatus.FAILED.name(), updateCompositionRes.right().value().getFormattedMessage());
650                     return false;
651                 }
652             }
653             Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> certifyRes = performFullCertification(checkouRes.left().value());
654             if (certifyRes.isRight()) {
655                 LOGGER.info(FAILED_TO_CHANGE_STATE_OF_COMPONENT, component.getName(), component.getInvariantUUID(), component.getVersion(), LifeCycleTransitionEnum.CERTIFY);
656                 outputHandler.addRecord(checkouRes.left().value().getComponentType().name(), checkouRes.left().value().getName(), checkouRes.left().value().getInvariantUUID(), checkouRes.left().value().getUniqueId(), MigrationResult.MigrationStatus.FAILED.name(), certifyRes.right().value().getFormattedMessage());
657                 return false;
658             }
659             updatedComponent = certifyRes.left().value();
660         } else {
661             LOGGER.info("The version {} of derived from generic type {} is up to date. No need to upgrade component with name {}, invariantUUID {} and version {}. ", latestGenericTypes.get(derivedFromGenericType), derivedFromGenericType, component.getName(), component.getInvariantUUID(), component.getVersion());
662         }
663         LOGGER.info(UPGRADE_COMPONENT_SUCCEEDED, component.getComponentType().getValue(), component.getName(), component.getInvariantUUID(), component.getVersion());
664         outputHandler.addRecord(updatedComponent.getComponentType().name(), updatedComponent.getName(), updatedComponent.getUUID(), updatedComponent.getUniqueId(), MigrationResult.MigrationStatus.COMPLETED.name(), updatedComponent.equals(component) ? UpgradeStatus.NOT_UPGRADED : UpgradeStatus.UPGRADED);
665         return true;
666     }
667
668     private StorageOperationStatus upgradeNodeType(GraphVertex nodeTypeV, Map<String, org.openecomp.sdc.be.model.Component> upgradedNodeTypesMap, List<String> allCertifiedUids, List<String> nodeTypes) {
669         StorageOperationStatus result = StorageOperationStatus.OK;
670         LOGGER.info("Starting upgrade node type with name {}, invariantUUID {}, version{}. ", nodeTypeV.getMetadataProperty(GraphPropertyEnum.NAME), nodeTypeV.getMetadataProperty(GraphPropertyEnum.INVARIANT_UUID), nodeTypeV.getMetadataProperty(GraphPropertyEnum.VERSION));
671         LOGGER.info("Starting to find derived to for node type with name {}, invariantUUID {}, version{}. ", nodeTypeV.getMetadataProperty(GraphPropertyEnum.NAME), nodeTypeV.getMetadataProperty(GraphPropertyEnum.INVARIANT_UUID), nodeTypeV.getMetadataProperty(GraphPropertyEnum.VERSION));
672         Either<List<GraphVertex>, TitanOperationStatus> parentResourceRes = titanDao.getParentVertecies(nodeTypeV, EdgeLabelEnum.DERIVED_FROM, JsonParseFlagEnum.ParseMetadata);
673         if (parentResourceRes.isRight() && parentResourceRes.right().value() != TitanOperationStatus.NOT_FOUND) {
674             return DaoStatusConverter.convertTitanStatusToStorageStatus(parentResourceRes.right().value());
675
676         }
677         List<GraphVertex> derivedResourcesUid = new ArrayList<>();
678         if (parentResourceRes.isLeft()) {
679             for (GraphVertex chV : parentResourceRes.left().value()) {
680                 Optional<String> op = allCertifiedUids.stream().filter(id -> id.equals((String) chV.getJsonMetadataField(JsonPresentationFields.UNIQUE_ID))).findAny();
681                 if (op.isPresent()) {
682                     derivedResourcesUid.add(chV);
683                 }
684             }
685         }
686         String uniqueId = (String) nodeTypeV.getJsonMetadataField(JsonPresentationFields.UNIQUE_ID);
687         Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getRes = toscaOperationFacade.getToscaElement(uniqueId);
688         if (getRes.isRight()) {
689             LOGGER.info("failed to fetch element with uniqueId {} ", uniqueId);
690             return getRes.right().value();
691         }
692
693         org.openecomp.sdc.be.model.Resource nt = (Resource) getRes.left().value();
694         boolean isNeedToUpgrade = true;
695         if (upgradedNodeTypesMap.containsKey(nt.getToscaResourceName()) || nodeTypes.stream().anyMatch(p -> p.equals(nt.getToscaResourceName()))) {
696             isNeedToUpgrade = false;
697         }
698         if (isNeedToUpgrade) {
699             LOGGER.info("Starting to perform check out of node type with name {}, invariantUUID {}, version {}. ", nt.getName(), nt.getInvariantUUID(), nt.getVersion());
700             Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> checkouRes = lifecycleBusinessLogic.changeComponentState(nt.getComponentType(), nt.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT, changeInfo, true, false);
701             if (checkouRes.isRight()) {
702                 return StorageOperationStatus.GENERAL_ERROR;
703             }
704             org.openecomp.sdc.be.model.Component upgradetComp = checkouRes.left().value();
705             boolean res = performFullCertification(upgradetComp).isLeft();
706             if (!res) {
707                 return StorageOperationStatus.GENERAL_ERROR;
708             }
709             upgradedNodeTypesMap.put(nt.getToscaResourceName(), upgradetComp);
710             titanDao.commit();
711         }
712         for (GraphVertex chV : derivedResourcesUid) {
713             result = upgradeNodeType(chV, upgradedNodeTypesMap, allCertifiedUids, nodeTypes);
714             LOGGER.info("Upgrade node type with name {}, invariantUUID {}, version {} has been finished with the status {}", chV.getMetadataProperty(GraphPropertyEnum.NAME), chV.getMetadataProperty(GraphPropertyEnum.INVARIANT_UUID), chV.getMetadataProperty(GraphPropertyEnum.VERSION), result);
715         }
716         return result;
717     }
718
719     private Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> performFullCertification(org.openecomp.sdc.be.model.Component component) {
720         LOGGER.info("Starting to perform full certification of {} with name {}, invariantUUID {}, version {}. ",
721                 component.getComponentType().getValue(), component.getName(), component.getInvariantUUID(), component.getVersion());
722
723         Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> changeStateEither = lifecycleBusinessLogic.changeComponentState(component.getComponentType(), component.getUniqueId(), user, LifeCycleTransitionEnum.CERTIFICATION_REQUEST, changeInfo, true, false);
724         if (changeStateEither.isRight()) {
725             LOGGER.info(FAILED_TO_CHANGE_STATE_OF_COMPONENT, component.getName(), component.getInvariantUUID(), component.getVersion(), LifeCycleTransitionEnum.CERTIFICATION_REQUEST);
726             return changeStateEither;
727         }
728         changeStateEither = lifecycleBusinessLogic.changeComponentState(component.getComponentType(), changeStateEither.left().value().getUniqueId(), user, LifeCycleTransitionEnum.START_CERTIFICATION, changeInfo, true, false);
729         if (changeStateEither.isRight()) {
730             LOGGER.info(FAILED_TO_CHANGE_STATE_OF_COMPONENT, component.getName(), component.getInvariantUUID(), component.getVersion(), LifeCycleTransitionEnum.START_CERTIFICATION);
731             return changeStateEither;
732         }
733         changeStateEither = lifecycleBusinessLogic.changeComponentState(component.getComponentType(), changeStateEither.left().value().getUniqueId(), user, LifeCycleTransitionEnum.CERTIFY, changeInfo, true, false);
734         if (changeStateEither.isRight()) {
735             LOGGER.info(FAILED_TO_CHANGE_STATE_OF_COMPONENT, component.getName(), component.getInvariantUUID(), component.getVersion(), LifeCycleTransitionEnum.CERTIFY);
736         } else {
737             LOGGER.info("Full certification of {} with name {}, invariantUUID {}, version {} finished successfully",
738                     changeStateEither.left().value().getComponentType().getValue(), changeStateEither.left().value().getName(),
739                     changeStateEither.left().value().getInvariantUUID(), changeStateEither.left().value().getVersion());
740         }
741         return changeStateEither;
742     }
743
744     private Either<List<GraphVertex>, TitanOperationStatus> findDerivedResources(String parentResource) {
745         Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
746         propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
747
748         propertiesToMatch.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, parentResource);
749         propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
750
751         return titanDao.getByCriteria(VertexTypeEnum.NODE_TYPE, propertiesToMatch, JsonParseFlagEnum.ParseMetadata);
752     }
753
754     private boolean latestVersionExists(GraphVertex latestDerivedFrom, String currentVersion) {
755         return isGreater((String) latestDerivedFrom.getJsonMetadataField(JsonPresentationFields.VERSION), currentVersion);
756     }
757
758     private boolean isGreater(String latestVersion, String currentVersion) {
759         if (latestVersion != null && currentVersion == null)
760             return true;
761         if (latestVersion == null)
762             return false;
763         return Double.parseDouble(latestVersion) > Double.parseDouble(currentVersion);
764     }
765
766     private Either<List<String>, TitanOperationStatus> getAllLatestCertifiedComponentUids(VertexTypeEnum vertexType, ComponentTypeEnum componentType) {
767         LOGGER.info("Starting to fetch all latest certified not checked out components with type {} upon upgrade migration 1710 process", componentType);
768         Either<List<String>, TitanOperationStatus> result = null;
769         Map<String, String> latestCertifiedMap = new HashMap<>();
770         Map<String, String> latestNotCertifiedMap = new HashMap<>();
771
772         Either<List<GraphVertex>, TitanOperationStatus> getComponentsRes = getAllLatestCertifiedComponents(vertexType, componentType);
773         if (getComponentsRes.isRight() && getComponentsRes.right().value() != TitanOperationStatus.NOT_FOUND) {
774             LOGGER.error("Failed to fetch all latest certified not checked out components with type {}. Status is {}. ", componentType, getComponentsRes.right().value());
775             result = Either.right(getComponentsRes.right().value());
776         }
777         if (getComponentsRes.isRight()) {
778             result = Either.left(new ArrayList<>());
779         }
780         if (result == null) {
781             for (GraphVertex component : getComponentsRes.left().value()) {
782                 String invariantUUID = (String) component.getJsonMetadataField(JsonPresentationFields.INVARIANT_UUID);
783                 if (((String) component.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals(LifecycleStateEnum.CERTIFIED.name())) {
784                     latestCertifiedMap.put(invariantUUID, (String) component.getJsonMetadataField(JsonPresentationFields.UNIQUE_ID));
785                 } else {
786                     latestNotCertifiedMap.put(invariantUUID, (String) component.getJsonMetadataField(JsonPresentationFields.UNIQUE_ID));
787                 }
788             }
789             result = Either.left(latestCertifiedMap.entrySet().stream().filter(e -> !latestNotCertifiedMap.containsKey(e.getKey())).map(Map.Entry::getValue).collect(Collectors.toList()));
790         }
791         return result;
792     }
793
794     private Either<List<GraphVertex>, TitanOperationStatus> getAllLatestCertifiedComponents(VertexTypeEnum vertexType, ComponentTypeEnum componentType) {
795
796         Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
797         propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
798         propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
799
800         Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
801         propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
802         if (vertexType == VertexTypeEnum.TOPOLOGY_TEMPLATE && componentType == ComponentTypeEnum.RESOURCE)
803             propertiesNotToMatch.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.CVFC.name());
804         return titanDao.getByCriteria(vertexType, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseMetadata);
805     }
806
807     private Either<List<GraphVertex>, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName) {
808
809         Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
810         Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
811
812         propertiesToMatch.put(property, nodeName);
813         propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
814
815         Either<List<GraphVertex>, TitanOperationStatus> highestResources = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseMetadata);
816         if (highestResources.isRight()) {
817             TitanOperationStatus status = highestResources.right().value();
818             LOGGER.debug("Failed to fetch resource with name {}. Status is {} ", nodeName, status);
819             return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
820         }
821         List<GraphVertex> resources = highestResources.left().value();
822         List<GraphVertex> result = new ArrayList<>();
823         for (GraphVertex component : resources) {
824             if (((String) component.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals(LifecycleStateEnum.CERTIFIED.name())) {
825                 result.add(component);
826             }
827         }
828         return Either.left(result);
829     }
830
831 }