-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathStorage_Module.cpp
More file actions
2667 lines (2389 loc) · 99.5 KB
/
Copy pathStorage_Module.cpp
File metadata and controls
2667 lines (2389 loc) · 99.5 KB
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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2024: Arizona Board of Regents on Behalf of the University of Arizona
*/
#include "Storage_Module.h"
#include "SpinFreePacketTimer.h"
#include <iostream>
#include <algorithm>
#include <limits>
#include <filesystem>
#include <thread>
#include <atomic>
#include <nlohmann/json.hpp>
#include <ASDP_BufferPool.h>
#include <ASDP_SpinFreeQueue.hpp>
#include <ASDP_StreamPacketSortedQueue.h>
using namespace asdp;
using json = nlohmann::json;
static bool parseVersion(const std::string& versionStr, uint16_t& major, uint16_t& minor, uint16_t& patch) {
size_t pos1 = versionStr.find('.');
if (pos1 == std::string::npos) {
std::cerr << "Invalid version format. Expected format: major.minor.patch" << std::endl;
return false;
}
size_t pos2 = versionStr.find('.', pos1 + 1);
if (pos2 == std::string::npos) {
std::cerr << "Invalid version format. Expected format: major.minor.patch" << std::endl;
return false;
}
try {
major = static_cast<uint16_t>(std::stoi(versionStr.substr(0, pos1)));
minor = static_cast<uint16_t>(std::stoi(versionStr.substr(pos1 + 1, pos2 - pos1 - 1)));
patch = static_cast<uint16_t>(std::stoi(versionStr.substr(pos2 + 1)));
}
catch (const std::invalid_argument& e) {
std::cerr << "Invalid version number: " << e.what() << std::endl;
return false;
}
catch (const std::out_of_range& e) {
std::cerr << "Version number out of range: " << e.what() << std::endl;
return false;
}
return true;
}
Storage_Module_Server::Storage_Module_Server(Storage_Module* parent, uint32_t serialNumber, const std::string& NicName,
uint16_t sendPort, uint16_t listenPort, uint32_t maxPayloadSize, int verbosity)
: CoreServerBase(serialNumber, NicName, sendPort, listenPort, maxPayloadSize, verbosity)
, m_parent(parent)
, m_nicName(NicName)
, m_replayPaused(false)
, m_stopReplayThreads(false)
, m_replayElapsedTime(std::make_shared<ElapsedTimeWithPause>())
{
// Save the state of record on reset.
m_recordOnReset = parent->m_persistentState.StoringAtRestart();
// We start out in "live" mode. This changes when replay is started and stopped.
// This is true even when we don't have a live conncetion to a parent, according to the spec.
m_camerasStreaming = true;
// Add the storage API to our features.
m_features.push_back(STORAGE_API_AVAILABLE);
// Record the state message that we will modify and send to clients when we are in idle mode. If we have
// stored data, read and store a state message from the first stored stream. If not, the parent will fill
// in our stored state after we are constructed.
std::vector<uint32_t> storedStreamIDs = getStoredStreamIDs();
if (!storedStreamIDs.empty()) {
std::string error = ReadInitialTimeAndState(storedStreamIDs[0], m_stateMessage);
if (!error.empty()) {
if (m_verbosity >= 0) {
std::cerr << "Storage_Module_Server::Storage_Module_Server(): readInitialTimeAndState(): " + error << std::endl;
}
}
if (m_stateMessage != nullptr) {
ConfigureStateFromStoredState();
}
}
// See if there is a config.json file in the first storage root directory for this server.
// If so, see if it has an "analysisPort" entry. If so, open a JSONStringSender on that port.
std::string configFileName = m_parent->m_storageRoots.size() >= 1 ?
m_parent->m_storageRoots[0] + "/" + std::to_string(m_serial) + "/config.json" :
"./config.json";
if (std::filesystem::exists(configFileName)) {
try {
std::ifstream configFile(configFileName);
json configJson;
configFile >> configJson;
if (configJson.contains("analysisPort")) {
uint16_t analysisPort;
analysisPort = configJson["analysisPort"];
std::string url = "tcp://" + m_nicName + ":" + std::to_string(analysisPort);
Status status = JSONStringSender::Create(url, m_analysisAPISender);
if (status != OKAY) {
if (m_verbosity > 0) {
std::cerr << " Storage_Module_Server::AnalysisAPIMessagesThreadFunction(): Error creating JSONStringSender: " << ErrorMessage(status) << std::endl;
}
return;
}
if (m_verbosity > 1) {
std::cout << " Storage_Module::Server " << serialNumber << " created Analysis API sender created on port " << analysisPort << std::endl;
}
}
}
catch (const std::exception& e) {
if (m_verbosity >= 0) {
std::cerr << "Storage_Module_Server::Storage_Module_Server(): Error reading config.json: " << e.what() << std::endl;
}
}
}
}
Storage_Module_Server::~Storage_Module_Server()
{
// Stop the replay if it is running.
if (m_replaying) {
for (auto& client : m_clients) {
doStopReplay(CommandPacketStopReplay(), client);
}
}
// Tear down our analysis API sender if we have one.
m_analysisAPISender.reset();
}
Status Storage_Module_Server::ConfigureStateFromStoredState()
{
if (m_stateMessage == nullptr) {
return UNEXPECTED_INTERNAL_STATE;
}
// Get the list of features that the server supports.
// Add the storage API to our features if it is not already present.
Status status = m_stateMessage->GetFeatures(m_features);
if (status != OKAY) {
return status;
}
if (std::find(m_features.begin(), m_features.end(), STORAGE_API_AVAILABLE) == m_features.end()) {
m_features.push_back(STORAGE_API_AVAILABLE);
}
return OKAY;
}
std::string Storage_Module_Server::StreamFileName(uint32_t streamID, uint32_t cameraID) const
{
size_t numRoots = m_parent->m_storageRoots.size();
std::string root = ".";
if (numRoots > 0) {
root = m_parent->m_storageRoots[cameraID % numRoots];
}
return root + "/" + std::to_string(m_serial) + "/" + std::to_string(streamID) + "/stream" + std::to_string(cameraID) + ".dat";
}
std::string Storage_Module_Server::ReadInitialTimeAndState(uint32_t streamID, std::shared_ptr<MessageState>& stateMessage)
{
// Clear the state message so we can check below for when we have read one.
stateMessage.reset();
// Open the main stream file for the stream ID and read the first message from it, storing its time that we
// will use to offset message times. Then continue to read messages until we get a status message and use it
// to set the initial state of the server.
std::string fileName = StreamFileName(streamID, 0);
std::shared_ptr<ReceiverFile> replayFile = std::make_shared<ReceiverFile>(fileName);
if (replayFile->GetConstructorStatus() != OKAY) {
return "Cannot open " + fileName;
}
bool gotFirstTime = false;
while (!gotFirstTime || (stateMessage == nullptr)) {
// Get the next packet from the file.
std::shared_ptr<StreamPacket> packet;
size_t size = 0;
Status status = replayFile->ReceiveStreamPacket(1.0, packet, size);
if (status != OKAY) {
return "Cannot read state message from " + fileName;
}
// Go through any messages in the packet, pulling out a state message if there is one.
std::shared_ptr<Message> msg;
status = packet->GetNextMessage(msg);
while (msg != nullptr) {
// Get the time and store it for the first message
if (!gotFirstTime) {
Time time;
status = msg->GetTime(time);
if (status != OKAY) {
return "Cannot get time from packet";
}
m_replayFirstTime = time;
gotFirstTime = true;
}
// Check to see if we have a state message.
MessageID msgID;
status = msg->GetType(msgID);
if (status != OKAY) {
return "Cannot get message type from packet";
}
if (msgID == STATE) {
stateMessage = std::make_shared<MessageState>(*msg);
if (stateMessage->GetConstructorStatus() != OKAY) {
return "Cannot construct state message";
}
}
status = packet->GetNextMessage(msg);
if (status != OKAY) {
return "Cannot get next message from packet";
}
}
}
return "";
}
void Storage_Module_Server::clientBeingRemoved(ClientState& client)
{
// Remove any subregions that this client has set up on any of the cameras.
{
std::unique_lock<std::shared_mutex> lock(m_subregionMutex);
// Every entry in a map is a pair of key and value. The first entry in the
// pair is the camera ID, which is used to index the map entry and clear it.
for (const auto& pair : m_subregions) {
m_subregions[pair.first].clear();
}
}
// Stop replay when the last client is being removed.
if (m_replaying && (m_clients.size() == 1)) {
doStopReplay(CommandPacketStopReplay(), client);
}
}
Time Storage_Module_Server::getCurrentReplayTime() const
{
return m_replayFirstTime + m_replayElapsedTime->ElapsedTime();
}
void Storage_Module_Server::doEveryLoop()
{
// Keep track of the period between calls to this function. When it has been more than the reporting frequency
// since the last time we reported, report the time per iteration statistics and then reset the
// counters.
if (m_verbosity >= 15) {
auto now = std::chrono::steady_clock::now();
auto deltaPrint = now - m_lastReportIterationTime;
if (deltaPrint > std::chrono::milliseconds(500)) {
if (m_iterationCount > 0) {
m_meanTimePerIteration = m_meanTimePerIteration / m_iterationCount;
std::cout << "doEveryLoop(): Mean time per iteration: " << m_meanTimePerIteration*1000 << " milliseconds, max: " << m_maxTimePerIteration*1000 << std::endl;
}
m_iterationCount = 0;
m_meanTimePerIteration = 0.0;
m_maxTimePerIteration = 0.0;
m_lastReportIterationTime = now;
} else {
auto delta = now - m_lastEveryIteration;
double deltaMs = std::chrono::duration_cast<std::chrono::microseconds>(delta).count();
m_meanTimePerIteration += deltaMs / 1e6;
m_maxTimePerIteration = std::max(m_maxTimePerIteration, deltaMs / 1e6);
m_iterationCount++;
}
m_lastEveryIteration = now;
}
// If the threads are supposed to be stopping, set an error indicating
// this.
if (m_parent->m_stop) {
m_error = "Server is stopping";
}
// If we are replaying, check for and handle incoming data.
auto now = std::chrono::steady_clock::now();
if (m_replaying) {
// Update the replay time in our parent class.
m_streamReplayTime = getCurrentReplayTime();
// If we don't have a next packet (may be held because it was in the future), read one and find
// its replay time.
if (m_replayPacket == nullptr) {
size_t offset = 0;
Status status = m_replayFiles[0]->ReceiveStreamPacket(0, m_replayPacket, offset);
if ((status != OKAY) && (status != TIMEOUT)) {
m_error = "doEveryLoop(): Error reading replay file: " + ErrorMessage(status);
return;
}
if (status != TIMEOUT) {
// Read the time from the first message in the packet.
std::shared_ptr<Message> msg;
status = m_replayPacket->GetNextMessage(msg);
if (status != OKAY) {
m_error = "doEveryLoop(): Error getting message from packet: " + ErrorMessage(status);
return;
}
status = msg->GetTime(m_replayPacketTime);
if (status != OKAY) {
m_error = "doEveryLoop(): Error getting time from message: " + ErrorMessage(status);
return;
}
}
// If we're at the end of the file (no more packets available), record that we are at the end of replay.
bool available;
status = m_replayFiles[0]->IsPacketAvailable(0, available);
if (status != OKAY) {
m_error = "doEveryLoop(): Error checking for packet availability: " + ErrorMessage(status);
return;
}
m_replayAtEnd = !available;
}
// If the current packet is in the present or past then process it.
// We don't need a lock on m_streamReplayTime here because we're in the same thread that modifies it
if ((m_replayPacket != nullptr) && (m_replayPacketTime <= m_streamReplayTime)) {
std::string ret = ForwardPacketToClients(m_replayPacket, true);
if (!ret.empty()) {
m_error = "doEveryLoop(): " + ret;
return;
}
// Done with the packet. We'll look for a new one the next time through.
m_replayPacket.reset();
}
// Flush all messages to the clients. This may fail because of a closed client.
for (auto& client : m_clients) {
Status status = client.m_writer->Flush();
if (status != OKAY) {
if (m_verbosity >= 0) {
std::cerr << "Storage_Module_Server::doEveryLoop(): Error flushing StreamWriter: " << ErrorMessage(status) << std::endl;
std::cerr << " (Client may have disconnected)" << std::endl;
}
}
}
} else {
// Not replaying, so can't be at the end.
m_replayAtEnd = false;
}
// Once per second, check and fill in the disk-space information in our state.
if (now - m_lastCheckDiskSpace > std::chrono::seconds(1)) {
std::filesystem::space_info minSpaceInfo;
for (const auto& root : m_parent->m_storageRoots) {
std::filesystem::space_info info = std::filesystem::space(root);
if (root == m_parent->m_storageRoots[0]) {
minSpaceInfo = info;
}
else {
if (info.available < minSpaceInfo.available) {
minSpaceInfo = info;
}
}
}
// When we have multiple storage roots, we assume that the data is spread evenly across them and
// that the relevant one to report on is the smallest.
m_remainingDiskSpace = minSpaceInfo.available * m_parent->m_storageRoots.size();
m_totalDiskSpace = minSpaceInfo.capacity * m_parent->m_storageRoots.size();
m_lastCheckDiskSpace = now;
}
}
void Storage_Module_Server::doReset(const CommandPacketReset& command, ClientState& client)
{
// Close all client connections
m_clients.clear();
// Stop storing and then re-start it if we're supposed to record on reset.
m_parent->StopStoring();
if (m_parent->m_persistentState.StoringAtRestart()) {
m_parent->StartStoring();
}
// Reset our clock to count up from zero starting now.
Time now;
Status status = m_timer->GetCoreTime(now);
if (status != OKAY) {
m_error = "doReset(): Error getting time: " + ErrorMessage(status);
return;
}
status = m_timer->SetCoreNegativeOffset(now);
if (status != OKAY) {
m_error = "doReset(): Error setting negative offset: " + ErrorMessage(status);
return;
}
Time zeroTime;
status = m_timer->SetCorePositiveOffset(zeroTime);
if (status != OKAY) {
m_error = "doReset(): Error setting positive offset: " + ErrorMessage(status);
return;
}
}
void Storage_Module_Server::doSetStreamStatePeriod(const CommandPacketSetStreamStatePeriod& command, ClientState& client)
{
if (CurrentMode() == Storage_Module_Server::Mode::Live) {
m_parent->SendCommandPacket(command);
}
}
void Storage_Module_Server::doSetNUCFlagState(const CommandPacketSetNUCFlagState& command, ClientState& client)
{
if (CurrentMode() == Storage_Module_Server::Mode::Live) {
m_parent->SendCommandPacket(command);
}
}
void Storage_Module_Server::doStartOnCameraNUC(const CommandPacketStartOnCameraNUC& command, ClientState& client)
{
if (CurrentMode() == Storage_Module_Server::Mode::Live) {
m_parent->SendCommandPacket(command);
}
}
void Storage_Module_Server::doConfigureTrigger(const CommandPacketConfigureTrigger& command, ClientState& client)
{
if (CurrentMode() == Storage_Module_Server::Mode::Live) {
m_parent->SendCommandPacket(command);
}
}
void Storage_Module_Server::doSoftwareTrigger(const CommandPacketSoftwareTrigger& command, ClientState& client)
{
if (CurrentMode() == Storage_Module_Server::Mode::Live) {
m_parent->SendCommandPacket(command);
}
}
void Storage_Module_Server::doStreamSubregion(const CommandPacketStreamSubregion& command, ClientState& client)
{
// Fill in the subregion description and endpoint from the command packet.
SubregionDescription subregion;
Status status = command.GetRegionDescription(subregion);
if (status != OKAY) {
m_error = ErrorMessage(status);
return;
}
StreamEndpoint endpoint;
status = command.GetEndpoint(endpoint);
if (status != OKAY) {
m_error = ErrorMessage(status);
return;
}
// Make a UDP sender for the endpoint and attach it to a writer.
std::shared_ptr<SenderUDP> sender = std::make_shared<SenderUDP>(endpoint);
std::shared_ptr<StreamWriter> writer = std::make_shared<StreamWriter>(sender, m_maxPayloadSize);
// Store the information, locking the mutex while doing so. If there is already an entry for this
// endpoint on this camera and client, overwrite it. If there is not an entry, add it.
std::shared_ptr<ReplayInfo> info = std::make_shared<ReplayInfo>();
info->subregion = subregion;
info->writer = writer;
std::unique_lock<std::shared_mutex> lock(m_subregionMutex);
m_subregions[subregion.cameraID][client][endpoint] = info;
}
void Storage_Module_Server::doCancelSubregion(const CommandPacketCancelSubregion& command, ClientState& client)
{
// Get the camera ID and endpoint from the command packet.
uint32_t cameraID;
Status status = command.GetCamera(cameraID);
if (status != OKAY) {
m_error = ErrorMessage(status);
return;
}
StreamEndpoint endpoint;
status = command.GetEndpoint(endpoint);
if (status != OKAY) {
m_error = ErrorMessage(status);
return;
}
// Remove any entry, locking the mutex while doing so. If there is not an entry, ignore that fact.
std::unique_lock<std::shared_mutex> lock(m_subregionMutex);
m_subregions[cameraID][client].erase(endpoint);
}
void Storage_Module_Server::doStartRecording(const CommandPacketStartRecording& command, ClientState& client)
{
// If the parent has the same serial number as we do, then try to start storing on it (which will also set our state).
// Otherwise, we ignore the command because we can only replay and not store.
if (m_parent->m_serial == m_serial) {
Status status = m_parent->StartStoring();
if (status != OKAY) {
m_error = ErrorMessage(status);
}
}
}
void Storage_Module_Server::doStopRecording(const CommandPacketStopRecording& command, ClientState& client)
{
// If the parent has the same serial number as we do, then try to stop storing on it (which will also set our state).
// Otherwise, we ignore the command because we can only replay and not store.
if (m_parent->m_serial == m_serial) {
Status status = m_parent->StopStoring();
if (status != OKAY) {
m_error = ErrorMessage(status);
}
}
}
void Storage_Module_Server::doSetStartUpRecordingState(const CommandPacketSetStartUpRecordingState& command, ClientState& client)
{
std::lock_guard<std::mutex> lock(m_parent->m_storageMutex);
uint32_t state;
Status status = command.GetState(state);
if (status != OKAY) {
m_error = ErrorMessage(status);
return;
}
m_parent->m_persistentState.SetStoringAtRestart(state != 0);
if (!m_parent->m_persistentState.SaveToFile()) {
m_error = "Failed to save persistent-state file";
}
m_recordOnReset = m_parent->m_persistentState.StoringAtRestart();
}
std::vector<uint32_t> Storage_Module_Server::getStoredStreamIDs() const
{
// Find a list of directory names in the first storage root directory for our serial number.
// Select the ones that can be parsed as unsigned integers.
std::vector<uint32_t> storedStreamIDs;
std::filesystem::path dirPath = ".";
if (!m_parent->m_storageRoots.empty()) {
dirPath = m_parent->m_storageRoots[0];
}
dirPath /= std::to_string(m_serial);
for (const auto& entry : std::filesystem::directory_iterator(dirPath)) {
uint32_t streamID = 0;
if (entry.is_directory()) {
try {
streamID = std::stoul(entry.path().filename().string());
storedStreamIDs.push_back(streamID);
}
catch (...) {
// Nothing to do here.
}
}
}
std::sort(storedStreamIDs.begin(), storedStreamIDs.end());
return storedStreamIDs;
}
void Storage_Module_Server::doListStoredStreams(const CommandPacketListStoredStreams& command, ClientState& client)
{
std::lock_guard<std::mutex> lock(m_parent->m_storageMutex);
// Find a list of directory names in the storage root directory for our serial number.
// Select the ones that can be parsed as unsigned integers.
std::vector<uint32_t> storedStreamIDs = getStoredStreamIDs();
// Send the list of stored streams back to the client.
Status status;
Time timeCode;
status = m_timer->GetCoreTime(timeCode);
if (status != OKAY) {
m_error = "doListStoredStreams(): Error getting time: " + ErrorMessage(status);
return;
}
for (auto& client : m_clients) {
std::shared_ptr<StreamPacket> packet;
status = client.m_writer->GetCurrentPacket(packet);
if (status != OKAY) {
m_error = "doListStoredStreams(): Error getting current packet: " + ErrorMessage(status);
return;
}
MessageStoredStreamList message(*packet, timeCode, storedStreamIDs);
if (message.GetConstructorStatus() != OKAY) {
m_error = "doListStoredStreams(): Error constructing MessageStoredStreamList: "
+ ErrorMessage(message.GetConstructorStatus())
+ " (client may have disconnected)";
return;
}
// Send the packet.
status = client.m_writer->Flush();
if (status != OKAY) {
if (m_verbosity >= 0) {
std::cerr << "doListStoredStreams(): Error flushing StreamWriter: " << ErrorMessage(status) << std::endl;
std::cerr << " (Client may have disconnected)" << std::endl;
}
}
}
}
void Storage_Module_Server::doEraseAllStoredStreams(const CommandPacketEraseAllStoredStreams& command, ClientState& client)
{
std::lock_guard<std::mutex> lock(m_parent->m_storageMutex);
// Find a list of directory names in the storage root directories for our serial number.
// Select the ones that can be parsed as unsigned integers.
std::vector<uint32_t> storedStreamIDs;
for (std::filesystem::path dirPath : m_parent->m_storageRoots) {
dirPath /= std::to_string(m_serial);
for (const auto& entry : std::filesystem::directory_iterator(dirPath)) {
uint32_t streamID = 0;
try {
streamID = std::stoul(entry.path().filename().string());
storedStreamIDs.push_back(streamID);
} catch (const std::filesystem::filesystem_error& e) {
// Ignore any errors that occur while deleting the directories.
}
}
// Avoid deleting a stream that is currently being written to.
// Remove the currently-storing stream ID from the list if there is one.
if (m_parent->m_writingToID > 0) {
auto it = std::find(storedStreamIDs.begin(), storedStreamIDs.end(), m_parent->m_writingToID);
if (it != storedStreamIDs.end()) {
storedStreamIDs.erase(it);
}
}
// Erase all the stored streams remaining in the list by recursively removing their directory tree.
for (auto streamID : storedStreamIDs) {
std::filesystem::path streamPath = dirPath;
streamPath /= std::to_string(streamID);
try {
std::filesystem::remove_all(streamPath);
} catch (const std::filesystem::filesystem_error& e) {
// Ignore any errors that occur while deleting the directories.
}
}
}
}
void Storage_Module_Server::doEraseStoredStream(const CommandPacketEraseStoredStream& command, ClientState& client)
{
std::lock_guard<std::mutex> lock(m_parent->m_storageMutex);
// Find the ID of the stream to erase.
uint32_t streamID;
Status status = command.GetID(streamID);
if (status != OKAY) {
m_error = "doListStoredStreams(): " + ErrorMessage(status);
return;
}
// Avoid deleting a stream that is currently being written to (do nothing).
if (streamID == m_parent->m_writingToID) {
return;
}
// Erase the stored stream by removing its directory tree from all storage roots.
for (std::filesystem::path streamPath : m_parent->m_storageRoots) {
streamPath /= std::to_string(m_serial);
streamPath /= std::to_string(streamID);
try {
std::filesystem::remove_all(streamPath);
} catch (const std::filesystem::filesystem_error& e) {
// Ignore any errors that occur while deleting the directories.
}
}
}
void Storage_Module_Server::doStartReplay(const CommandPacketStartReplay& command, ClientState& client)
{
// If we're already replaying, then stop replaying first. Do this before we grab the mutex because
// the other command will grab it.
if (m_replaying) {
doStopReplay(CommandPacketStopReplay(), client);
}
std::unique_lock<std::shared_mutex> lock(m_replayMutex);
// Parse the command packet to get the stream ID to replay and time offset.
uint32_t streamID;
Status status = command.GetID(streamID);
if (status != OKAY) {
m_error = "doStartReplay(): " + ErrorMessage(status);
return;
}
status = command.GetInitialTime(m_replayInitialTime);
if (status != OKAY) {
m_error = "doStartReplay(): " + ErrorMessage(status);
return;
}
// Open the main stream file for the stream ID and read the first message from it, storing its time that we
// will use to offset message times. Then continue to read messages until we get a status message and use it
// to set the initial state of the server.
std::shared_ptr<MessageState> stateMessage;
std::string error = ReadInitialTimeAndState(streamID, stateMessage);
if (stateMessage != nullptr) {
m_stateMessage = stateMessage;
status = ConfigureStateFromStoredState();
if (status != OKAY) {
m_error = "Storage_Module_Server::doStartReplay(): Error configuring state from stored state: " + ErrorMessage(status);
return;
}
}
if (!error.empty()) {
if (m_verbosity >= 0) {
std::cerr << "Storage_Module_Server::doStartReplay(): " + error << std::endl;
}
// Ignore the error and return. We will not be able to replay without the file.
m_replayFiles.clear();
return;
}
if (m_verbosity > 1) {
std::cout << " Storage_Module_Server::Opened replay file for stream: " << streamID << std::endl;
}
if (m_verbosity > 3) {
std::cout << " First time from replay file: " << m_replayFirstTime.seconds << ":" << m_replayFirstTime.microseconds << std::endl;
}
// Start replay at the beginning of the file, with offset based on the current steady-clock value.
m_replayElapsedTime->Reset();
// Find out how many cameras we have from the state message.
std::vector<CameraInfo> cameras;
status = m_stateMessage->GetCameras(cameras);
if (status != OKAY) {
if (m_verbosity >= 0) {
std::cerr << "Storage_Module_Server::doStartReplay(): Cannot get cameras from state message" << std::endl;
}
// Ignore the error and return. We will not be able to replay without the file.
m_replayFiles.clear();
return;
}
if (m_verbosity > 3) {
std::cout << " Number of cameras in replay file: " << cameras.size() << std::endl;
}
m_replayThreads.resize(cameras.size() + 1);
m_replayFiles.resize(cameras.size() + 1);
// Restart the main stream file so that all packets will be read from it and passed on.
m_replayFiles[0].reset();
std::string fileName = StreamFileName(streamID, 0);
m_replayFiles[0] = std::make_shared<ReceiverFile>(fileName);
// Open the camera stream files for each stream ID, add them round-robin along with camera IDs to a set of
// vectors and start the stream replay threads with those vectors.
m_stopReplayThreads = false;
// 21 threads was optimum on 6/20/2025, using a single thread per camera unless doing stereo.
static const size_t MAX_REPLAY_THREADS = 21;
std::vector< std::vector<ReplayCameraDescription> > cameraBatches(
std::min(cameras.size(), MAX_REPLAY_THREADS));
for (uint32_t i = 1; i <= cameras.size(); i++) {
ReplayCameraDescription desc;
desc.cameraID = i;
std::string fileName = StreamFileName(streamID, i);
desc.receiver = std::make_shared<ReceiverFile>(fileName);
cameraBatches[(i-1) % cameraBatches.size()].push_back(desc);
}
for (size_t i = 0; i < cameraBatches.size(); i++) {
m_replayThreads[i] = std::thread(&Storage_Module_Server::ReplayThread, this, cameraBatches[i]);
}
// Start the analysis API thread if we have an analysis directory. See if it exists and is a directory.
{
std::string rootDir = ".";
if (!m_parent->m_storageRoots.empty()) {
rootDir = m_parent->m_storageRoots[0];
}
std::string anaDir = rootDir + "/" + std::to_string(m_serial) + "/" + std::to_string(streamID) + "/analysis";
if (std::filesystem::exists(anaDir) && std::filesystem::is_directory(anaDir)) {
m_stopAnalysisAPIThread = false;
m_analysisAPIThread = std::thread(&Storage_Module_Server::AnalysisAPIMessagesThreadFunction, this, anaDir);
}
}
// Switching away from live mode and not paused.
m_replayAtEnd = false;
m_camerasStreaming = false;
m_replayPacket.reset();
m_replaying = true;
m_replayPaused = false;
// Get the current time in idle or live mode so we can send the START_OF_REPLAY with it.
Time nowInLive;
status = m_timer->GetCoreTime(nowInLive);
if (status != OKAY) {
m_error = "Storage_Module_Server::doStartReplay(): Error getting time: " + ErrorMessage(status);
return;
}
if (CurrentMode() == Storage_Module_Server::Mode::Live) {
m_parent->m_timer->GetCoreTime(nowInLive);
}
// Inform the client that we are replaying by sending a START_OF_REPLAY message
// followed by a clock-sync message. Use the old time code for the first and the new for
// the second.
for (auto& client : m_clients) {
// Clear the last-sent message times so that we send a new message stream starting now.
client.m_lastStateSent = { 0, 0 };
client.m_lastClockSent = { 0, 0 };
std::shared_ptr<StreamPacket> packet;
status = client.m_writer->GetCurrentPacket(packet);
if (status != OKAY) {
m_error = "Storage_Module_Server::doStartReplay(): Error getting current packet: " + ErrorMessage(status);
return;
}
// The start-of-replay message is sent with the current time code.
MessageEvent message(*packet, nowInLive, 0, START_OF_REPLAY,
std::to_string(streamID));
if (message.GetConstructorStatus() != OKAY) {
m_error = "Storage_Module_Server::doStartReplay(): Error constructing MessageReplayStarted: " + ErrorMessage(message.GetConstructorStatus());
return;
}
// The clock-sync message is sent with the replay time code.
MessageEvent message2(*packet, m_replayInitialTime, 0, CLOCK_SYNC, "");
if (message2.GetConstructorStatus() != OKAY) {
m_error = "Storage_Module_Server::doStartReplay(): Error constructing MessageClockSync: " + ErrorMessage(message2.GetConstructorStatus());
return;
}
// Send the packet.
status = client.m_writer->Flush();
if (status != OKAY) {
// Client may have disconnected.
if (m_verbosity >= 0) {
std::cerr << "Storage_Module_Server::doStartReplay(): Error flushing StreamWriter: " << ErrorMessage(status) << std::endl;
std::cerr << " (Client may have disconnected)" << std::endl;
}
}
}
}
Time Storage_Module_Server::AdjustTimeForReplay(Time const & timeCode) const
{
Time time = timeCode;
// Never go below zero before adding the initial time.
if (time >= m_replayFirstTime) {
time -= m_replayFirstTime;
} else {
time = Time(0, 0);
}
time += m_replayInitialTime;
return std::move(time);
}
void Storage_Module_Server::doPauseReplay(const CommandPacketPauseReplay& command, ClientState& client)
{
// Do nothing if we're not replaying.
if (!m_replaying) {
return;
}
m_replayElapsedTime->Pause();
m_replayPaused = true;
// Tell all clients that we are paused.
Status status;
for (auto& client : m_clients) {
std::shared_ptr<StreamPacket> packet;
status = client.m_writer->GetCurrentPacket(packet);
if (status != OKAY) {
m_error = "doPauseReplay(): Error getting current packet: " + ErrorMessage(status);
return;
}
MessageEvent message(*packet, AdjustTimeForReplay(getCurrentReplayTime()), 0, REPLAY_PAUSED, "");
if (message.GetConstructorStatus() != OKAY) {
m_error = "doPauseReplay(): Error constructing MessageStoredStreamList: "
+ ErrorMessage(message.GetConstructorStatus())
+ " (client may have disconnected)";
return;
}
// Send the packet.
status = client.m_writer->Flush();
if (status != OKAY) {
if (m_verbosity >= 0) {
std::cerr << "doPauseReplay(): Error flushing StreamWriter: " << ErrorMessage(status) << std::endl;
std::cerr << " (Client may have disconnected)" << std::endl;
}
}
}
}
void Storage_Module_Server::doResumeReplay(const CommandPacketResumeReplay& command, ClientState& client)
{
// Do nothing if we're not replaying.
if (!m_replaying) {
return;
}
m_replayElapsedTime->Resume();
m_replayPaused = false;
// Tell all clients that we are resumed.
Status status;
for (auto& client : m_clients) {
std::shared_ptr<StreamPacket> packet;
status = client.m_writer->GetCurrentPacket(packet);
if (status != OKAY) {
m_error = "doResumeReplay(): Error getting current packet: " + ErrorMessage(status);
return;
}
MessageEvent message(*packet, AdjustTimeForReplay(getCurrentReplayTime()), 0, REPLAY_RESUMED, "");
if (message.GetConstructorStatus() != OKAY) {
m_error = "doResumeReplay(): Error constructing MessageStoredStreamList: "
+ ErrorMessage(message.GetConstructorStatus())
+ " (client may have disconnected)";
return;
}
// Send the packet.
status = client.m_writer->Flush();
if (status != OKAY) {
if (m_verbosity >= 0) {
std::cerr << "doResumeReplay(): Error flushing StreamWriter: " << ErrorMessage(status) << std::endl;
std::cerr << " (Client may have disconnected)" << std::endl;
}
}
}
}
void Storage_Module_Server::doStopReplay(const CommandPacketStopReplay& command, ClientState& client)
{
// Do nothing if we're not replaying.
if (!m_replaying) {
return;
}
// Stop our analysis API thread if it is running.
m_stopAnalysisAPIThread = true;
if (m_analysisAPIThread.joinable()) {
m_analysisAPIThread.join();
}
// Stop all of our per-camera receive threads.
m_stopReplayThreads = true;
for (auto& thread : m_replayThreads) {
// The zeroeth thread will not be joinable because it is not started; the main thread handles it.
if (thread.joinable()) {
thread.join();
}
}
// Wait to grab the lock until all threads have stopped because they may be using the mutex.
std::unique_lock<std::shared_mutex> lock(m_replayMutex);
m_replayThreads.clear();
// Stop all of our stream receivers.
m_replayFiles.clear();
// Switching back to live (or idle) mode.
m_camerasStreaming = true;
m_replayPacket.reset();
m_replaying = false;
Time nowInReplay = m_replayFirstTime + m_replayElapsedTime->ElapsedTime();
// Inform the clients that we are no longer replaying by sending an END_OF_REPLAY message
// in replay time followed by a clock-sync message in our local time code (if we are idle).
// The connected server will send clock sync as usual in live mode.
for (auto& client : m_clients) {
// Clear the last-sent message times so that we send a new message stream starting now.
client.m_lastStateSent = { 0, 0 };
client.m_lastClockSent = { 0, 0 };
std::shared_ptr<StreamPacket> packet;
Status status = client.m_writer->GetCurrentPacket(packet);
if (status != OKAY) {
m_error = "Storage_Module_Server::doStopReplay(): Error getting current packet: " + ErrorMessage(status);
return;
}
MessageEvent message(*packet, nowInReplay, 0, END_OF_REPLAY, "");
if (message.GetConstructorStatus() != OKAY) {
m_error = "Storage_Module_Server::doStopReplay(): Error constructing MessageReplayStopped: " + ErrorMessage(message.GetConstructorStatus());
return;
}
if (CurrentMode() == Storage_Module_Server::Mode::Idle) {
// The clock-sync message is sent with a current time code.
Time nowInIdle;
status = m_timer->GetCoreTime(nowInIdle);
if (status != OKAY) {
m_error = "Storage_Module_Server::doStopReplay(): Error getting live time: " + ErrorMessage(status);
return;
}
MessageEvent message2(*packet, nowInIdle, 0, CLOCK_SYNC, "");
if (message2.GetConstructorStatus() != OKAY) {
m_error = "Storage_Module_Server::doStopReplay(): Error constructing MessageClockSync: "
+ ErrorMessage(message.GetConstructorStatus());
return;
}
}
// Send the packet.
status = client.m_writer->Flush();
if (status != OKAY) {
// Client may have disconnected.