/
ViewManager.java
293 lines (252 loc) · 9.02 KB
/
ViewManager.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
package com.orientechnologies.orient.core.db.viewmanager;
import com.orientechnologies.orient.core.db.ODatabase;
import com.orientechnologies.orient.core.db.OScenarioThreadLocal;
import com.orientechnologies.orient.core.db.OrientDBInternal;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentEmbedded;
import com.orientechnologies.orient.core.metadata.schema.OImmutableClass;
import com.orientechnologies.orient.core.metadata.schema.OSchema;
import com.orientechnologies.orient.core.metadata.schema.OView;
import com.orientechnologies.orient.core.record.OElement;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.sql.executor.OResult;
import com.orientechnologies.orient.core.sql.executor.OResultSet;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
public class ViewManager {
private final OrientDBInternal orientDB;
private final String dbName;
ViewThread thread;
/**
* To retain clusters that are being used in queries until the queries are closed.
* <p>
* view -> cluster -> number of visitors
*/
ConcurrentMap<Integer, AtomicInteger> viewCluserVisitors = new ConcurrentHashMap<>();
ConcurrentMap<Integer, String> oldClustersPerViews = new ConcurrentHashMap<>();
List<Integer> clustersToDrop = Collections.synchronizedList(new ArrayList<>());
Map<String, Long> lastUpdateTimestampForView = new HashMap<>();
Map<String, Long> lastChangePerClass = new ConcurrentHashMap<>();
String lastUpdatedView = null;
public ViewManager(OrientDBInternal orientDb, String dbName) {
this.orientDB = orientDb;
this.dbName = dbName;
init();
}
protected void init() {
}
public void start() {
thread = new ViewThread(this, () -> orientDB.openNoAuthorization(dbName));
thread.start();
}
public void close() {
try {
thread.finish();
} catch (Exception e) {
e.printStackTrace();
}
}
public synchronized void cleanUnusedViewClusters(ODatabaseDocument db) {
List<Integer> toRemove = new ArrayList<>();
for (Integer cluster : clustersToDrop) {
AtomicInteger visitors = viewCluserVisitors.get(cluster);
if (visitors == null || visitors.get() <= 0) {
toRemove.add(cluster);
}
}
for (Integer cluster : toRemove) {
viewCluserVisitors.remove(cluster);
clustersToDrop.remove(cluster);
oldClustersPerViews.remove(cluster);
db.dropCluster(cluster, false);
}
}
public synchronized OView getNextViewToUpdate(ODatabase db) {
OSchema schema = db.getMetadata().getSchema();
List<String> names = schema.getViews().stream().map(x -> x.getName()).sorted().collect(Collectors.toList());
if (names.isEmpty()) {
return null;
}
for (String name : names) {
if (!buildOnThisNode(db, name)) {
continue;
}
if (!isUpdateExpiredFor(name, db)) {
continue;
}
if (!needsUpdateBasedOnWatchRules(name, db)) {
continue;
}
if (lastUpdatedView == null || name.compareTo(lastUpdatedView) > 0) {
lastUpdatedView = name;
return schema.getView(name);
}
}
lastUpdatedView = null;
return null;
}
protected boolean buildOnThisNode(ODatabase db, String name) {
return true;
}
/**
* Checks if the view could need an update based on watch rules
*
* @param name view name
* @param db db instance
*
* @return true if there are no watch rules for this view; true if there are watch rules and some of them happened since last
* update; true if the view was never updated; false otherwise.
*/
private boolean needsUpdateBasedOnWatchRules(String name, ODatabase db) {
OView view = db.getMetadata().getSchema().getView(name);
if (view == null) {
return false;
}
Long lastViewUpdate = lastUpdateTimestampForView.get(name);
if (lastViewUpdate == null) {
return true;
}
List<String> watchRules = view.getWatchClasses();
if (watchRules == null || watchRules.size() == 0) {
return true;
}
for (String watchRule : watchRules) {
Long classChangeTimestamp = lastChangePerClass.get(watchRule.toLowerCase(Locale.ENGLISH));
if (classChangeTimestamp == null) {
continue;
}
if (classChangeTimestamp >= lastViewUpdate) {
return true;
}
}
return false;
}
private boolean isUpdateExpiredFor(String viewName, ODatabase db) {
Long lastUpdate = lastUpdateTimestampForView.get(viewName);
if (lastUpdate == null) {
return true;
}
OView view = db.getMetadata().getSchema().getView(viewName);
int updateInterval = view.getUpdateIntervalSeconds();
return lastUpdate + (updateInterval * 1000) < System.currentTimeMillis();
}
public synchronized void updateView(OView view, ODatabaseDocument db) {
lastUpdateTimestampForView.put(view.getName(), System.currentTimeMillis());
int cluster = db.addCluster(getNextClusterNameFor(view, db));
String viewName = view.getName();
String query = view.getQuery();
String originRidField = view.getOriginRidField();
String clusterName = db.getClusterNameById(cluster);
OScenarioThreadLocal.executeAsDistributed(new Callable<Object>() {
@Override
public Object call() {
OResultSet rs = db.query(query);
while (rs.hasNext()) {
OResult item = rs.next();
OElement newRow = copyElement(item, db);
if (originRidField != null) {
newRow.setProperty(originRidField, item.getIdentity().orElse(item.getProperty("@rid")));
newRow.setProperty("@view", viewName);
}
db.save(newRow, clusterName);
}
return null;
}
});
view = db.getMetadata().getSchema().getView(view.getName());
if (view == null) {
//the view was dropped in the meantime
db.dropCluster(clusterName, false);
return;
}
lockView(view);
view.addClusterId(cluster);
for (int i : view.getClusterIds()) {
if (i != cluster) {
clustersToDrop.add(i);
viewCluserVisitors.put(i, new AtomicInteger(0));
oldClustersPerViews.put(i, view.getName());
view.removeClusterId(i);
}
}
unlockView(view);
cleanUnusedViewClusters(db);
}
private synchronized void unlockView(OView view) {
//TODO
}
private void lockView(OView view) {
//TODO
}
private String getNextClusterNameFor(OView view, ODatabase db) {
int i = 0;
String viewName = view.getName();
while (true) {
String clusterName = viewName.toLowerCase(Locale.ENGLISH) + (i++);
if (!db.getClusterNames().contains(clusterName)) {
return clusterName;
}
}
}
private OElement copyElement(OResult item, ODatabaseDocument db) {
OElement newRow = db.newElement();
for (String prop : item.getPropertyNames()) {
if (!prop.equalsIgnoreCase("@rid")) {
newRow.setProperty(prop, item.getProperty(prop));
}
}
return newRow;
}
public void updateViewAsync(String name, ViewCreationListener listener) {
new Thread(() -> {
ODatabaseDocument db = orientDB.openNoAuthorization(dbName);
if (!buildOnThisNode(db, name)) {
return;
}
try {
OView view = db.getMetadata().getSchema().getView(name);
updateView(view, db);
if (listener != null) {
listener.afterCreate(name);
}
} catch (Exception e) {
if (listener != null) {
listener.onError(name, e);
}
} finally {
db.close();
}
}).start();
}
public synchronized void startUsingViewCluster(Integer cluster) {
AtomicInteger item = viewCluserVisitors.get(cluster);
if (item == null) {
item = new AtomicInteger(0);
viewCluserVisitors.put(cluster, item);
}
item.incrementAndGet();
}
public synchronized void endUsingViewCluster(Integer cluster) {
AtomicInteger item = viewCluserVisitors.get(cluster);
if (item == null) {
return;
}
item.decrementAndGet();
}
public void recordAdded(OImmutableClass clazz, ODocument doc, ODatabaseDocumentEmbedded oDatabaseDocumentEmbedded) {
lastChangePerClass.put(clazz.getName().toLowerCase(Locale.ENGLISH), System.currentTimeMillis());
}
public void recordUpdated(OImmutableClass clazz, ODocument doc, ODatabaseDocumentEmbedded oDatabaseDocumentEmbedded) {
lastChangePerClass.put(clazz.getName().toLowerCase(Locale.ENGLISH), System.currentTimeMillis());
}
public void recordDeleted(OImmutableClass clazz, ODocument doc, ODatabaseDocumentEmbedded oDatabaseDocumentEmbedded) {
lastChangePerClass.put(clazz.getName().toLowerCase(Locale.ENGLISH), System.currentTimeMillis());
}
public String getViewFromOldCluster(int clusterId){
return oldClustersPerViews.get(clusterId);
}
}