AAI-1523 checkstyle warnings for aai-core query
[aai/aai-common.git] / aai-core / src / test / java / org / onap / aai / query / builder / optimization / AbstractGraphTraversalBuilderOptmizationTest.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017-2018 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 package org.onap.aai.query.builder.optimization;
21
22 import com.google.common.base.CaseFormat;
23 import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
24 import org.apache.tinkerpop.gremlin.structure.Graph;
25 import org.apache.tinkerpop.gremlin.structure.Vertex;
26 import org.junit.After;
27 import org.junit.AfterClass;
28 import org.onap.aai.AAISetup;
29 import org.onap.aai.db.props.AAIProperties;
30 import org.onap.aai.dbmap.AAIGraph;
31 import org.onap.aai.dbmap.DBConnectionType;
32 import org.onap.aai.introspection.Introspector;
33 import org.onap.aai.introspection.Loader;
34 import org.onap.aai.introspection.ModelType;
35
36 import org.onap.aai.query.builder.QueryBuilder;
37 import org.onap.aai.serialization.db.DBSerializer;
38 import org.onap.aai.serialization.db.EdgeSerializer;
39 import org.onap.aai.serialization.engines.JanusGraphDBEngine;
40 import org.onap.aai.serialization.engines.QueryStyle;
41 import org.onap.aai.serialization.engines.TransactionalGraphEngine;
42 import org.springframework.beans.factory.annotation.Autowired;
43
44 import java.lang.reflect.InvocationTargetException;
45 import java.lang.reflect.Method;
46 import java.util.Arrays;
47 import java.util.List;
48 import java.util.Random;
49
50 import static org.junit.Assert.assertEquals;
51
52 public abstract class AbstractGraphTraversalBuilderOptmizationTest extends AAISetup{
53
54     protected static final List<String> RANDOM_VALUES = Arrays.asList("A","B","C","D","E");
55
56     protected static final String crUriPattern = "/cloud-infrastructure/cloud-regions/cloud-region/%s/%s";
57     protected static final String tenantUriPatternSuffix = "/tenants/tenant/%s";
58     protected static final String tenantUriPattern = crUriPattern + tenantUriPatternSuffix;
59     protected static final String vserverUriPatternSuffix = "/vservers/vserver/%s";
60     protected static final String vserverUriPattern = tenantUriPattern + vserverUriPatternSuffix;
61
62     public static final String VSERVER_ID = "vserver-id";
63     public static final String TENANT_ID = "tenant-id";
64     public static final String TENANT_NAME = "tenant-name";
65     public static final String PROV_STATUS = "prov-status";
66     public static final String VSERVER_NAME = "vserver-name";
67     public static final String VSERVER_SELFLINK = "vserver-selflink";
68     public static final String TENANT = "tenant";
69     public static final String VSERVER = "vserver";
70     public static final String CLOUD_REGION = "cloud-region";
71     public static final String CLOUD_REGION_ID = "cloud-region-id";
72     public static final String CLOUD_OWNER = "cloud-owner";
73
74     private static final ModelType introspectorFactoryType = ModelType.MOXY;
75     private static final QueryStyle queryStyle = QueryStyle.TRAVERSAL;
76     private static final DBConnectionType type = DBConnectionType.REALTIME;
77     private static TransactionalGraphEngine dbEngine;
78     private static DBSerializer dbser;
79     protected static Loader loader;
80     protected static Graph graph;
81     protected static GraphTraversalSource g;
82     @Autowired
83     private static EdgeSerializer edgeSer;
84
85     protected static Random rand;
86
87
88     protected void setupData(int tenantNum, int vserverPerTenantNum, String prefix) throws Exception{
89         loader = loaderFactory.createLoaderForVersion(introspectorFactoryType, schemaVersions.getDefaultVersion());
90         graph = AAIGraph.getInstance().getGraph();
91
92         dbEngine = new JanusGraphDBEngine(queryStyle, type, loader);
93         g = dbEngine.startTransaction().traversal();
94         dbser = new DBSerializer(schemaVersions.getDefaultVersion(), dbEngine, introspectorFactoryType, "AAI-TEST-" + prefix);
95
96         rand = new Random();
97
98         Vertex cr;
99         Vertex tenant;
100         Vertex vserver;
101         String crUri;
102         String tenantUri;
103         String vserverUri;
104         System.out.println("Data load started");
105         long startTime = System.currentTimeMillis();
106         for (int crCtr = 0; crCtr < 3; crCtr++) {
107             crUri = String.format(crUriPattern, prefix + "cloud-owner-" + crCtr, prefix + "cloud-region-id-" + crCtr);
108             //System.out.println(crUri);
109             cr = g.addV(AAIProperties.NODE_TYPE, CLOUD_REGION,
110                     CLOUD_REGION_ID, prefix + "cloud-region-id-" + crCtr,
111                     CLOUD_OWNER, prefix + "cloud-owner-" + crCtr,
112                     AAIProperties.AAI_URI, crUri
113             ).next();
114             for (int i = 0; i < tenantNum; i++) {
115                 Introspector intro = loader.introspectorFromName(TENANT);
116                 tenant = dbser.createNewVertex(intro);
117                 edgeSer.addTreeEdge(g, cr, tenant);
118                 intro.setValue(TENANT_ID, prefix + "tenant-id-" + i);
119                 intro.setValue(TENANT_NAME, prefix + "tenant-name-" + i);
120                 dbser.serializeSingleVertex(tenant, intro, "AAI-TEST-" + prefix);
121                 //System.out.println("Tenant " + crCtr + " " + i);
122                 for (int j = 0; j < vserverPerTenantNum; j++) {
123                     intro = loader.introspectorFromName(VSERVER);
124                     vserver = dbser.createNewVertex(intro);
125                     edgeSer.addTreeEdge(g, tenant, vserver);
126                     intro.setValue(VSERVER_ID, prefix + "vserver-id-" + i + "-" + j);
127                     intro.setValue(VSERVER_NAME, prefix + "vserver-name-" + i + "-" + j);
128                     intro.setValue(PROV_STATUS, RANDOM_VALUES.get(rand.nextInt(RANDOM_VALUES.size())));
129                     intro.setValue(VSERVER_SELFLINK, RANDOM_VALUES.get(rand.nextInt(RANDOM_VALUES.size())));
130                     dbser.serializeSingleVertex(vserver, intro, "AAI-TEST-" + prefix);
131                     //System.out.println("Vserver " + crCtr + " " + i + " " + j);
132                 }
133             }
134         }
135         //g.V().forEachRemaining(v -> v.properties().forEachRemaining(p -> System.out.println(p.key() + " : " + p.value())));
136         //g.E().forEachRemaining(e -> System.out.println(e.outVertex().property(AAIProperties.NODE_TYPE).value() + " : " + e.inVertex().property(AAIProperties.NODE_TYPE).value()));
137         long time = System.currentTimeMillis()-startTime;
138         System.out.println("Data load ended\n" + time);
139
140     }
141
142     @After
143     public void deConfigure() throws Exception {
144     }
145
146     @AfterClass
147     public static void teardown() throws Exception {
148         dbEngine.rollback();
149         System.out.println("Done");
150     }
151
152     protected void execute(Method getQueryMethod, int numResultsExpected) throws Exception{
153
154         int iterations = numOfTimesToRun();
155         long noneTimer = 0;
156         long uriTimer = 0;
157         for (int i = 0; i < iterations+1 ; i++) {
158             if (i == 0 ) { // dont use incase initial cold starts
159                 timeQuery(getQuery(getQueryMethod, OptimizeEnum.NONE), numResultsExpected, OptimizeEnum.NONE);
160                 timeQuery(getQuery(getQueryMethod, OptimizeEnum.URI), numResultsExpected, OptimizeEnum.URI);
161             } else {
162                 noneTimer += timeQuery(getQuery(getQueryMethod, OptimizeEnum.NONE), numResultsExpected, OptimizeEnum.NONE);
163                 uriTimer += timeQuery(getQuery(getQueryMethod, OptimizeEnum.URI), numResultsExpected, OptimizeEnum.URI);
164             }
165         }
166
167         noneTimer /= iterations;
168         uriTimer /= iterations;
169         System.out.println(CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, getQueryMethod.getName()).replace("-query", "") + "\t" + (noneTimer)/100000.0 + "\t" + (uriTimer)/100000.0);
170         //System.out.println((noneTimer)/100000.0 + " ms, (Not optimized)");
171         //System.out.println((uriTimer)/100000.0 + " ms, (URI optimized)");
172
173     }
174
175     private QueryBuilder<Vertex> getQuery(Method getQueryMethod, OptimizeEnum optimization) throws InvocationTargetException, IllegalAccessException {
176         return (QueryBuilder<Vertex>) getQueryMethod.invoke(this, optimization);
177     }
178
179
180     private long timeQuery(QueryBuilder<Vertex> query, int numResultsExpected, OptimizeEnum optimized) {
181
182         //System.out.println(optimized.toString());
183
184         long startTime = System.nanoTime();
185         List<Vertex> result = query.toList();
186         long endTime = System.nanoTime();
187
188 //      if (!optimized) {
189 //          result.get(0).properties().forEachRemaining(p -> System.out.println(p.key() + " : " + p.value()));
190 //      }
191         //System.out.println("Result size: " + result.size());
192         if (numResultsExpected != Integer.MIN_VALUE) {
193             assertEquals( optimized.toString() + " optimized" + " query results in " + numResultsExpected + " vserver ", numResultsExpected, result.size());
194         }
195
196         return endTime - startTime;
197
198     }
199
200     protected abstract int getTenantNum();
201
202     protected abstract int getVserverNumPerTenant();
203
204     protected int numOfTimesToRun() {
205         return 500;
206     }
207
208 }
209