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