diff options
Diffstat (limited to 'src/main/java/org/traccar/schedule')
6 files changed, 276 insertions, 28 deletions
diff --git a/src/main/java/org/traccar/schedule/ScheduleManager.java b/src/main/java/org/traccar/schedule/ScheduleManager.java index 7a3d33b85..07cdb1fe1 100644 --- a/src/main/java/org/traccar/schedule/ScheduleManager.java +++ b/src/main/java/org/traccar/schedule/ScheduleManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2020 - 2022 Anton Tananaev (anton@traccar.org) + * Copyright 2020 - 2023 Anton Tananaev (anton@traccar.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,22 +15,35 @@ */ package org.traccar.schedule; +import com.google.inject.Injector; import org.traccar.LifecycleObject; +import jakarta.inject.Inject; +import jakarta.inject.Singleton; +import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; +@Singleton public class ScheduleManager implements LifecycleObject { + private final Injector injector; private ScheduledExecutorService executor; + @Inject + public ScheduleManager(Injector injector) { + this.injector = injector; + } + @Override public void start() { executor = Executors.newSingleThreadScheduledExecutor(); - - new TaskDeviceInactivityCheck().schedule(executor); - new TaskWebSocketKeepalive().schedule(executor); - new TaskHealthCheck().schedule(executor); + var tasks = List.of( + TaskReports.class, + TaskDeviceInactivityCheck.class, + TaskWebSocketKeepalive.class, + TaskHealthCheck.class); + tasks.forEach(task -> injector.getInstance(task).schedule(executor)); } @Override diff --git a/src/main/java/org/traccar/schedule/ScheduleTask.java b/src/main/java/org/traccar/schedule/ScheduleTask.java new file mode 100644 index 000000000..1b537213b --- /dev/null +++ b/src/main/java/org/traccar/schedule/ScheduleTask.java @@ -0,0 +1,22 @@ +/* + * Copyright 2022 Anton Tananaev (anton@traccar.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.traccar.schedule; + +import java.util.concurrent.ScheduledExecutorService; + +public interface ScheduleTask extends Runnable { + void schedule(ScheduledExecutorService executor); +} diff --git a/src/main/java/org/traccar/schedule/TaskDeviceInactivityCheck.java b/src/main/java/org/traccar/schedule/TaskDeviceInactivityCheck.java index 80641d7d4..8e45568d5 100644 --- a/src/main/java/org/traccar/schedule/TaskDeviceInactivityCheck.java +++ b/src/main/java/org/traccar/schedule/TaskDeviceInactivityCheck.java @@ -1,5 +1,5 @@ /* - * Copyright 2020 Anton Tananaev (anton@traccar.org) + * Copyright 2020 - 2023 Anton Tananaev (anton@traccar.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,17 +15,28 @@ */ package org.traccar.schedule; -import org.traccar.Context; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.traccar.database.NotificationManager; import org.traccar.model.Device; import org.traccar.model.Event; +import org.traccar.model.Group; import org.traccar.model.Position; +import org.traccar.storage.Storage; +import org.traccar.storage.StorageException; +import org.traccar.storage.query.Columns; +import org.traccar.storage.query.Request; +import jakarta.inject.Inject; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; -public class TaskDeviceInactivityCheck implements Runnable { +public class TaskDeviceInactivityCheck implements ScheduleTask { + + private static final Logger LOGGER = LoggerFactory.getLogger(TaskDeviceInactivityCheck.class); public static final String ATTRIBUTE_DEVICE_INACTIVITY_START = "deviceInactivityStart"; public static final String ATTRIBUTE_DEVICE_INACTIVITY_PERIOD = "deviceInactivityPeriod"; @@ -33,6 +44,16 @@ public class TaskDeviceInactivityCheck implements Runnable { private static final long CHECK_PERIOD_MINUTES = 15; + private final Storage storage; + private final NotificationManager notificationManager; + + @Inject + public TaskDeviceInactivityCheck(Storage storage, NotificationManager notificationManager) { + this.storage = storage; + this.notificationManager = notificationManager; + } + + @Override public void schedule(ScheduledExecutorService executor) { executor.scheduleAtFixedRate(this, CHECK_PERIOD_MINUTES, CHECK_PERIOD_MINUTES, TimeUnit.MINUTES); } @@ -43,19 +64,47 @@ public class TaskDeviceInactivityCheck implements Runnable { long checkPeriod = TimeUnit.MINUTES.toMillis(CHECK_PERIOD_MINUTES); Map<Event, Position> events = new HashMap<>(); - for (Device device : Context.getDeviceManager().getAllDevices()) { - if (device.getLastUpdate() != null && checkDevice(device, currentTime, checkPeriod)) { - Event event = new Event(Event.TYPE_DEVICE_INACTIVE, device.getId()); - event.set(ATTRIBUTE_LAST_UPDATE, device.getLastUpdate().getTime()); - events.put(event, null); + + try { + Map<Long, Group> groups = storage.getObjects(Group.class, new Request(new Columns.All())) + .stream().collect(Collectors.toMap(Group::getId, group -> group)); + for (Device device : storage.getObjects(Device.class, new Request(new Columns.All()))) { + if (device.getLastUpdate() != null && checkDevice(device, groups, currentTime, checkPeriod)) { + Event event = new Event(Event.TYPE_DEVICE_INACTIVE, device.getId()); + event.set(ATTRIBUTE_LAST_UPDATE, device.getLastUpdate().getTime()); + events.put(event, null); + } } + } catch (StorageException e) { + LOGGER.warn("Database error", e); } - Context.getNotificationManager().updateEvents(events); + notificationManager.updateEvents(events); + } + + private long getAttribute(Device device, Map<Long, Group> groups, String key) { + long deviceValue = device.getLong(key); + if (deviceValue > 0) { + return deviceValue; + } else { + long groupId = device.getGroupId(); + while (groupId > 0) { + Group group = groups.get(groupId); + if (group == null) { + return 0; + } + long groupValue = group.getLong(key); + if (groupValue > 0) { + return groupValue; + } + groupId = group.getGroupId(); + } + return 0; + } } - private boolean checkDevice(Device device, long currentTime, long checkPeriod) { - long deviceInactivityStart = device.getLong(ATTRIBUTE_DEVICE_INACTIVITY_START); + private boolean checkDevice(Device device, Map<Long, Group> groups, long currentTime, long checkPeriod) { + long deviceInactivityStart = getAttribute(device, groups, ATTRIBUTE_DEVICE_INACTIVITY_START); if (deviceInactivityStart > 0) { long timeThreshold = device.getLastUpdate().getTime() + deviceInactivityStart; if (currentTime >= timeThreshold) { @@ -64,7 +113,7 @@ public class TaskDeviceInactivityCheck implements Runnable { return true; } - long deviceInactivityPeriod = device.getLong(ATTRIBUTE_DEVICE_INACTIVITY_PERIOD); + long deviceInactivityPeriod = getAttribute(device, groups, ATTRIBUTE_DEVICE_INACTIVITY_PERIOD); if (deviceInactivityPeriod > 0) { long count = (currentTime - timeThreshold - 1) / deviceInactivityPeriod; timeThreshold += count * deviceInactivityPeriod; diff --git a/src/main/java/org/traccar/schedule/TaskHealthCheck.java b/src/main/java/org/traccar/schedule/TaskHealthCheck.java index 087cd3e63..abdc5af48 100644 --- a/src/main/java/org/traccar/schedule/TaskHealthCheck.java +++ b/src/main/java/org/traccar/schedule/TaskHealthCheck.java @@ -19,23 +19,31 @@ import com.sun.jna.Library; import com.sun.jna.Native; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.traccar.Context; +import org.traccar.config.Config; import org.traccar.config.Keys; +import jakarta.inject.Inject; +import jakarta.ws.rs.client.Client; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; -public class TaskHealthCheck implements Runnable { +public class TaskHealthCheck implements ScheduleTask { private static final Logger LOGGER = LoggerFactory.getLogger(TaskHealthCheck.class); + private final Config config; + private final Client client; + private SystemD systemD; private boolean enabled; private long period; - public TaskHealthCheck() { - if (!Context.getConfig().getBoolean(Keys.WEB_DISABLE_HEALTH_CHECK) + @Inject + public TaskHealthCheck(Config config, Client client) { + this.config = config; + this.client = client; + if (!config.getBoolean(Keys.WEB_DISABLE_HEALTH_CHECK) && System.getProperty("os.name").toLowerCase().startsWith("linux")) { try { systemD = Native.load("systemd", SystemD.class); @@ -54,11 +62,12 @@ public class TaskHealthCheck implements Runnable { } private String getUrl() { - String address = Context.getConfig().getString(Keys.WEB_ADDRESS, "localhost"); - int port = Context.getConfig().getInteger(Keys.WEB_PORT); + String address = config.getString(Keys.WEB_ADDRESS, "localhost"); + int port = config.getInteger(Keys.WEB_PORT); return "http://" + address + ":" + port + "/api/server"; } + @Override public void schedule(ScheduledExecutorService executor) { if (enabled) { executor.scheduleAtFixedRate(this, period, period, TimeUnit.MILLISECONDS); @@ -68,7 +77,7 @@ public class TaskHealthCheck implements Runnable { @Override public void run() { LOGGER.debug("Health check running"); - int status = Context.getClient().target(getUrl()).request().get().getStatus(); + int status = client.target(getUrl()).request().get().getStatus(); if (status == 200) { int result = systemD.sd_notify(0, "WATCHDOG=1"); if (result < 0) { diff --git a/src/main/java/org/traccar/schedule/TaskReports.java b/src/main/java/org/traccar/schedule/TaskReports.java new file mode 100644 index 000000000..30f20f437 --- /dev/null +++ b/src/main/java/org/traccar/schedule/TaskReports.java @@ -0,0 +1,146 @@ +/* + * Copyright 2023 Anton Tananaev (anton@traccar.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.traccar.schedule; + +import com.google.inject.Injector; +import com.google.inject.servlet.RequestScoper; +import com.google.inject.servlet.ServletScopes; +import net.fortuna.ical4j.model.Period; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.traccar.model.BaseModel; +import org.traccar.model.Calendar; +import org.traccar.model.Device; +import org.traccar.model.Group; +import org.traccar.model.Report; +import org.traccar.model.User; +import org.traccar.reports.EventsReportProvider; +import org.traccar.reports.RouteReportProvider; +import org.traccar.reports.StopsReportProvider; +import org.traccar.reports.SummaryReportProvider; +import org.traccar.reports.TripsReportProvider; +import org.traccar.reports.common.ReportMailer; +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 jakarta.inject.Inject; +import java.util.Collections; +import java.util.Date; +import java.util.List; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; + +public class TaskReports implements ScheduleTask { + + private static final Logger LOGGER = LoggerFactory.getLogger(TaskReports.class); + + private static final long CHECK_PERIOD_MINUTES = 1; + + private final Storage storage; + private final Injector injector; + + @Inject + public TaskReports(Storage storage, Injector injector) { + this.storage = storage; + this.injector = injector; + } + + @Override + public void schedule(ScheduledExecutorService executor) { + executor.scheduleAtFixedRate(this, CHECK_PERIOD_MINUTES, CHECK_PERIOD_MINUTES, TimeUnit.MINUTES); + } + + @Override + public void run() { + Date currentCheck = new Date(); + Date lastCheck = new Date(System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(CHECK_PERIOD_MINUTES)); + + try { + for (Report report : storage.getObjects(Report.class, new Request(new Columns.All()))) { + Calendar calendar = storage.getObject(Calendar.class, new Request( + new Columns.All(), new Condition.Equals("id", report.getCalendarId()))); + + var lastEvents = calendar.findPeriods(lastCheck); + var currentEvents = calendar.findPeriods(currentCheck); + + if (!lastEvents.isEmpty() && currentEvents.isEmpty()) { + Period period = lastEvents.iterator().next(); + RequestScoper scope = ServletScopes.scopeRequest(Collections.emptyMap()); + try (RequestScoper.CloseableScope ignored = scope.open()) { + executeReport(report, period.getStart(), period.getEnd()); + } + } + } + } catch (StorageException e) { + LOGGER.warn("Scheduled reports error", e); + } + } + + private void executeReport(Report report, Date from, Date to) throws StorageException { + + var deviceIds = storage.getObjects(Device.class, new Request( + new Columns.Include("id"), + new Condition.Permission(Device.class, Report.class, report.getId()))) + .stream().map(BaseModel::getId).collect(Collectors.toList()); + var groupIds = storage.getObjects(Group.class, new Request( + new Columns.Include("id"), + new Condition.Permission(Group.class, Report.class, report.getId()))) + .stream().map(BaseModel::getId).collect(Collectors.toList()); + var users = storage.getObjects(User.class, new Request( + new Columns.Include("id"), + new Condition.Permission(User.class, Report.class, report.getId()))); + + ReportMailer reportMailer = injector.getInstance(ReportMailer.class); + + for (User user : users) { + switch (report.getType()) { + case "events": + var eventsReportProvider = injector.getInstance(EventsReportProvider.class); + reportMailer.sendAsync(user.getId(), stream -> eventsReportProvider.getExcel( + stream, user.getId(), deviceIds, groupIds, List.of(), from, to)); + break; + case "route": + var routeReportProvider = injector.getInstance(RouteReportProvider.class); + reportMailer.sendAsync(user.getId(), stream -> routeReportProvider.getExcel( + stream, user.getId(), deviceIds, groupIds, from, to)); + break; + case "summary": + var summaryReportProvider = injector.getInstance(SummaryReportProvider.class); + reportMailer.sendAsync(user.getId(), stream -> summaryReportProvider.getExcel( + stream, user.getId(), deviceIds, groupIds, from, to, false)); + break; + case "trips": + var tripsReportProvider = injector.getInstance(TripsReportProvider.class); + reportMailer.sendAsync(user.getId(), stream -> tripsReportProvider.getExcel( + stream, user.getId(), deviceIds, groupIds, from, to)); + break; + case "stops": + var stopsReportProvider = injector.getInstance(StopsReportProvider.class); + reportMailer.sendAsync(user.getId(), stream -> stopsReportProvider.getExcel( + stream, user.getId(), deviceIds, groupIds, from, to)); + break; + default: + LOGGER.warn("Unsupported report type {}", report.getType()); + break; + } + } + } + +} diff --git a/src/main/java/org/traccar/schedule/TaskWebSocketKeepalive.java b/src/main/java/org/traccar/schedule/TaskWebSocketKeepalive.java index 953b0efea..d9e0c6f0b 100644 --- a/src/main/java/org/traccar/schedule/TaskWebSocketKeepalive.java +++ b/src/main/java/org/traccar/schedule/TaskWebSocketKeepalive.java @@ -1,5 +1,5 @@ /* - * Copyright 2021 Anton Tananaev (anton@traccar.org) + * Copyright 2021 - 2022 Anton Tananaev (anton@traccar.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,22 +15,31 @@ */ package org.traccar.schedule; -import org.traccar.Context; +import org.traccar.session.ConnectionManager; +import jakarta.inject.Inject; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; -public class TaskWebSocketKeepalive implements Runnable { +public class TaskWebSocketKeepalive implements ScheduleTask { private static final long PERIOD_SECONDS = 55; + private final ConnectionManager connectionManager; + + @Inject + public TaskWebSocketKeepalive(ConnectionManager connectionManager) { + this.connectionManager = connectionManager; + } + + @Override public void schedule(ScheduledExecutorService executor) { executor.scheduleAtFixedRate(this, PERIOD_SECONDS, PERIOD_SECONDS, TimeUnit.SECONDS); } @Override public void run() { - Context.getConnectionManager().sendKeepalive(); + connectionManager.sendKeepalive(); } } |