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