Catalog alignment
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / components / impl / ArchiveBusinessLogic.java
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  * Modifications copyright (c) 2019 Nokia
20  * ================================================================================
21  */
22 package org.openecomp.sdc.be.components.impl;
23
24 import com.google.common.annotations.VisibleForTesting;
25 import fj.data.Either;
26 import org.openecomp.sdc.be.catalog.enums.ChangeTypeEnum;
27 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
28 import org.openecomp.sdc.be.components.validation.AccessValidations;
29 import org.openecomp.sdc.be.dao.api.ActionStatus;
30 import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao;
31 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
32 import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
33 import org.openecomp.sdc.be.facade.operations.CatalogOperation;
34 import org.openecomp.sdc.be.impl.ComponentsUtils;
35 import org.openecomp.sdc.be.model.Component;
36 import org.openecomp.sdc.be.model.ComponentParametersView;
37 import org.openecomp.sdc.be.model.User;
38 import org.openecomp.sdc.be.model.catalog.CatalogComponent;
39 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArchiveOperation;
40 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade;
41 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
42 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
43 import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode;
44 import org.openecomp.sdc.common.log.wrappers.Logger;
45 import org.openecomp.sdc.exception.ResponseFormat;
46
47 import java.util.HashMap;
48 import java.util.HashSet;
49 import java.util.LinkedList;
50 import java.util.List;
51 import java.util.Map;
52 import java.util.stream.Collectors;
53
54 import static org.openecomp.sdc.common.datastructure.FunctionalInterfaces.wrapWithTryCatch;
55
56
57 @org.springframework.stereotype.Component
58 public class ArchiveBusinessLogic {
59
60     private static final Logger log = Logger.getLogger(ArchiveBusinessLogic.class.getName());
61
62     private final JanusGraphDao janusGraphDao;
63     private final AccessValidations accessValidations;
64     private final ArchiveOperation archiveOperation;
65     private final ToscaOperationFacade toscaOperationFacade;
66     private final ComponentsUtils componentUtils;
67         private final CatalogOperation catalogOperations;
68
69     public ArchiveBusinessLogic(JanusGraphDao janusGraphDao, AccessValidations accessValidations, ArchiveOperation archiveOperation, ToscaOperationFacade tof, ComponentsUtils componentsUtils,
70         CatalogOperation catalogOperations) {
71         this.janusGraphDao = janusGraphDao;
72         this.accessValidations = accessValidations;
73         this.archiveOperation = archiveOperation;
74         this.toscaOperationFacade = tof;
75         this.componentUtils = componentsUtils;
76                 this.catalogOperations = catalogOperations;
77     }
78
79     public void archiveComponent(String containerComponentType, String userId, String componentId) {
80         User user = accessValidations.userIsAdminOrDesigner(userId, containerComponentType + "_ARCHIVE");
81         Either<List<String>, ActionStatus> result = this.archiveOperation.archiveComponent(componentId);
82
83         if (result.isRight()){
84             throw new ByActionStatusComponentException(result.right().value(), componentId);
85         }
86         this.auditAction(ArchiveOperation.Action.ARCHIVE, result.left().value(), user, containerComponentType);
87                 // Send Archive Notification To Facade
88                 wrapWithTryCatch(() -> sendNotificationToFacade(componentId, ChangeTypeEnum.ARCHIVE));
89     }
90
91     public void restoreComponent(String containerComponentType, String userId, String componentId) {
92         User user = accessValidations.userIsAdminOrDesigner(userId, containerComponentType + "_RESTORE");
93         Either<List<String>, ActionStatus> result = this.archiveOperation.restoreComponent(componentId);
94         if (result.isRight()){
95             throw new ByActionStatusComponentException(result.right().value(), componentId);
96         }
97         this.auditAction(ArchiveOperation.Action.RESTORE, result.left().value(), user, containerComponentType);
98                 // Send Archive Notification To Facade
99                 wrapWithTryCatch(() -> sendNotificationToFacade(componentId, ChangeTypeEnum.RESTORE));
100     }
101
102     public List<String> onVspArchive(String userId, List<String> csarUuids){
103         return this.onVspArchiveOrRestore(userId, csarUuids, ArchiveOperation.Action.ARCHIVE);
104     }
105
106     public List<String> onVspRestore(String userId, List<String> csarUuids){
107         return this.onVspArchiveOrRestore(userId, csarUuids, ArchiveOperation.Action.RESTORE);
108     }
109
110     private List<String> onVspArchiveOrRestore(String userId, List<String> csarUuids, ArchiveOperation.Action action) {
111
112         accessValidations.userIsAdminOrDesigner(userId, action.name() + "_VSP");
113
114         ActionStatus actionStatus;
115         List<String> failedCsarIDs = new LinkedList<>();
116
117         for (String csarUuid : csarUuids) {
118             try {
119
120                 if (action == ArchiveOperation.Action.ARCHIVE) {
121                     actionStatus = this.archiveOperation.onVspArchived(csarUuid);
122                 } else {
123                     actionStatus = this.archiveOperation.onVspRestored(csarUuid);
124                 }
125
126                 //If not found VFs with this CSAR ID we still want a success (nothing is actually done)
127                 if (actionStatus == ActionStatus.RESOURCE_NOT_FOUND) {
128                     actionStatus = ActionStatus.OK;
129                 }
130
131                 if (actionStatus != ActionStatus.OK) {
132                     failedCsarIDs.add(csarUuid);
133                 }
134
135             } catch (Exception e) {
136                 log.error("Failed to handle notification: {} on VSP for csarUuid: {}", action.name(), csarUuid);
137                 log.error("Exception Thrown:", e);
138                 failedCsarIDs.add(csarUuid);
139             }
140         }
141
142         return failedCsarIDs;
143     }
144
145     public Map<String, List<CatalogComponent>> getArchiveComponents(String userId, List<OriginTypeEnum> excludeTypes) {
146         try {
147
148             Either<List<CatalogComponent>, StorageOperationStatus> components = toscaOperationFacade.getCatalogOrArchiveComponents(false, excludeTypes);
149             if (components.isLeft()) {
150                 List<CatalogComponent> comps = components.left().value();
151                 return comps.stream().collect(Collectors.groupingBy(cmpt -> ComponentTypeEnum.findParamByType(cmpt.getComponentType())));
152             } else {
153                 log.info("No components found");
154                 return new HashMap();
155             }
156         } catch (Exception e){
157             log.error("Error fetching archived elements", e);
158             throw e;
159         }
160         finally {
161             janusGraphDao.commit();
162         }
163     }
164
165
166     @VisibleForTesting
167     void auditAction(ArchiveOperation.Action action, List<String> affectedCompIds, User user, String containerComponentType) {
168         String comment = String.format("All versions of this component were %s", action == ArchiveOperation.Action.ARCHIVE ? "archived" : "restored");
169         HashSet<String> auditDoneUUIDs = new HashSet<>();
170         for (String componentId : affectedCompIds){
171             Either<Component, StorageOperationStatus> result = toscaOperationFacade.getToscaElement(componentId, new ComponentParametersView());
172             if (result.isRight()) {
173                 log.error(EcompLoggerErrorCode.DATA_ERROR, null, "GetToscaElement",
174                         result.right().value().name() + "for component with id {}", componentId);
175                 continue;
176             }
177             if (auditDoneUUIDs.add(result.left().value().getUUID())) {
178                 //a component with this UUID is not added to audit DB/log for current archive/restore operation yet - add to audit DB now
179                 AuditingActionEnum auditAction = action == ArchiveOperation.Action.ARCHIVE ? AuditingActionEnum.ARCHIVE_COMPONENT : AuditingActionEnum.RESTORE_COMPONENT; //The audit Action
180                 result.left().foreachDoEffect(
181                     c -> {
182                         // The archive/restore records have been retrieved from Cassandra using the separate queries.
183                         // Setting current version as null allows to avoid appearing same records in ActivityLog twice:
184                         // - first time as per current version query
185                         //- second type as per archive/restore query
186                         c.setVersion(null);
187                         componentUtils.auditComponentAdmin(componentUtils.getResponseFormat(ActionStatus.OK), user, c, auditAction, ComponentTypeEnum.findByParamName(containerComponentType), comment);
188                     });
189             }
190         }
191     }
192         protected Either<Component, ResponseFormat> sendNotificationToFacade(String componentId,
193                         ChangeTypeEnum changeStatus) {
194                 log.debug("build {} notification for facade start", changeStatus.name());
195                 Either<Component, StorageOperationStatus> toscaElement = toscaOperationFacade.getToscaElement(componentId);
196                 Component component = toscaElement.left()
197                                 .value();
198                 ActionStatus status = catalogOperations.updateCatalog(changeStatus, component);
199                 if (status != ActionStatus.OK) {
200                         return Either.right(componentUtils.getResponseFormat(status));
201                 }
202                 return Either.left(component);
203         }
204 }