77fd010e85140f13005d030afb79b40c0ac73f87
[sdc.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2019 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.model.jsonjanusgraph.operations;
22
23 import fj.data.Either;
24 import org.openecomp.sdc.be.dao.api.ActionStatus;
25 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
26 import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
27 import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao;
28 import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
29 import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
30 import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
31 import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition;
32 import org.openecomp.sdc.be.datatypes.elements.CompositionDataDefinition;
33 import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
34 import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
35 import org.openecomp.sdc.be.model.LifecycleStateEnum;
36 import org.openecomp.sdc.be.model.jsonjanusgraph.enums.JsonConstantKeysEnum;
37 import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation;
38 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
39 import org.openecomp.sdc.common.log.wrappers.Logger;
40 import org.springframework.beans.factory.annotation.Autowired;
41 import org.springframework.stereotype.Component;
42
43 import java.util.*;
44 import java.util.stream.Collectors;
45
46 import static org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArchiveOperation.Action.ARCHIVE;
47 import static org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArchiveOperation.Action.RESTORE;
48
49 /**
50  * Created by yavivi on 25/03/2018.
51  */
52 @Component
53 public class ArchiveOperation extends BaseOperation {
54
55     private static final Logger log = Logger.getLogger(ArchiveOperation.class.getName());
56
57     @Autowired
58     private IGraphLockOperation graphLockOperation;
59
60     public enum Action {
61         ARCHIVE, RESTORE;
62     }
63
64     public ArchiveOperation(JanusGraphDao janusGraphDao, IGraphLockOperation graphLockOperation){
65         this.janusGraphDao = janusGraphDao;
66         this.graphLockOperation = graphLockOperation;
67     }
68
69     public Either<List<String>, ActionStatus> archiveComponent(String componentId) {
70         final Either<GraphVertex, JanusGraphOperationStatus> vertexResult = this.janusGraphDao.getVertexById(componentId);
71         if (vertexResult.isLeft()){
72             return doAction(ARCHIVE, vertexResult.left().value());
73         } else {
74             return Either.right(onError(ARCHIVE.name(), componentId, vertexResult.right().value()));
75         }
76     }
77
78     public Either<List<String>, ActionStatus> restoreComponent(String componentId) {
79         final Either<GraphVertex, JanusGraphOperationStatus> vertexResult = this.janusGraphDao.getVertexById(componentId);
80         if (vertexResult.isLeft()){
81             return doAction(RESTORE, vertexResult.left().value());
82         } else {
83             return Either.right(onError(RESTORE.name(), componentId, vertexResult.right().value()));
84         }
85     }
86
87     public ActionStatus onVspRestored(String csarId){
88         return onVspStateChanged(RESTORE, csarId);
89     }
90
91     public ActionStatus onVspArchived(String csarId){
92         return onVspStateChanged(ARCHIVE, csarId);
93     }
94
95     private ActionStatus onVspStateChanged(Action action, String csarId) {
96         Map<GraphPropertyEnum, Object> props = new HashMap<>();
97         props.put(GraphPropertyEnum.CSAR_UUID, csarId);
98         Either<List<GraphVertex>, JanusGraphOperationStatus> vfsE = janusGraphDao
99             .getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, props);
100         return vfsE.either(vList -> setVspArchived(action, vList), s -> onError("VSP_"+action.name(), csarId, s));
101     }
102
103     private ActionStatus setVspArchived(Action action, List<GraphVertex> vList) {
104         if (!vList.isEmpty()) {
105             //Find & Lock the highest version component
106             GraphVertex highestVersion = this.getHighestVersionFrom(vList.get(0));
107             StorageOperationStatus lockStatus = this.graphLockOperation.lockComponent(highestVersion.getUniqueId(), highestVersion.getType().getNodeType());
108             if (lockStatus != StorageOperationStatus.OK){
109                 return onError(action.name(), highestVersion.getUniqueId(), JanusGraphOperationStatus.ALREADY_LOCKED);
110             }
111
112             try {
113                 //Set isVspArchived flag
114                 for (GraphVertex v : vList) {
115                     boolean val = action == ARCHIVE ? true : false;
116                     v.setJsonMetadataField(JsonPresentationFields.IS_VSP_ARCHIVED, val);
117                     v.addMetadataProperty(GraphPropertyEnum.IS_VSP_ARCHIVED, val);
118                     janusGraphDao.updateVertex(v);
119                 }
120                 return commitAndCheck("VSP_"+action.name(), vList.toString());
121             } finally {
122                 this.graphLockOperation.unlockComponent(highestVersion.getUniqueId(), highestVersion.getType().getNodeType());
123             }
124
125         }
126         return ActionStatus.OK;
127     }
128
129     public List<String> setArchivedOriginsFlagInComponentInstances(GraphVertex compositionService) {
130         List<String> ciUidsWithArchivedOrigins = new LinkedList();
131         Either<List<GraphVertex>, JanusGraphOperationStatus> instanceOfVerticesE = janusGraphDao
132             .getChildrenVertecies(compositionService, EdgeLabelEnum.INSTANCE_OF, JsonParseFlagEnum.NoParse);
133         Either<List<GraphVertex>, JanusGraphOperationStatus> proxyOfVerticesE = janusGraphDao
134             .getChildrenVertecies(compositionService, EdgeLabelEnum.PROXY_OF, JsonParseFlagEnum.NoParse);
135
136         List<GraphVertex> all = new LinkedList<>();
137         if (instanceOfVerticesE.isLeft()){
138             all.addAll(instanceOfVerticesE.left().value());
139         }
140         if (proxyOfVerticesE.isLeft()){
141             all.addAll(proxyOfVerticesE.left().value());
142         }
143
144         List<GraphVertex> archivedOrigins = all.stream().filter(v -> Boolean.TRUE.equals(v.getMetadataProperty(GraphPropertyEnum.IS_ARCHIVED))).collect(Collectors.toList());
145         List<String> archivedOriginsUids = archivedOrigins.stream().map(GraphVertex::getUniqueId).collect(Collectors.toList());
146
147         Map<String, CompositionDataDefinition> compositionsJson = (Map<String, CompositionDataDefinition>) compositionService.getJson();
148
149         if (compositionsJson != null) {
150             CompositionDataDefinition composition = compositionsJson.get(JsonConstantKeysEnum.COMPOSITION.getValue());
151             if (composition != null) {
152
153                 //Get all component instances from composition
154                 Map<String, ComponentInstanceDataDefinition> componentInstances = composition.getComponentInstances();
155
156                 //Extract component instances uids that has archived origins
157                 ciUidsWithArchivedOrigins = componentInstances.
158                         values().
159                         stream().
160                         //filter CIs whose origins are marked as archived (componentUid is in archivedOriginsUids) the second condition handles the PROXY_OF case)
161                         filter(ci -> archivedOriginsUids.contains(ci.getComponentUid()) || archivedOriginsUids.contains(ci.getToscaPresentationValue(JsonPresentationFields.CI_SOURCE_MODEL_UID))).
162                         map(ComponentInstanceDataDefinition::getUniqueId).collect(Collectors.toList());
163
164                 //set archived origins flag
165                 componentInstances.
166                         values().
167                         stream().
168                         filter(ci -> archivedOriginsUids.contains(ci.getComponentUid()) || archivedOriginsUids.contains(ci.getToscaPresentationValue(JsonPresentationFields.CI_SOURCE_MODEL_UID))).
169                         forEach( ci -> ci.setOriginArchived(true));
170
171             }
172         }
173
174         return ciUidsWithArchivedOrigins;
175     }
176
177     private Either<List<String>, ActionStatus> doAction(Action action, GraphVertex componentVertex){
178
179         GraphVertex highestVersion = this.getHighestVersionFrom(componentVertex);
180
181         if (action.equals(ARCHIVE) && isInCheckoutState(highestVersion)) {
182             return Either.right(ActionStatus.INVALID_SERVICE_STATE);
183         }
184
185         //Lock the Highest Version
186         StorageOperationStatus lockStatus = this.graphLockOperation.lockComponent(highestVersion.getUniqueId(), highestVersion.getType().getNodeType());
187         if (lockStatus != StorageOperationStatus.OK){
188             return Either.right(onError(action.name(), componentVertex.getUniqueId(), JanusGraphOperationStatus.ALREADY_LOCKED));
189         }
190
191         //Refetch latest version with full parsing
192         highestVersion = this.janusGraphDao
193             .getVertexById(highestVersion.getUniqueId(), JsonParseFlagEnum.ParseAll).left().value();
194
195         try {
196             //Get Catalog and Archive Roots
197             GraphVertex catalogRoot = janusGraphDao.getVertexByLabel(VertexTypeEnum.CATALOG_ROOT).left().value();
198             GraphVertex archiveRoot = janusGraphDao.getVertexByLabel(VertexTypeEnum.ARCHIVE_ROOT).left().value();
199
200             if (action == ARCHIVE) {
201                 archiveEdges(catalogRoot, archiveRoot, highestVersion);
202             } else if (action == RESTORE) {
203                 restoreEdges(catalogRoot, archiveRoot, highestVersion);
204             }
205             setPropertiesByAction(highestVersion, action);
206             janusGraphDao.updateVertex(highestVersion);
207
208             List<String> affectedComponentIds = handleParents(highestVersion, catalogRoot, archiveRoot, action);
209             ActionStatus sc = commitAndCheck(action.name(), highestVersion.getUniqueId());
210             return  sc == ActionStatus.OK ? Either.left(affectedComponentIds) : Either.right(sc);
211         } finally {
212             this.graphLockOperation.unlockComponent(highestVersion.getUniqueId(), highestVersion.getType().getNodeType());
213         }
214     }
215
216     private ActionStatus commitAndCheck(String action, String componentId) {
217         JanusGraphOperationStatus status = janusGraphDao.commit();
218         if (!status.equals(JanusGraphOperationStatus.OK)){
219             return onError(action, componentId, status);
220         }
221         return ActionStatus.OK;
222     }
223
224     private boolean isInCheckoutState(GraphVertex v) {
225         if (LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name().equals(v.getMetadataProperty(GraphPropertyEnum.STATE))){
226             return true;
227         }
228         return false;
229     }
230
231     /**
232      * Walks on children until highest version is reached
233      * @param v
234      * @return
235      */
236     private GraphVertex getHighestVersionFrom(GraphVertex v) {
237         Either<GraphVertex, JanusGraphOperationStatus> childVertexE = janusGraphDao
238             .getChildVertex(v, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse);
239         GraphVertex highestVersionVertex = v;
240
241         while (childVertexE.isLeft()) {
242             highestVersionVertex = childVertexE.left().value();
243             childVertexE = janusGraphDao
244                 .getChildVertex(highestVersionVertex, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse);
245         }
246         return highestVersionVertex;
247     }
248
249     private boolean isHighestVersion(GraphVertex v){
250         Boolean highest = (Boolean) v.getMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION);
251         return highest != null && highest;
252     }
253
254     private List<String> handleParents(GraphVertex v, GraphVertex catalogRoot, GraphVertex archiveRoot, Action action) {
255         Either<GraphVertex, JanusGraphOperationStatus> parentVertexE = janusGraphDao
256             .getParentVertex(v, EdgeLabelEnum.VERSION, JsonParseFlagEnum.ParseAll);
257         List<String> affectedCompIds = new ArrayList();
258         affectedCompIds.add(v.getUniqueId());
259
260         while (parentVertexE.isLeft()){
261             GraphVertex cv = parentVertexE.left().value();
262             affectedCompIds.add(cv.getUniqueId());
263             boolean isHighestVersion = isHighestVersion(cv);
264             if (isHighestVersion){
265                 if (action == ARCHIVE) {
266                     archiveEdges(catalogRoot, archiveRoot, cv);
267                 } else {
268                     restoreEdges(catalogRoot, archiveRoot, cv);
269                 }
270             }
271             setPropertiesByAction(cv, action);
272             janusGraphDao.updateVertex(cv);
273             parentVertexE = janusGraphDao
274                 .getParentVertex(cv, EdgeLabelEnum.VERSION, JsonParseFlagEnum.ParseAll);
275         }
276         return affectedCompIds;
277     }
278
279     private void archiveEdges(GraphVertex catalogRoot, GraphVertex archiveRoot, GraphVertex v) {
280         janusGraphDao.deleteAllEdges(catalogRoot, v, EdgeLabelEnum.CATALOG_ELEMENT);
281         janusGraphDao.createEdge(archiveRoot, v, EdgeLabelEnum.ARCHIVE_ELEMENT, null);
282         setPropertiesByAction(v, ARCHIVE);
283     }
284
285     private void restoreEdges(GraphVertex catalogRoot, GraphVertex archiveRoot, GraphVertex v) {
286         janusGraphDao.deleteAllEdges(archiveRoot, v, EdgeLabelEnum.ARCHIVE_ELEMENT);
287         janusGraphDao.createEdge(catalogRoot, v, EdgeLabelEnum.CATALOG_ELEMENT, null);
288         setPropertiesByAction(v, RESTORE);
289     }
290
291     private void setPropertiesByAction(GraphVertex v, Action action) {
292         long now = System.currentTimeMillis();
293
294         boolean isArchived = action == ARCHIVE ? true : false;
295         v.addMetadataProperty(GraphPropertyEnum.IS_ARCHIVED, isArchived);
296         v.addMetadataProperty(GraphPropertyEnum.ARCHIVE_TIME, now);
297         v.setJsonMetadataField(JsonPresentationFields.IS_ARCHIVED, isArchived);
298         v.setJsonMetadataField(JsonPresentationFields.ARCHIVE_TIME, now);
299     }
300
301     private ActionStatus onError(String action, String componentId, JanusGraphOperationStatus s) {
302         ActionStatus ret = ActionStatus.GENERAL_ERROR;
303         if (s == JanusGraphOperationStatus.NOT_FOUND){
304             ret = ActionStatus.RESOURCE_NOT_FOUND;
305         } else if (s == JanusGraphOperationStatus.ALREADY_LOCKED) {
306             ret = ActionStatus.COMPONENT_IN_USE;
307         }
308         String retCodeVal = ret.name();
309         log.error("error occurred when trying to {} {}. Return code is: {}", action, componentId, retCodeVal);
310         return ret;
311     }
312 }