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