-
Notifications
You must be signed in to change notification settings - Fork 52
/
navmerge.cc
287 lines (234 loc) · 8.64 KB
/
navmerge.cc
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
#include "sclasses.hh"
#include <map>
#include "navmon.hh"
#include "navmon.pb.h"
#include <thread>
#include <signal.h>
#include "fmt/format.h"
#include "fmt/printf.h"
#include "nmmsender.hh"
#include "CLI/CLI.hpp"
#include "version.hh"
using namespace std;
static char program[]="navmerge";
/* ubxtool/rtcmtool/septool deliver data to one of several `navrecv` instances
This means we need a 'merge' tool.
The merge tool should be able to stream data from multiple `navnexus` instances
(that correspond to the `navrecv` instances)
Currently, `navnexus` is really simple - it will send you a feed from x hours back, where
you don't get to pick x.
The simplest navmerge implementation does nothing but connect to a few navnexus instances
and it mixes them together.
Every message "should" only appear on one of the upstreams, but you never know.
On initial connection, the different navnexuses may start up from a different time, currently.
Let us state that This Should Not Happen.
On initial connect, a navnexus might take dozens of seconds before it starts coughing up data.
Initial goal for navmerge is: only make sure realtime works.
Every upstream has a thread that loops trying to connect
If a new message comes in, it is stored in a shared data structure
If a new connect is made, set a "don't send" marker for a whole minute
There is a sender thread that periodically polls this data structure
Any data that is older than the previous high-water mark gets sent out & removed from structure
However, transmission stops 10 seconds before realtime
If a "don't send" marker is set, we don't do a thing
*/
multimap<pair<uint64_t, uint64_t>, string> g_buffer;
std::mutex g_mut;
// navmerge can also dedup its output, we keep track of recent messages here
// this means each Galileo message will only get set once
map<tuple<uint32_t, std::string, uint32_t, std::string, int16_t>, time_t> g_seen;
bool g_inavdedup{false};
/* Goal: do a number of TCP operations that have a combined timeout.
maybe some helper:
auto deadline = xSecondsFromNow(1.5);
SConnectWithDeadline(sock, addr, deadline);
resp=SReadWithDeadline(sock, 2, deadline);
..
resp2=SReadWithDeadline(sock, num, deadline);
//
// not getting 'num' bytes -> error
// exceeding timeout before getting 'num' bytes -> error
*/
static auto xSecondsFromNow(double seconds)
{
auto now = chrono::steady_clock::now();
now += std::chrono::milliseconds((unsigned int)(seconds*1000));
return now;
}
static int msecLeft(const std::chrono::steady_clock::time_point& deadline)
{
auto now = chrono::steady_clock::now();
return std::chrono::duration_cast<std::chrono::milliseconds>(deadline - now).count();
}
string SReadWithDeadline(int sock, int num, const std::chrono::steady_clock::time_point& deadline)
{
string ret;
char buffer[1024];
std::string::size_type leftToRead=num;
for(; leftToRead;) {
auto now = chrono::steady_clock::now();
auto msecs = chrono::duration_cast<chrono::milliseconds>(deadline-now);
if(msecs.count() <= 0)
throw std::runtime_error("Timeout");
double toseconds = msecs.count()/1000.0;
int res = waitForRWData(sock, true, &toseconds); // 0 = timeout, 1 = data, -1 error
if(res == 0)
throw std::runtime_error("Timeout");
if(res < 0)
throw std::runtime_error("Reading with deadline: "+string(strerror(errno)));
auto chunk = sizeof(buffer) < leftToRead ? sizeof(buffer) : leftToRead;
res = read(sock, buffer, chunk);
if(res < 0)
throw std::runtime_error(fmt::sprintf("Read from socket: %s", strerror(errno)));
if(!res)
throw std::runtime_error(fmt::sprintf("Unexpected EOF"));
ret.append(buffer, res);
leftToRead -= res;
}
return ret;
}
void recvSession(ComboAddress upstream)
{
for(;;) {
try {
Socket sock(upstream.sin4.sin_family, SOCK_STREAM);
cerr<<"Connecting to "<< upstream.toStringWithPort()<<" to source data..";
SConnectWithTimeout(sock, upstream, 5);
cerr<<" done"<<endl;
for(int count=0;;++count) {
auto deadline = xSecondsFromNow(600); //
string part=SReadWithDeadline(sock, 4, deadline);
if(part.empty()) {
cerr<<"EOF from "<<upstream.toStringWithPort()<<endl;
break;
}
if(part != "bert") {
cerr << "Message "<<count<<", wrong magic from "<<upstream.toStringWithPort()<<": "<<makeHexDump(part)<<endl;
break;
}
if(!count)
cerr<<"Receiving messages from "<<upstream.toStringWithPort()<<endl;
string out=part;
part = SReadWithDeadline(sock, 2, deadline);
out += part;
uint16_t len;
memcpy(&len, part.c_str(), 2);
len = htons(len);
part = SReadWithDeadline(sock, len, deadline); // XXXXX ???
if(part.size() != len) {
cerr<<"Mismatch, "<<part.size()<<", len "<<len<<endl;
// XX AND THEN WHAT??
}
out += part;
// if(msecLeft(deadline)/1000.0 < 119)
// cerr<<"Done with "<<msecLeft(deadline)/1000.0<<" seconds left\n";
NavMonMessage nmm;
nmm.ParseFromString(part);
if(g_inavdedup) {
if(nmm.type() == NavMonMessage::GalileoInavType) {
std::lock_guard<std::mutex> mut(g_mut);
decltype(g_seen)::key_type tup(nmm.gi().gnsssv(), nmm.gi().contents(), nmm.gi().sigid(), nmm.gi().reserved1(),nmm.gi().has_ssp() ? nmm.gi().ssp() : -1);
if(!g_seen.count(tup))
g_buffer.insert({{nmm.localutcseconds(), nmm.localutcnanoseconds()}, part});
g_seen[tup]=time(0);
}
}
else {
std::lock_guard<std::mutex> mut(g_mut);
g_buffer.insert({{nmm.localutcseconds(), nmm.localutcnanoseconds()}, part});
}
}
}
catch(std::exception& e) {
cerr<<"Error in receiving thread: "<<e.what()<<endl;
sleep(1);
}
}
cerr<<"Thread for "<<upstream.toStringWithPort()<< " exiting"<<endl;
}
static void cleanFilter()
{
time_t lim = time(0) - 60;
std::lock_guard<std::mutex> mut(g_mut);
for(auto iter = g_seen.begin(); iter!= g_seen.end() ;) {
if(iter->second < lim)
iter = g_seen.erase(iter);
else
++iter;
}
}
int main(int argc, char** argv)
{
GOOGLE_PROTOBUF_VERIFY_VERSION;
vector<string> destinations;
vector<string> sources;
vector<string> listeners;
bool doVERSION{false}, doSTDOUT{false};
CLI::App app(program);
app.add_option("--source", sources, "Connect to these IP address:port to source protobuf");
app.add_option("--destination,-d", destinations, "Send output to this IPv4/v6 address");
app.add_option("--listener,-l", listeners, "Make data available on this IPv4/v6 address");
app.add_flag("--inavdedup", g_inavdedup, "Only pass on Galileo I/NAV, and dedeup");
app.add_flag("--version", doVERSION, "show program version and copyright");
app.add_flag("--stdout", doSTDOUT, "Emit output to stdout");
CLI11_PARSE(app, argc, argv);
if(doVERSION) {
showVersion(program, g_gitHash);
exit(0);
}
if(sources.empty()) {
cerr<< "No sources defined. Exiting."<<endl;
exit(0);
}
signal(SIGPIPE, SIG_IGN);
NMMSender ns;
ns.d_debug = true;
for(const auto& s : destinations) {
auto res=resolveName(s, true, true);
if(res.empty()) {
cerr<<"Unable to resolve '"<<s<<"' as destination for data, exiting"<<endl;
exit(EXIT_FAILURE);
}
ns.addDestination(s); // ComboAddress(s, 29603));
}
for(const auto& l : listeners) {
ComboAddress ca(l, 29604);
cerr<<"Adding listener on "<<ca.toStringWithPort()<<endl;
ns.addListener(l); // ComboAddress(s, 29603));
}
if(doSTDOUT)
ns.addDestination(1);
for(const auto& s : sources) {
ComboAddress oneaddr(s, 29601);
std::thread one(recvSession, oneaddr);
one.detach();
}
ns.launch();
time_t start=time(0);
int counter=0;
for(;;) {
usleep(500000);
vector<string> tosend;
{
std::lock_guard<std::mutex> mut(g_mut);
time_t now = time(0);
if(now - start < 30) { // was 30
cerr<<"Have "<<g_buffer.size()<<" messages"<<endl;
continue;
}
for(auto iter = g_buffer.begin(); iter != g_buffer.end(); ) {
if(iter->first.first > (uint64_t)now - 5)
break;
tosend.push_back(iter->second);
iter = g_buffer.erase(iter);
}
}
// cerr<<"Have "<<tosend.size()<<" messages to send, "<<g_buffer.size()<<" left in queue"<<endl;
std::string buf;
for(const auto& m : tosend) {
if(!((counter++) % 32768))
cleanFilter();
ns.emitNMM(m);
}
}
}