eive-obsw/mission/tmtc/PersistentTmStore.cpp

343 lines
12 KiB
C++
Raw Normal View History

2023-02-07 12:23:00 +01:00
#include "PersistentTmStore.h"
2022-11-11 15:39:27 +01:00
2022-10-25 18:20:21 +02:00
#include <mission/memory/SdCardMountedIF.h>
2022-11-11 15:39:27 +01:00
#include <algorithm>
2022-12-12 14:58:56 +01:00
#include <cinttypes>
2022-12-12 16:18:00 +01:00
#include <filesystem>
2022-12-12 18:42:51 +01:00
#include <fstream>
2022-12-13 15:56:40 +01:00
#include <utility>
2022-10-24 10:57:30 +02:00
2023-02-21 20:43:16 +01:00
#include "fsfw/ipc/CommandMessage.h"
#include "fsfw/ipc/QueueFactory.h"
#include "fsfw/tmstorage/TmStoreMessage.h"
2022-10-24 10:57:30 +02:00
using namespace returnvalue;
2023-02-21 21:37:30 +01:00
PersistentTmStore::PersistentTmStore(object_id_t objectId, const char* baseDir,
std::string baseName, RolloverInterval intervalUnit,
uint32_t intervalCount, timeval& currentTv,
StorageManagerIF& tmStore, SdCardMountedIF& sdcMan)
2022-12-14 10:42:16 +01:00
: SystemObject(objectId),
2023-02-20 17:57:18 +01:00
baseDir(baseDir),
2022-12-14 10:42:16 +01:00
baseName(std::move(baseName)),
currentTv(currentTv),
2023-02-07 12:19:13 +01:00
sdcMan(sdcMan),
tmStore(tmStore) {
2023-02-21 20:43:16 +01:00
tcQueue = QueueFactory::instance()->createMessageQueue();
2022-12-12 18:27:01 +01:00
calcDiffSeconds(intervalUnit, intervalCount);
}
2022-10-24 10:57:30 +02:00
2023-02-22 13:27:16 +01:00
ReturnValue_t PersistentTmStore::assignAndOrCreateMostRecentFile() {
using namespace std::filesystem;
for (auto const& file : directory_iterator(basePath)) {
if (file.is_directory()) {
continue;
}
auto pathStr = file.path().string();
if (pathStr.find(baseName) == std::string::npos) {
continue;
}
unsigned int underscorePos = pathStr.find_last_of('_');
std::string stampStr = pathStr.substr(underscorePos + 1);
struct tm time {};
if (nullptr == strptime(stampStr.c_str(), FILE_DATE_FORMAT, &time)) {
sif::error << "PersistentTmStore::assignOrCreateMostRecentFile: Error reading timestamp"
<< std::endl;
// Delete the file and re-create it.
activeFile = std::nullopt;
std::filesystem::remove(file.path());
break;
}
time_t fileEpoch = timegm(&time);
// There is still a file within the active time window, so re-use that file for new TMs to
// store.
if (fileEpoch + rolloverDiffSeconds > currentTv.tv_sec) {
activeFileTv.tv_sec = fileEpoch;
activeFile = file.path();
break;
}
}
if (not activeFile.has_value()) {
return createMostRecentFile();
}
return returnvalue::OK;
}
2023-02-21 21:37:30 +01:00
ReturnValue_t PersistentTmStore::handleCommandQueue(StorageManagerIF& ipcStore,
TmFunnelBase& tmFunnel) {
2023-02-21 20:43:16 +01:00
CommandMessage cmdMessage;
ReturnValue_t result = tcQueue->receiveMessage(&cmdMessage);
if (result == MessageQueueIF::EMPTY) {
return returnvalue::OK;
}
if (result != returnvalue::OK) {
return result;
}
if (cmdMessage.getMessageType() == messagetypes::TM_STORE) {
Command_t cmd = cmdMessage.getCommand();
if (cmd == TmStoreMessage::DELETE_STORE_CONTENT_TIME) {
store_address_t storeId = TmStoreMessage::getStoreId(&cmdMessage);
auto accessor = ipcStore.getData(storeId);
uint32_t deleteUpToUnixSeconds = 0;
size_t size = accessor.second.size();
SerializeAdapter::deSerialize(&deleteUpToUnixSeconds, accessor.second.data(), &size,
SerializeIF::Endianness::NETWORK);
deleteUpTo(deleteUpToUnixSeconds);
} else if (cmd == TmStoreMessage::DOWNLINK_STORE_CONTENT_TIME) {
store_address_t storeId = TmStoreMessage::getStoreId(&cmdMessage);
auto accessor = ipcStore.getData(storeId);
2023-02-22 13:27:16 +01:00
if (accessor.second.size() < 8) {
return returnvalue::FAILED;
}
2023-02-21 20:43:16 +01:00
uint32_t dumpFromUnixSeconds;
uint32_t dumpUntilUnixSeconds;
2023-02-22 13:27:16 +01:00
size_t size = 8;
2023-02-21 20:43:16 +01:00
SerializeAdapter::deSerialize(&dumpFromUnixSeconds, accessor.second.data(), &size,
SerializeIF::Endianness::NETWORK);
2023-02-22 13:27:16 +01:00
SerializeAdapter::deSerialize(&dumpUntilUnixSeconds, accessor.second.data() + 4, &size,
2023-02-21 20:43:16 +01:00
SerializeIF::Endianness::NETWORK);
dumpFromUpTo(dumpFromUnixSeconds, dumpUntilUnixSeconds, tmFunnel);
}
}
return returnvalue::OK;
}
2023-02-21 21:37:30 +01:00
ReturnValue_t PersistentTmStore::passPacket(PusTmReader& reader) {
2022-11-11 15:39:27 +01:00
bool inApidList = false;
if (filter.apid) {
auto& apidFilter = filter.apid.value();
if (std::find(apidFilter.begin(), apidFilter.end(), reader.getApid()) != apidFilter.end()) {
if (not filter.serviceSubservices and not filter.services) {
return storePacket(reader);
}
inApidList = true;
}
}
std::pair<uint8_t, uint8_t> serviceSubservice;
serviceSubservice.first = reader.getService();
serviceSubservice.second = reader.getSubService();
if (filter.services) {
auto& serviceFilter = filter.services.value();
if (std::find(serviceFilter.begin(), serviceFilter.end(), serviceSubservice.first) !=
serviceFilter.end()) {
if (filter.apid and inApidList) {
return storePacket(reader);
}
}
}
if (filter.serviceSubservices) {
auto& serviceSubserviceFilter = filter.serviceSubservices.value();
if (std::find(serviceSubserviceFilter.begin(), serviceSubserviceFilter.end(),
serviceSubservice) != serviceSubserviceFilter.end()) {
if (filter.apid and inApidList) {
return storePacket(reader);
}
}
}
2022-10-25 18:20:21 +02:00
return returnvalue::OK;
2022-10-24 10:57:30 +02:00
}
2023-02-21 21:37:30 +01:00
void PersistentTmStore::dumpFrom(uint32_t fromUnixSeconds, TmFunnelBase& tmFunnel) {
2023-02-07 15:22:01 +01:00
return dumpFromUpTo(fromUnixSeconds, currentTv.tv_sec, tmFunnel);
}
2023-02-21 21:37:30 +01:00
ReturnValue_t PersistentTmStore::storePacket(PusTmReader& reader) {
2022-12-12 10:06:30 +01:00
using namespace std::filesystem;
2022-12-12 18:27:01 +01:00
if (baseDirUninitialized) {
updateBaseDir();
2022-12-12 10:06:30 +01:00
}
2022-12-12 18:27:01 +01:00
// It is assumed here that the filesystem is usable.
2023-02-22 13:27:16 +01:00
if (not activeFile.has_value()) {
ReturnValue_t result = assignAndOrCreateMostRecentFile();
if (result != returnvalue::OK) {
return result;
}
2022-12-12 10:06:30 +01:00
}
2022-12-12 18:42:51 +01:00
2023-02-22 13:27:16 +01:00
if (currentTv.tv_sec < activeFileTv.tv_sec or
currentTv.tv_sec - activeFileTv.tv_sec > static_cast<int>(rolloverDiffSeconds)) {
if (file_size(activeFile.value()) + reader.getFullPacketLen() > fileBuf.size()) {
2022-12-13 10:07:36 +01:00
uint8_t appendedCounter = 1;
path rolloverName;
while (true) {
2023-02-22 13:27:16 +01:00
rolloverName = path(activeFile.value().string() + "." + std::to_string(appendedCounter));
2022-12-13 10:07:36 +01:00
if (not exists(rolloverName)) {
break;
}
appendedCounter++;
}
2023-02-22 13:27:16 +01:00
rename(activeFile.value(), rolloverName);
std::ofstream of(activeFile.value(), std::ios::binary);
2022-12-12 18:42:51 +01:00
}
}
// Rollover conditions were handled, write to file now
2023-02-22 13:27:16 +01:00
std::ofstream of(activeFile.value(), std::ios::app | std::ios::binary);
2023-02-21 20:43:16 +01:00
of.write(reinterpret_cast<const char*>(reader.getFullData()),
static_cast<std::streamsize>(reader.getFullPacketLen()));
2022-12-12 10:06:30 +01:00
return returnvalue::OK;
}
2022-11-11 15:39:27 +01:00
2023-02-21 21:37:30 +01:00
MessageQueueId_t PersistentTmStore::getCommandQueue() const { return tcQueue->getId(); }
2022-12-12 18:27:01 +01:00
2023-02-21 21:37:30 +01:00
void PersistentTmStore::calcDiffSeconds(RolloverInterval intervalUnit, uint32_t intervalCount) {
2022-12-13 15:34:13 +01:00
if (intervalUnit == RolloverInterval::MINUTELY) {
rolloverDiffSeconds = 60 * intervalCount;
} else if (intervalUnit == RolloverInterval::HOURLY) {
2022-12-13 13:46:49 +01:00
rolloverDiffSeconds = 60 * 60 * intervalCount;
2022-12-12 18:27:01 +01:00
} else if (intervalUnit == RolloverInterval::DAILY) {
2022-12-13 13:46:49 +01:00
rolloverDiffSeconds = 60 * 60 * 24 * intervalCount;
2022-12-12 18:27:01 +01:00
}
}
2023-02-21 21:37:30 +01:00
void PersistentTmStore::updateBaseDir() {
2022-12-12 18:27:01 +01:00
using namespace std::filesystem;
std::string currentPrefix = sdcMan.getCurrentMountPrefix();
2022-12-14 10:34:23 +01:00
basePath = path(currentPrefix) / baseDir / baseName;
if (not exists(basePath)) {
create_directories(basePath);
2022-12-12 18:27:01 +01:00
}
baseDirUninitialized = false;
}
2023-02-21 21:37:30 +01:00
void PersistentTmStore::addApid(uint16_t apid) {
2022-12-13 14:19:43 +01:00
if (not filter.apid) {
2022-12-13 15:56:40 +01:00
filter.apid = std::vector<uint16_t>({apid});
2022-12-13 14:19:43 +01:00
return;
}
filter.apid.value().push_back(apid);
}
2023-02-21 21:37:30 +01:00
void PersistentTmStore::addService(uint8_t service) {
2022-12-13 14:19:43 +01:00
if (not filter.services) {
2022-12-13 15:56:40 +01:00
filter.services = std::vector<uint8_t>({service});
2022-12-14 10:14:53 +01:00
return;
2022-12-13 14:19:43 +01:00
}
filter.services.value().push_back(service);
}
2022-12-13 15:56:40 +01:00
2023-02-21 21:37:30 +01:00
void PersistentTmStore::addServiceSubservice(uint8_t service, uint8_t subservice) {
2022-12-13 15:56:40 +01:00
if (not filter.serviceSubservices) {
filter.serviceSubservices =
std::vector<std::pair<uint8_t, uint8_t>>({std::pair(service, subservice)});
2022-12-14 10:14:53 +01:00
return;
2022-12-13 15:56:40 +01:00
}
2023-02-21 20:43:16 +01:00
filter.serviceSubservices.value().emplace_back(service, subservice);
2022-12-13 15:56:40 +01:00
}
2022-12-19 13:25:45 +01:00
2023-02-21 21:37:30 +01:00
void PersistentTmStore::deleteUpTo(uint32_t unixSeconds) {
2023-02-07 12:19:13 +01:00
using namespace std::filesystem;
for (auto const& file : directory_iterator(basePath)) {
2023-02-22 13:27:16 +01:00
if (file.is_directory() or (activeFile.has_value() and (activeFile.value() == file.path()))) {
2023-02-07 12:19:13 +01:00
continue;
}
2023-02-22 13:27:16 +01:00
// Convert file time to the UNIX epoch
struct tm fileTime {};
if (pathToTm(file.path(), fileTime) != returnvalue::OK) {
sif::error << "Time extraction for " << file << "failed" << std::endl;
2023-02-07 12:19:13 +01:00
continue;
}
2023-02-22 13:27:16 +01:00
time_t epoch = timegm(&fileTime);
if (epoch + rolloverDiffSeconds < unixSeconds) {
2023-02-07 12:19:13 +01:00
std::filesystem::remove(file.path());
}
}
}
2022-12-19 13:25:45 +01:00
2023-02-21 21:37:30 +01:00
void PersistentTmStore::dumpFromUpTo(uint32_t fromUnixSeconds, uint32_t upToUnixSeconds,
TmFunnelBase& funnel) {
2023-02-07 12:19:13 +01:00
using namespace std::filesystem;
for (auto const& file : directory_iterator(basePath)) {
2023-02-07 15:22:01 +01:00
if (file.is_directory()) {
continue;
}
2023-02-22 13:27:16 +01:00
struct tm fileTime {};
if (pathToTm(file.path(), fileTime) != returnvalue::OK) {
sif::error << "Time extraction for file " << file << "failed" << std::endl;
2023-02-07 12:19:13 +01:00
continue;
}
2023-02-22 13:27:16 +01:00
auto fileEpoch = static_cast<uint32_t>(timegm(&fileTime));
if ((fileEpoch > fromUnixSeconds) and (fileEpoch + rolloverDiffSeconds <= upToUnixSeconds)) {
fileToPackets(file, fileEpoch, funnel);
2023-02-07 12:19:13 +01:00
}
}
}
2023-02-22 13:27:16 +01:00
ReturnValue_t PersistentTmStore::pathToTm(const std::filesystem::path& path, struct tm& time) {
2023-02-07 12:19:13 +01:00
auto pathStr = path.string();
2023-02-21 20:43:16 +01:00
size_t splitChar = pathStr.find('_');
2023-02-22 13:27:16 +01:00
auto timeOnlyStr = pathStr.substr(splitChar + 1);
if (nullptr == strptime(timeOnlyStr.c_str(), FILE_DATE_FORMAT, &time)) {
return returnvalue::FAILED;
}
return returnvalue::OK;
2023-02-07 12:19:13 +01:00
}
2023-02-21 21:37:30 +01:00
void PersistentTmStore::fileToPackets(const std::filesystem::path& path, uint32_t unixStamp,
TmFunnelBase& funnel) {
2022-12-19 14:40:27 +01:00
store_address_t storeId;
TmTcMessage message;
2023-02-07 12:19:13 +01:00
size_t size = std::filesystem::file_size(path);
if (size < 6) {
// Can't even read the CCSDS header
return;
}
std::ifstream ifile(path, std::ios::binary);
2023-02-21 20:43:16 +01:00
ifile.read(reinterpret_cast<char*>(fileBuf.data()), static_cast<std::streamsize>(size));
2023-02-07 12:19:13 +01:00
size_t currentIdx = 0;
while (currentIdx < size) {
PusTmReader reader(&timeReader, fileBuf.data(), fileBuf.size());
// CRC check to fully ensure this is a valid TM
ReturnValue_t result = reader.parseDataWithCrcCheck();
if (result == returnvalue::OK) {
2023-02-17 17:05:39 +01:00
result = tmStore.addData(&storeId, fileBuf.data() + currentIdx, reader.getFullPacketLen());
2023-02-07 12:19:13 +01:00
if (result != returnvalue::OK) {
continue;
}
funnel.sendPacketToDestinations(storeId, message, fileBuf.data() + currentIdx,
reader.getFullPacketLen());
currentIdx += reader.getFullPacketLen();
} else {
sif::error << "Parsing of PUS TM failed with code " << result << std::endl;
triggerEvent(POSSIBLE_FILE_CORRUPTION, result, unixStamp);
// Stop for now, do not really know where to continue and we do not trust the file anymore.
break;
}
}
2022-12-19 14:40:27 +01:00
}
2023-02-22 13:27:16 +01:00
ReturnValue_t PersistentTmStore::createMostRecentFile() {
using namespace std::filesystem;
unsigned currentIdx = 0;
path pathStart = basePath / baseName;
memcpy(fileBuf.data() + currentIdx, pathStart.c_str(), pathStart.string().length());
currentIdx += pathStart.string().length();
fileBuf[currentIdx] = '_';
currentIdx += 1;
time_t epoch = currentTv.tv_sec;
struct tm* time = gmtime(&epoch);
size_t writtenBytes = strftime(reinterpret_cast<char*>(fileBuf.data() + currentIdx),
fileBuf.size(), FILE_DATE_FORMAT, time);
if (writtenBytes == 0) {
sif::error << "PersistentTmStore::createMostRecentFile: Could not create file timestamp"
<< std::endl;
return returnvalue::FAILED;
}
currentIdx += writtenBytes;
strncpy(reinterpret_cast<char*>(fileBuf.data() + currentIdx), ".bin",
fileBuf.size() - currentIdx);
currentIdx += 4;
path newPath(std::string(reinterpret_cast<const char*>(fileBuf.data()), currentIdx));
std::ofstream of(newPath, std::ios::binary);
activeFile = newPath;
activeFileTv = currentTv;
return returnvalue::OK;
}
ReturnValue_t PersistentTmStore::initializeTmStore() {
updateBaseDir();
return assignAndOrCreateMostRecentFile();
}