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