Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add performance improvements for opening websocket with SQL backed storage #5296

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
11 changes: 9 additions & 2 deletions src/main/java/org/traccar/api/AsyncSocket.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,13 @@
import org.traccar.model.Event;
import org.traccar.model.LogRecord;
import org.traccar.model.Position;
import org.traccar.model.User;
import org.traccar.session.ConnectionManager;
import org.traccar.storage.Storage;
import org.traccar.storage.StorageException;
import org.traccar.storage.query.Columns;
import org.traccar.storage.query.Condition;
import org.traccar.storage.query.Request;

import java.util.Collection;
import java.util.HashMap;
Expand Down Expand Up @@ -64,9 +68,12 @@ public void onWebSocketConnect(Session session) {

try {
Map<String, Collection<?>> data = new HashMap<>();
data.put(KEY_POSITIONS, PositionUtil.getLatestPositions(storage, userId));
var devices = storage.getObjects(Device.class, new Request(
new Columns.Include("id"),
new Condition.Permission(User.class, userId, Device.class)));
data.put(KEY_POSITIONS, PositionUtil.getLatestPositions(storage, userId, devices));
sendData(data);
connectionManager.addListener(userId, this);
connectionManager.addListener(userId, this, devices);
} catch (StorageException e) {
throw new RuntimeException(e);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ public Collection<Position> getJson(
new Columns.All(), new Condition.LatestPositions(deviceId)));
}
} else {
return PositionUtil.getLatestPositions(storage, getUserId());
return PositionUtil.getLatestPositions(storage, getUserId(), null);
}
}

Expand Down
13 changes: 8 additions & 5 deletions src/main/java/org/traccar/helper/model/PositionUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -64,14 +64,17 @@ public static List<Position> getPositions(
new Order("fixTime")));
}

public static List<Position> getLatestPositions(Storage storage, long userId) throws StorageException {
var devices = storage.getObjects(Device.class, new Request(
new Columns.Include("id"),
new Condition.Permission(User.class, userId, Device.class)));
public static List<Position> getLatestPositions(Storage storage, long userId, List<Device> devices)
throws StorageException {
if (devices == null) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the right solution is to do a single query that would combine devices query with positions.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree. I’ll refactor.

Copy link
Author

@revilo464 revilo464 Apr 10, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

While working on this suggestion, I found that org.traccar.storage.DatabaseStorage#getObjects only instantiates objects of a given type, and the members should match the SQL ResultSet. In the case of joining Positions to Devices in the Devices query, I would only be able to instantiate one or the other, unless I created another type of object (something akin to DevicePosition).

Would this be your recommendation?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not proposing to join tables, but filter positions by devices.

Copy link
Author

@revilo464 revilo464 Apr 10, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

From your first message in this thread proposing a single query that would combine devices query with positions I see no other way to do this than performing a join...

Here would be the proposed query which would seem to work:

-- only adding aliases and the INNER JOIN here
SELECT * FROM tc_devices td
INNER JOIN tc_positions tp on tp.id = td.positionid 
WHERE td.id IN (SELECT tc_user_device.deviceId FROM tc_user_device WHERE userId = ? UNION SELECT DISTINCT deviceId FROM tc_user_group INNER JOIN (SELECT id as parentId, id as groupId FROM tc_groups UNION SELECT groupId as parentId, id as groupId FROM tc_groups WHERE groupId IS NOT NULL UNION SELECT g2.groupId as parentId, g1.id as groupId FROM tc_groups AS g2 INNER JOIN tc_groups AS g1 ON g2.id = g1.groupId WHERE g2.groupId IS NOT NULL) AS all_groups ON tc_user_group.groupId = all_groups.parentId INNER JOIN (SELECT groupId as parentId, id as deviceId FROM tc_devices WHERE groupId IS NOT NULL) AS devices ON all_groups.groupId = devices.parentId WHERE userId = ?);

But as mentioned the Traccar DB interface in its current form only allows returning a single type of object.

When you suggest, however, filtering positions by devices, that seems to be exactly what I'm doing with the IN operator in this PR. Your current implementation also filters positions by devices, but it does this only after creating Java objects from all of the latest positions, flooding the heap when the amount of devices in the DB is large (>40k).

Would love to implement this in a way the project would appreciate. 😃

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't understand why you need joins. What I'm proposing is something like this:

SELECT * FROM tc_positions WHERE id IN (
  SELECT positionId FROM tc_devices WHERE id IN (
    ... something similar to the current permission query
  )
)

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the clarification Anton. I understand now.

However, this again adds the issue that we can't reuse the list of devices accessible to the user and this is the most expensive part of the servlet request right now. In all of my measurements the permission query takes the majority (>80%) of the wall time. I already refactored so it would only happen once. If we cannot save the deviceIds from the permission query then we repeat it again which doubles the wall time requirement of the servlet request again.

See attached what the servlet request looks like before removing the second call. Your proposal would require the second call again.

image

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's a different issue and I think it's a reasonable trade-off.

devices = storage.getObjects(Device.class, new Request(
new Columns.Include("id"),
new Condition.Permission(User.class, userId, Device.class)));
}
var deviceIds = devices.stream().map(BaseModel::getId).collect(Collectors.toUnmodifiableSet());

var positions = storage.getObjects(Position.class, new Request(
new Columns.All(), new Condition.LatestPositions()));
new Columns.All(), new Condition.LatestPositions(deviceIds)));
return positions.stream()
.filter(position -> deviceIds.contains(position.getDeviceId()))
.collect(Collectors.toList());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ public DevicesReportProvider(Config config, ReportUtils reportUtils, Storage sto

public Collection<DeviceReportItem> getObjects(long userId) throws StorageException {

var positions = PositionUtil.getLatestPositions(storage, userId).stream()
var positions = PositionUtil.getLatestPositions(storage, userId, null).stream()
.collect(Collectors.toMap(Message::getDeviceId, p -> p));

return storage.getObjects(Device.class, new Request(
Expand Down
5 changes: 2 additions & 3 deletions src/main/java/org/traccar/session/ConnectionManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -376,14 +376,13 @@ public interface UpdateListener {
void onUpdateLog(LogRecord record);
}

public synchronized void addListener(long userId, UpdateListener listener) throws StorageException {
public synchronized void addListener(long userId, UpdateListener listener, List<Device> devices)
throws StorageException {
var set = listeners.get(userId);
if (set == null) {
set = new HashSet<>();
listeners.put(userId, set);

var devices = storage.getObjects(Device.class, new Request(
new Columns.Include("id"), new Condition.Permission(User.class, userId, Device.class)));
userDevices.put(userId, devices.stream().map(BaseModel::getId).collect(Collectors.toSet()));
devices.forEach(device -> deviceUsers.computeIfAbsent(device.getId(), id -> new HashSet<>()).add(userId));
}
Expand Down
24 changes: 24 additions & 0 deletions src/main/java/org/traccar/storage/DatabaseStorage.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import jakarta.inject.Inject;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
Expand Down Expand Up @@ -230,6 +231,17 @@ private Map<String, Object> getConditionVariables(Condition genericCondition) {
var condition = (Condition.LatestPositions) genericCondition;
if (condition.getDeviceId() > 0) {
results.put("deviceId", condition.getDeviceId());
} else if (condition.getDeviceIds() != null) {
int paramMultiple = (condition.getDeviceIds().size() / 10) + 1;
List<Long> deviceList = new ArrayList<>(condition.getDeviceIds());
for (int i = 0; i < paramMultiple * 10; i++) {
String key = String.format("deviceId%s", i);
if (i < deviceList.size()) {
results.put(key, deviceList.get(i));
} else {
results.put(key, 0L);
}
}
}
}
return results;
Expand Down Expand Up @@ -291,6 +303,18 @@ private String formatCondition(Condition genericCondition, boolean appendWhere)
result.append(getStorageName(Device.class));
if (condition.getDeviceId() > 0) {
result.append(" WHERE id = :deviceId");
} else if (condition.getDeviceIds() != null) {
result.append(" WHERE id IN ( ");
int paramMultiple = (condition.getDeviceIds().size() / 10) + 1;
for (int i = 0; i < paramMultiple; i++) {
for (int j = 0; j < 10; j++) {
result.append(String.format(":deviceId%s", j + (10 * i)));
if (i != (paramMultiple - 1) || j != 9) {
result.append(", ");
}
}
}
result.append(" )");
Comment on lines +307 to +317
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This definitely doesn't look right. If a user has thousands of devices, they shouldn't be included here one by one.

}
result.append(")");

Expand Down
3 changes: 3 additions & 0 deletions src/main/java/org/traccar/storage/QueryBuilder.java
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,9 @@ public QueryBuilder setInteger(String name, int value) throws SQLException {
}

public QueryBuilder setLong(String name, long value) throws SQLException {
if (name.matches("^deviceId\\d+$")) {
return setLong(name, value, true);
}
return setLong(name, value, false);
}

Expand Down
16 changes: 12 additions & 4 deletions src/main/java/org/traccar/storage/query/Condition.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import org.traccar.model.GroupedModel;

import java.util.List;
import java.util.Set;

public interface Condition {

Expand Down Expand Up @@ -194,18 +195,25 @@ public boolean getIncludeGroups() {

class LatestPositions implements Condition {
private final long deviceId;
private final Set<Long> deviceIds;

public LatestPositions(long deviceId) {
this.deviceId = deviceId;
public LatestPositions(Set<Long> deviceIds) {
this.deviceId = 0;
this.deviceIds = deviceIds;
}

public LatestPositions() {
this(0);
public LatestPositions(long deviceId) {
this.deviceId = deviceId;
this.deviceIds = null;
}

public long getDeviceId() {
return deviceId;
}

public Set<Long> getDeviceIds() {
return deviceIds;
}
}

}