Catalog alignment
[sdc.git] / asdctool / src / main / java / org / openecomp / sdc / asdctool / impl / validator / executers / ArtifactValidatorExecuter.java
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.asdctool.impl.validator.executers;
22
23 import fj.data.Either;
24 import org.openecomp.sdc.asdctool.impl.validator.config.ValidationConfigManager;
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.VertexTypeEnum;
29 import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
30 import org.openecomp.sdc.be.model.ArtifactDefinition;
31 import org.openecomp.sdc.be.model.Component;
32 import org.openecomp.sdc.be.model.ComponentParametersView;
33 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade;
34 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
35 import org.openecomp.sdc.common.log.wrappers.Logger;
36
37 import java.io.BufferedWriter;
38 import java.io.FileOutputStream;
39 import java.io.IOException;
40 import java.io.OutputStreamWriter;
41 import java.io.Writer;
42 import java.util.ArrayList;
43 import java.util.Collection;
44 import java.util.HashMap;
45 import java.util.HashSet;
46 import java.util.List;
47 import java.util.Map;
48 import java.util.Optional;
49 import java.util.Set;
50 import java.util.stream.Collectors;
51
52 public class ArtifactValidatorExecuter{
53
54          protected JanusGraphDao janusGraphDao;
55         protected ToscaOperationFacade toscaOperationFacade;
56
57         public ArtifactValidatorExecuter(JanusGraphDao janusGraphDao,
58                 ToscaOperationFacade toscaOperationFacade) {
59                 this.janusGraphDao = janusGraphDao;
60                 this.toscaOperationFacade = toscaOperationFacade;
61         }
62
63         private static Logger log = Logger.getLogger(ArtifactValidatorExecuter.class.getName());
64          
65          protected String name;
66
67             public void setName(String name) {
68                 this.name = name;
69             }
70
71             public String getName() {
72                 return name;
73             }
74
75          
76         
77            public Map<String, List<Component>> getVerticesToValidate(VertexTypeEnum type, Map<GraphPropertyEnum, Object> hasProps){
78                    Map<String, List<Component>> result = new HashMap<>();
79                 Either<List<GraphVertex>, JanusGraphOperationStatus> resultsEither = janusGraphDao
80               .getByCriteria(type, hasProps);
81                 if (resultsEither.isRight()) {
82                         log.error("getVerticesToValidate failed "+ resultsEither.right().value());
83                     return result;
84                 }
85                 System.out.println("getVerticesToValidate: "+resultsEither.left().value().size()+" vertices to scan");
86                 List<GraphVertex> componentsList = resultsEither.left().value();
87                 componentsList.forEach(vertex -> {
88                         String ivariantUuid = (String)vertex.getMetadataProperty(GraphPropertyEnum.INVARIANT_UUID);
89                         if(!result.containsKey(ivariantUuid)){
90                                 List<Component> compList = new ArrayList<Component>();
91                                 result.put(ivariantUuid, compList);
92                         }
93                         List<Component> compList = result.get(ivariantUuid);
94                         
95                         ComponentParametersView filter = new ComponentParametersView(true);                             
96                                 filter.setIgnoreArtifacts(false);
97                                 
98                                 Either<Component, StorageOperationStatus> toscaElement = toscaOperationFacade.getToscaElement(vertex.getUniqueId(), filter);
99                                 if (toscaElement.isRight()) {
100                                         log.error("getVerticesToValidate: failed to find element"+ vertex.getUniqueId()+" staus is" + toscaElement.right().value());
101                                 }else{
102                                         compList.add(toscaElement.left().value());
103                                 }
104                          
105                 });             
106               
107                         return result;
108             }
109             
110            public boolean validate( Map<String, List<Component>> vertices) {
111                    boolean result = true;
112                    long time = System.currentTimeMillis();
113                    String fileName = ValidationConfigManager.getOutputFilePath() + this.getName() + "_"+ time + ".csv";
114                    try(Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName), "utf-8"))) {
115                         writer.write("name, UUID, invariantUUID, state, version\n");
116                         Collection<List<Component>> collection = vertices.values();
117                         for(List<Component> compList: collection ){
118                                 Set<String> artifactEsId = new HashSet<>();
119                                 for(Component component: compList ){
120                                         Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
121                                         Optional<ArtifactDefinition> op = toscaArtifacts.values().
122                                                         stream().filter(a -> artifactEsId.contains(a.getEsId())).findAny();
123                                         if(op.isPresent()){
124                                                 result = false;
125                                                 writeModuleResultToFile(writer, compList);
126                                                 writer.flush();
127                                                 break;
128                                         }else{
129                                                 artifactEsId.addAll(toscaArtifacts.values().stream().map(ArtifactDefinition::getEsId).collect(Collectors.toList()))     ;
130                                         }
131                                 }
132                                 
133                         }
134                         
135                    } catch (Exception e) {
136                                 log.error("Failed to fetch vf resources ", e);
137                                 return false;
138                         } finally {
139                                 janusGraphDao.commit();
140                         }
141                         return result;
142             }
143            
144            private void writeModuleResultToFile(Writer writer, List<Component> components) {
145                         try {
146                                 // "service name, service id, state, version
147                                 for(Component component: components ){
148                                         StringBuffer sb = new StringBuffer(component.getName());
149                                         sb.append(",").append(component.getUniqueId()).append(",").append(component.getInvariantUUID()).append(",").append(component.getLifecycleState()).append(",").append(component.getVersion());
150                                         
151                                         sb.append("\n");
152                                         writer.write(sb.toString());
153                                 }
154                         } catch (IOException e) {
155                                 log.error("Failed to write module result to file ", e);
156                         }
157                 }
158
159 }