Debian Codegraph @

mgendr/Source/Main.cpp

raw
1
2 #include "Main.h"
3 #include "ControlComponent.h"
4 #include"protoString.h"
5 #include <stdarg.h> // for va_start, etc
6 #include "mgenVersion.h"
7
8 const char* MGENDR_VERSION = "0.1.3";
9
10 static MgenderApp* app_ptr = NULL;
11
12 int MgenderApp::DoMgenLogEvent(FILE*, const char* format, ...)
13 {
14 va_list args;
15 va_start(args, format);
16 char text[256];
17 text[255] = '\0';
18 int result = vsnprintf(text, 255, format, args);
19 va_end(args);
20 app_ptr->OnMgenLogEvent(text);
21 return result;
22 } // end MgenderApp::DoMgenLog()
23
24 MgenderApp::MgenderApp()
25 : mgen(GetTimerMgr(), GetSocketNotifier()),
26 probe_src_port(0), next_feedback_flow_id(PROBE_FLOW_ID + 1),
27 filter_feedback(true), dynamic_probe_addr(false),
28 active_chooser(nullptr), event_index(0)
29 {
30 probe_addr.ConvertFromString("127.0.0.1");
31 probe_addr.SetPort(0);
32 iface_name[0] = iface_name[255] = '\0';
33 app_ptr = this;
34 #ifdef JUCE_MAC
35 PopupMenu extraMenu;
36 extraMenu.addCommandItem(&cmd_manager, CMD_ABOUT_APP);
37 extraMenu.addItem(CMD_ABOUT_APP, String("About mgendr ..."));
38 MenuBarModel::setMacMainMenu(this, &extraMenu);
39 #endif // JUCE_MAC
40 setApplicationCommandManagerToWatch(&cmd_manager);
41 cmd_manager.registerAllCommandsForTarget(this);
42 prune_timer.SetListener(this, &MgenderApp::OnPruneTimeout);
43 }
44
45 MgenderApp::~MgenderApp()
46 {
47 report_table.Destroy();
48 }
49
50 bool MgenderApp::ProcessCommandLine()
51 {
52 StringArray argv = getCommandLineParameterArray();
53 unsigned int argc = argv.size();
54 // Group command line arguments into MgenApp or Mgen commands
55 // and their (if applicable) respective arguments
56 // Parse command line
57 int i = 0;
58 while (i < argc)
59 {
60 Mgen::CmdType cmdType = Mgen::GetCmdType(argv[i].toRawUTF8());
61 switch (cmdType)
62 {
63 case Mgen::CMD_INVALID:
64 {
65 #ifdef JUCE_MAC
66 if (0 == strcmp(argv[i].toRawUTF8(), "-NsXXX"))
67 {
68 // Skip baked-in command-line option by Xcode issued for MacOSX debugging
69 i += 2;
70 break;
71 }
72 #endif // JUCE_MAC
73 String warn = String("Invalid command-line command: \"") + argv[i] + String("\"");
74 #ifdef ANDROID
75 AlertWindow::showMessageBoxAsync(AlertWindow::WarningIcon, String("mgender"), warn);
76 #else
77 AlertWindow::showMessageBox(AlertWindow::WarningIcon, String("mgender"), warn);
78 #endif // if/else ANDROID
79 i++;
80 return false;
81 }
82 case Mgen::CMD_NOARG:
83 {
84 if (!mgen.OnCommand(mgen.GetCommandFromString(argv[i].toRawUTF8()), NULL))
85 {
86 String warn = String("Error invoking command: \"") + argv[i] + String("\"");
87 #ifdef ANDROID
88 AlertWindow::showMessageBoxAsync(AlertWindow::WarningIcon, String("mgender"), warn);
89 #else
90 AlertWindow::showMessageBox(AlertWindow::WarningIcon, String("mgender"), warn);
91 #endif // if/else ANDROID
92 return false;
93 }
94 i++;
95 break;
96 }
97 case Mgen::CMD_ARG:
98 {
99 if (argc <= (i + 1))
100 {
101 String warn = String("Mission command-line argument for command: \"") + argv[i] + String("\"");
102 #ifdef ANDROID
103 AlertWindow::showMessageBoxAsync(AlertWindow::WarningIcon, String("mgender"), warn);
104 #else
105 AlertWindow::showMessageBox(AlertWindow::WarningIcon, String("mgender"), warn);
106 #endif // if/else ANDROID
107 return false;
108 }
109 if (!mgen.OnCommand(mgen.GetCommandFromString(argv[i].toRawUTF8()), argv[i+1].toRawUTF8()))
110 {
111 String warn = String("Error invoking command: \"") + argv[i] + String(" ") + argv[i+1] + String("\"");
112 #ifdef ANDROID
113 AlertWindow::showMessageBoxAsync(AlertWindow::WarningIcon, String("mgender"), warn);
114 #else
115 AlertWindow::showMessageBox(AlertWindow::WarningIcon, String("mgender"), warn);
116 #endif // if/else ANDROID
117 return false;
118 }
119 i += 2;
120 break;
121 }
122 }
123 }
124 return true;
125 } // end MgenderApp::ProcessCommandLine()
126
127 void MgenderApp::getAllCommands(Array<CommandID>& cmds)
128 {
129 Array<CommandID> commands {CMD_ABOUT_APP, CMD_LOAD_SCRIPT, CMD_SET_LOG, CMD_FILTER_FEEDBACK, CMD_DYNAMIC_ADDR};
130 cmds.addArray(commands);
131 } // end MgenderApp::getAllCommands()
132
133 void MgenderApp::getCommandInfo(CommandID commandID, ApplicationCommandInfo& result)
134 {
135 char shortcut = '\0';
136 switch (commandID)
137 {
138 case CMD_ABOUT_APP:
139 result.setInfo ("About mgendr ...", "mgendr Application Information", "Menu", 0);
140 result.setTicked (false);
141 break;
142 case CMD_LOAD_SCRIPT:
143 shortcut = 'O';
144 result.setInfo ("Load Script ...", "Load MGEN script", "Menu", 0);
145 result.setTicked (false);
146 break;
147 case CMD_SET_LOG:
148 shortcut = 'S';
149 result.setInfo ("Set Logfile ...", "Set MGEN log file", "Menu", 0);
150 result.setTicked (false);
151 break;
152 case CMD_FILTER_FEEDBACK:
153 result.setInfo ("Filter feedback", "Filter out probe feedback flows in flow report display", "Menu", 0);
154 result.setTicked (filter_feedback);
155 break;
156 case CMD_DYNAMIC_ADDR:
157 result.setInfo ("Dynamic probe address", "Enable dynamic update of probe address based on feedback", "Menu", 0);
158 result.setTicked (dynamic_probe_addr);
159 default:
160 break;
161 }
162 #ifndef JUCE_ANDROID
163 if ('\0' != shortcut)
164 result.addDefaultKeypress(shortcut, ModifierKeys::commandModifier);
165 #endif // !JUCE_ANDROID
166
167 } // end MgenderApp::getCommandInfo()
168
169 bool MgenderApp::perform(const InvocationInfo& info)
170 {
171 switch (info.commandID)
172 {
173 case CMD_ABOUT_APP:
174 ShowAppInfo();
175 break;
176 case CMD_LOAD_SCRIPT:
177 // TBD - open load script file dialog
178 LoadScriptFile();
179 break;
180 case CMD_SET_LOG:
181 SetLogFile();
182 break;
183 case CMD_FILTER_FEEDBACK:
184 // toggle state
185 filter_feedback = filter_feedback ? false : true;
186 break;
187 case CMD_DYNAMIC_ADDR:
188 // toggle state
189 dynamic_probe_addr = dynamic_probe_addr ? false : true;
190 break;
191 default:
192 return false;
193 }
194 return true;
195 } // end MgenderApp::perform()
196
197 StringArray MgenderApp::getMenuBarNames()
198 {
199 return StringArray(String("File"), String("Options"), String("About"));
200 } // end MgenderApp::getMenuBarNames()
201
202 PopupMenu MgenderApp::getMenuForIndex(int menuIndex, const String &menuName)
203 {
204 PopupMenu menu;
205 switch (menuIndex)
206 {
207 /*case -1: // Mac OSX "extra" menu
208 menu.addCommandItem(&cmd_manager, CMD_ABOUT_APP);
209 break;*/
210 case 0: // "File" menu
211 menu.addCommandItem(&cmd_manager, CMD_LOAD_SCRIPT);
212 menu.addCommandItem(&cmd_manager, CMD_SET_LOG);
213 break;
214 case 1: // "Options" menu
215 menu.addCommandItem(&cmd_manager, CMD_FILTER_FEEDBACK);
216 menu.addCommandItem(&cmd_manager, CMD_DYNAMIC_ADDR);
217 break;
218 case 2: // "About" menu
219 menu.addCommandItem(&cmd_manager, CMD_ABOUT_APP);
220 break;
221 default:
222 break;
223 }
224 return menu;
225 } // end MgenderApp::getMenuForIndex()
226
227 void MgenderApp::menuItemSelected(int menuItemID, int menuIndex)
228 {
229 if ((-1 == menuIndex) && (CMD_ABOUT_APP == menuItemID))
230 {
231 ShowAppInfo();
232 }
233 }
234
235 void MgenderApp::ShowAppInfo()
236 {
237 String info = String("mgendr Message Generator\nVersion ") + String(MGENDR_VERSION) +
238 String("\n(MGEN version ") + String(MGEN_VERSION) + String(")\n") +
239 String("written by Brian Adamson\nU.S. Naval Research Laboratory\nJune 2018");
240 #ifdef ANDROID
241 AlertWindow::showMessageBoxAsync(AlertWindow::InfoIcon, String("mgendr"), info);
242 #else
243 AlertWindow::showMessageBox(AlertWindow::InfoIcon, String("mgendr"), info);
244 #endif // if/else ANDROID
245 } // end MgenderApp::ShowAppInfo()
246
247 void MgenderApp::LoadScriptFile()
248 {
249
250 FileChooser* fileChooser = new FileChooser(String("mgender"), File::getCurrentWorkingDirectory(), String("*"));
251 ASSERT(nullptr == active_chooser);
252 active_chooser = fileChooser;
253 int flags = FileBrowserComponent::openMode | FileBrowserComponent::canSelectFiles;
254 fileChooser->launchAsync(flags,
255 [this](const FileChooser& fc)
256 {
257 if (fc.getResults().size() > 0)
258 {
259 String path = fc.getResult().getFullPathName();
260 dispatcher.SuspendThread();
261 if (!mgen.ParseScript(path.toRawUTF8()))
262 {
263 String warn = String("Invalid MGEN script \"") + path + String("\"");
264 #ifdef ANDROID
265 AlertWindow::showMessageBoxAsync(AlertWindow::WarningIcon, String("mgender"), warn);
266 #else
267 AlertWindow::showMessageBox(AlertWindow::WarningIcon, String("mgender"), warn);
268 #endif // if/else ANDROID
269 }
270 dispatcher.ResumeThread();
271 }
272 delete &fc;
273 active_chooser = nullptr;
274 });
275 } // end MgenderApp::LoadScriptFile()
276
277 void MgenderApp::SetLogFile()
278 {
279
280 FileChooser* fileChooser = new FileChooser(String("mgender"), File::getCurrentWorkingDirectory(), String("*"));
281 ASSERT(nullptr == active_chooser);
282 active_chooser = fileChooser;
283 int flags = FileBrowserComponent::saveMode | FileBrowserComponent::canSelectFiles;
284 fileChooser->launchAsync(flags,
285 [this](const FileChooser& fc)
286 {
287 if (fc.getResults().size() > 0)
288 {
289 String path = fc.getResult().getFullPathName();
290 dispatcher.SuspendThread();
291 if (!mgen.OpenLog(path.toRawUTF8(), false, false))
292 {
293 String warn = String("Unable to create log \"") + path + String("\"");
294 #ifdef ANDROID
295 AlertWindow::showMessageBoxAsync(AlertWindow::WarningIcon, String("mgender"), warn);
296 #else
297 AlertWindow::showMessageBox(AlertWindow::WarningIcon, String("mgender"), warn);
298 #endif // if/else ANDROID
299 }
300 dispatcher.ResumeThread();
301 }
302 delete &fc;
303 active_chooser = nullptr;
304 });
305 } // end MgenderApp::SetLogFile()
306
307 void MgenderApp::initialise(const String& commandLine)
308 {
309 // This method is where you should put your application's initialisation code ...
310 dispatcher.StartThread();
311 ctrl_window = new ControlComponent(*this);
312 main_window.reset(new MainWindow(getApplicationName(), ctrl_window));
313 main_window->addKeyListener(cmd_manager.getKeyMappings());
314 report_flow_count = 0;
315 dispatcher.SuspendThread();
316 //mgen.SetLogFunction(DoMgenLogEvent);
317 //mgen.SetLogFile(stdout);
318 mgen.SetController(this);
319 mgen.SetComputeAnalytics(true);
320 mgen.SetAnalyticWindow(5.0);
321 ProcessCommandLine();
322 mgen.Start();
323 // We "start probing" (and immediately stop it) so an
324 // ephemeral port is established as the probe source port
325 ProtoAddress addr;
326 addr.ConvertFromString("127.0.0.1");
327 addr.SetPort(8001);
328 StartProbing(addr, "periodic", 1.0, 512, NULL);
329 StopProbing();
330 SetProbeAddress(addr, mgen.GetDefaultMulticastInterface()); // 8001 is our default probing port (TBD - make configurable)
331 ctrl_window->OnUpdateProbeAddress();
332 prune_timer.SetInterval(5.0);
333 prune_timer.SetRepeat(-1.0);
334 dispatcher.GetDispatcher().ActivateTimer(prune_timer);
335 dispatcher.ResumeThread();
336
337 } // end mgenderApp::initialise()
338
339 void MgenderApp::shutdown()
340 {
341 // Add your application's shutdown code here ...
342 if (nullptr != active_chooser)
343 {
344 delete active_chooser;
345 active_chooser = nullptr;
346 }
347 if (prune_timer.IsActive())
348 prune_timer.Deactivate();
349 mgen.Stop();
350 dispatcher.Stop();
351 #ifdef JUCE_MAC
352 MenuBarModel::setMacMainMenu(nullptr);
353 #endif // JUCE_MAC
354 main_window = nullptr; // (deletes our window)
355 } // end MgenderApp::shutdown()
356
357 bool MgenderApp::SetProbeAddress(const ProtoAddress& probeAddr, const char* ifaceName)
358 {
359 // Also joins multicast address if applicable
360 char eventText[256];
361 UINT16 thePort = probeAddr.GetPort();
362 UINT16 probePort = probe_addr.GetPort();
363 if (thePort != probePort)
364 {
365 if (0 != probePort)
366 {
367 // Stop listening on old port
368 sprintf(eventText, "ignore udp %hu", probePort);
369 DrecEvent event;
370 event.InitFromString(eventText);
371 dispatcher.SuspendThread();
372 mgen.ProcessDrecEvent(event);
373 dispatcher.ResumeThread();
374 probePort = 0;
375 }
376 if (0 != thePort)
377 {
378 // Try to listen on new port
379 sprintf(eventText, "listen udp %hu", thePort);
380 DrecEvent event;
381 event.InitFromString(eventText);
382 dispatcher.SuspendThread();
383 bool result = mgen.ProcessDrecEvent(event);
384 dispatcher.ResumeThread();
385 if (result)
386 {
387 probePort = thePort;
388 }
389 else
390 {
391 PLOG(PL_ERROR, "MgendrApp::SetProbeAddress() error: listen failed\n");
392 return false;
393 }
394 }
395 }
396 // If mcast_addr or iface_name has changed leave and rejoin
397 if (!probeAddr.HostIsEqual(probe_addr) ||
398 ((NULL != ifaceName) && (0 != strcmp(ifaceName, iface_name))) ||
399 ((NULL == ifaceName) && ('\0' != iface_name[0])))
400 {
401 if (probe_addr.IsMulticast())
402 {
403 // Leave the probe group (note this could conflict with an MGEN scripted membership)
404 if ('\0' != iface_name[0])
405 sprintf(eventText, "leave %s port %hu interface %s", probe_addr.GetHostString(), probe_addr.GetPort(), iface_name);
406 else
407 sprintf(eventText, "leave %s port %hu", probe_addr.GetHostString(), probe_addr.GetPort());
408 DrecEvent drecEvent;
409 drecEvent.InitFromString(eventText);
410 if (!mgen.ProcessDrecEvent(drecEvent))
411 PLOG(PL_WARN, "MgendrApp::SetProbeAddress() warning: Multicast leave failure?!\n");
412 }
413
414 if (probeAddr.IsMulticast())
415 {
416 if (NULL != ifaceName)
417 sprintf(eventText, "join %s port %hu interface %s", probeAddr.GetHostString(), probeAddr.GetPort(), ifaceName);
418 else
419 sprintf(eventText, "join %s port %hu", probeAddr.GetHostString(), probeAddr.GetPort());
420 DrecEvent drecEvent;
421 drecEvent.InitFromString(eventText);
422 if (!mgen.ProcessDrecEvent(drecEvent))
423 {
424 PLOG(PL_ERROR, "MgendrApp::SetProbeAddress error: unable to join multicast group!\n");
425 return false;
426 }
427 }
428 }
429 // Update probe_addr/port and iface_name in any case since one of them has changed
430 probe_addr = probeAddr;
431 if (NULL == ifaceName)
432 iface_name[0] = '\0';
433 else
434 strncpy(iface_name, ifaceName, 255);
435 return true; // probing was disabled
436 } // end MgenderApp::SetProbeAddress()
437
438 bool MgenderApp::StartProbing(const ProtoAddress& probeAddr,
439 const char* pattern,
440 double rate,
441 unsigned int size,
442 const char* ifaceName)
443 {
444 dispatcher.SuspendThread();
445 MgenFlow* probeFlow = mgen.FindFlowById(PROBE_FLOW_ID);
446 const char* cmd = (NULL != probeFlow) ? "mod" : "on";
447 char eventString[256];
448 if (probeAddr.IsMulticast())
449 {
450 if (NULL != ifaceName)
451 sprintf(eventString, "%s %u udp dst %s/%hu %s [%lf %u] ttl 255 interface %s",
452 cmd, PROBE_FLOW_ID, probeAddr.GetHostString(), probeAddr.GetPort(),
453 pattern, rate, size, ifaceName);
454 else
455 sprintf(eventString, "%s %u udp dst %s/%hu %s [%lf %u] ttl 255",
456 cmd, PROBE_FLOW_ID, probeAddr.GetHostString(), probeAddr.GetPort(),
457 pattern, rate, size);
458 }
459 else
460 {
461 sprintf(eventString, "%s %u udp dst %s/%hu %s [%lf %u]",
462 cmd, PROBE_FLOW_ID, probeAddr.GetHostString(), probeAddr.GetPort(),
463 pattern, rate, size);
464 }
465 MgenEvent event;
466 event.InitFromString(eventString);
467 bool result = mgen.ProcessMgenEvent(event);
468 if (result)
469 {
470 if (NULL == probeFlow)
471 probeFlow = mgen.FindFlowById(PROBE_FLOW_ID);
472 ASSERT(NULL != probeFlow);
473 probeFlow->Resume();
474 UINT16 srcPort = probeFlow->GetSrcPort();
475 // Listen on the probe_src_port for unicast responses to probing
476 sprintf(eventString, "listen udp %hu", srcPort);
477 DrecEvent drecEvent;
478 drecEvent.InitFromString(eventString);
479 if (mgen.ProcessDrecEvent(drecEvent))
480 probe_src_port = srcPort;
481 else
482 StopProbing();
483 }
484 dispatcher.ResumeThread();
485 return result;
486 } // end MgenderApp::StartProbing()
487
488 void MgenderApp::StopProbing()
489 {
490 dispatcher.SuspendThread();
491 MgenFlow* flow = mgen.FindFlowById(PROBE_FLOW_ID);
492 if (NULL != flow) flow->Suspend();
493 if (0 != probe_src_port)
494 {
495 char eventText[64];
496 sprintf(eventText, "ignore udp %hu", probe_src_port);
497 DrecEvent drecEvent;
498 drecEvent.InitFromString(eventText);
499 mgen.ProcessDrecEvent(drecEvent);
500 probe_src_port = 0;
501 }
502 dispatcher.ResumeThread();
503 } // end MgenderApp::StopProbing()
504
505 void MgenderApp::OnMgenLogEvent(const char* text)
506 {
507 size_t index = 0;
508 size_t len = strlen(text);
509 while (index < len)
510 {
511 size_t space = 511 - event_index;
512 size_t nbytes = (space > len) ? len : space;
513 const char* ptr = strchr(text+index, '\n');
514 if (NULL != ptr)
515 {
516 size_t offset = (ptr - text) - index + 1;
517 if (offset < nbytes)
518 nbytes = offset;
519 }
520 strncpy(event_buffer+event_index, text+index, nbytes);
521 space -= nbytes;
522 index += nbytes;
523 event_index += nbytes;
524 if ((NULL != ptr) || (0 == space))
525 {
526 if ((NULL != ptr) && (0 == space))
527 index = ptr - text + 1; // advance to next line
528 // Process and reset our 'event_buffer'
529 //ProtoTokenator tk(event_buffer);
530 //const char* eventType = tk.GetNextItem(); // skip first field (timestamp)
531 /*eventType = tk.GetNextItem();
532 if ((NULL != eventType) && (0 == strcmp(eventType, "REPORT")))
533 {
534 MessageManagerLock mml;
535 if (mml.lockWasGained())
536 ctrl_window->AppendReportContent(event_buffer);
537 }*/
538 event_index = 0;
539 }
540 }
541 } // end MgenderApp::OnMgenLogEvent()
542
543
544 MgenderApp::Report::Report(Protocol theProtocol,
545 const ProtoAddress& srcAddr,
546 const ProtoAddress& dstAddr,
547 UINT32 flowId,
548 const ProtoAddress* reporterAddr)
549 : feedback_id(0)
550 {
551 report_keysize = BuildKey(report_key, MAX_KEY, theProtocol, srcAddr, dstAddr, flowId, reporterAddr);
552 protocol = theProtocol;
553 src_addr = srcAddr;
554 dst_addr = dstAddr;
555 flow_id = flowId;
556 if (NULL != reporterAddr)
557 reporter_addr = *reporterAddr;
558 else
559 reporter_addr.Invalidate();
560 }
561
562 MgenderApp::Report::~Report()
563 {
564 }
565
566 unsigned int MgenderApp::Report::BuildKey(char* buffer,
567 unsigned int buflen,
568 Protocol theProtocol,
569 const ProtoAddress& srcAddr,
570 const ProtoAddress& dstAddr,
571 UINT32 flowId,
572 const ProtoAddress* reporterAddr)
573 {
574 // TBD - we could be more efficient and encode the address type
575 // info into the "report_key" and pull these from the key
576 // instead of keeping separate member variables
577 if (buflen < MAX_KEY)
578 {
579 PLOG(PL_ERROR, "MgenderApp::Report::BuildKey() error: 'buffer' must be at least %u bytes\n", MAX_KEY);
580 return 0;
581 }
582 unsigned index = 0;
583 buffer[index++] = (char)theProtocol;
584 memcpy(buffer+index, srcAddr.GetRawHostAddress(), srcAddr.GetLength());
585 index += srcAddr.GetLength();
586 UINT16 p = srcAddr.GetPort();
587 memcpy(buffer+index, &p, 2);
588 index += 2;
589 memcpy(buffer+index, dstAddr.GetRawHostAddress(), dstAddr.GetLength());
590 index += dstAddr.GetLength();
591 p = dstAddr.GetPort();
592 memcpy(buffer+index, &p, 2);
593 index += 2;
594 memcpy(buffer+index, &flowId, 4);
595 index += 4;
596 if (NULL != reporterAddr)
597 {
598 memcpy(buffer+index, reporterAddr->GetRawHostAddress(), reporterAddr->GetLength());
599 index += reporterAddr->GetLength();
600 p = reporterAddr->GetPort();
601 memcpy(buffer+index, &p, 2);
602 index += 2;
603 }
604 return (index << 3);
605 } // end MgenderApp::Report::BuildKey()
606
607 bool MgenderApp::Report::Update(const ProtoTime& theTime,
608 const MgenAnalytic::Report& report,
609 const ProtoTime& sentTime)
610 {
611 if (reporter_addr.IsValid())
612 {
613 // Make sure it's not a duplicate of the current report
614 // (and not an older one)
615
616 ProtoTime newEnd = sentTime - report.GetWindowOffset();
617 ProtoTime newStart = newEnd - report.GetWindowSize();
618 ProtoTime oldEnd = report_time - report_offset;
619 ProtoTime oldStart = oldEnd - report_window;
620 if (newEnd < oldStart)
621 return false; // an older report
622 if (newStart < oldEnd)
623 {
624 double overlap = oldEnd - newStart;
625 if (overlap > 0.5*report_window)
626 return false; // it's redundant (TBD - could check for matching values?)
627 }
628 }
629 rate_ave = report.GetRateAve();
630 loss_fraction = report.GetLossFraction();
631 late_ave = report.GetLatencyAve();
632 late_min = report.GetLatencyMin();
633 late_max = report.GetLatencyMax();
634 report_window = report.GetWindowSize();
635 report_offset = report.GetWindowOffset();
636 report_time = sentTime;
637 update_time = theTime;
638 return true;
639
640 } // end MgenderApp::Report::Update()
641
642 MgenderApp::Report* MgenderApp::ReportTable::FindReport(Protocol theProtocol,
643 const ProtoAddress& srcAddr,
644 const ProtoAddress& dstAddr,
645 UINT32 flowId,
646 const ProtoAddress* reporterAddr)
647 {
648 char key[Report::MAX_KEY];
649 unsigned int keysize =
650 Report::BuildKey(key, Report::MAX_KEY, theProtocol, srcAddr, dstAddr, flowId, reporterAddr);
651 return Find(key, keysize);
652 } // end MgenderApp::ReportTable::FindReport()
653
654
655 // MgenController method implementations
656 void MgenderApp::OnUpdateReport(const ProtoTime& theTime,
657 const MgenAnalytic::Report& localReport)
658 {
659 ProtoAddress srcAddr, dstAddr;
660 localReport.GetSrcAddr(srcAddr);
661 localReport.GetDstAddr(dstAddr);
662 Report* report = report_table.FindReport(localReport.GetProtocol(),
663 srcAddr, dstAddr,
664 localReport.GetFlowId());
665 if (NULL == report)
666 {
667 report = new Report(localReport.GetProtocol(),
668 srcAddr, dstAddr,
669 localReport.GetFlowId());
670 if (NULL == report)
671 {
672 PLOG(PL_ERROR,"MgenderApp::OnUpdateReport() new Report error: %s\n", GetErrorString());
673 return;
674 }
675 if (!report_table.Insert(*report))
676 {
677 PLOG(PL_ERROR,"MgenderApp::OnUpdateReport() error: unable to insert new flow report\n");
678 delete report;
679 return;
680 }
681 if (!report_list.Append(*report))
682 {
683 PLOG(PL_ERROR,"MgenderApp::OnUpdateReport() error: unable to insert new flow report\n");
684 report_table.Remove(*report);
685 delete report;
686 return;
687 }
688 if (report_flow_count >= MAX_REPORT_FLOWS)
689 {
690 Report* oldest = report_list.GetHead();
691 ASSERT(NULL != oldest);
692 RemoveFlowReport(*oldest);
693 delete oldest;
694 }
695 else
696 {
697 report_flow_count++;
698 }
699 if (PROBE_FLOW_ID == report->GetFlowId())
700 {
701 // This is a new probing flow from a remote, so set up
702 // a reciprocal feedback flow.
703 char eventString[256];
704 UINT32 feedbackId = next_feedback_flow_id;
705 const ProtoAddress& reportSrcAddr = report->GetSrcAddr();
706 // Send 5 feedback message per averaging window for robust feedback
707 double feedbackRate = 5.0 / (mgen.GetAnalyticWindow());
708 sprintf(eventString, "on %u udp dst %s/%hu periodic [%lf 96] feedback",
709 feedbackId, reportSrcAddr.GetHostString(),
710 reportSrcAddr.GetPort(), feedbackRate);
711 MgenEvent event;
712 event.InitFromString(eventString);
713 dispatcher.SuspendThread();
714 if (mgen.ProcessMgenEvent(event))
715 {
716 // TBD - we could keep trying until we find a flow id that works?
717 report->SetFeedbackId(next_feedback_flow_id++);
718 }
719 else
720 {
721 PLOG(PL_ERROR, "MgenderApp::OnUpdateReport() error: unable to initiate feedback\n");
722 }
723 dispatcher.ResumeThread();
724 }
725 }
726 if (report->Update(theTime, localReport, theTime))
727 {
728 report_list.Remove(*report);
729 report_list.Append(*report);
730 if ((probe_src_port != report->GetDstAddr().GetPort()) || (!filter_feedback)) // filter out feedback flows
731 AppendReportContent(*report, theTime);
732 }
733 PruneFlowReports(theTime);
734 } // end MgenderApp::OnUpdateReport()
735
736 void MgenderApp::OnRecvReport(const ProtoTime& theTime,
737 const MgenAnalytic::Report& recvReport,
738 const ProtoAddress& senderAddr,
739 const ProtoTime& sentTime)
740 {
741 ProtoAddress srcAddr, dstAddr;
742 recvReport.GetSrcAddr(srcAddr);
743 recvReport.GetDstAddr(dstAddr);
744 Report* report = report_table.FindReport(recvReport.GetProtocol(),
745 srcAddr, dstAddr,
746 recvReport.GetFlowId(),
747 &senderAddr);
748 if (NULL == report)
749 {
750 report = new Report(recvReport.GetProtocol(),
751 srcAddr, dstAddr,
752 recvReport.GetFlowId(),
753 &senderAddr);
754 if (NULL == report)
755 {
756 PLOG(PL_ERROR,"MgenderApp::OnRecvReport() new Report error: %s\n", GetErrorString());
757 return;
758 }
759 if (!report_table.Insert(*report))
760 {
761 PLOG(PL_ERROR,"MgenderApp::OnRecvReport() error: unable to insert new flow report\n");
762 delete report;
763 return;
764 }
765 if (!report_list.Append(*report))
766 {
767 PLOG(PL_ERROR,"MgenderApp::OnRecvReport() error: unable to insert new flow report\n");
768 report_table.Remove(*report);
769 delete report;
770 return;
771 }
772 if (report_flow_count >= MAX_REPORT_FLOWS)
773 {
774 Report* oldest = report_list.GetHead();
775 ASSERT(NULL != oldest);
776 RemoveFlowReport(*oldest);
777 delete oldest;
778 }
779 else
780 {
781 report_flow_count++;
782 }
783 }
784 if (report->Update(theTime, recvReport, sentTime))
785 {
786 report_list.Remove(*report);
787 report_list.Append(*report);
788 AppendReportContent(*report, theTime);
789 }
790
791 if (dynamic_probe_addr &&
792 probe_addr.IsUnicast() &&
793 report->GetDstAddr().IsEqual(probe_addr) &&
794 !report->GetReporterAddr().IsEqual(probe_addr))
795 {
796 // The probe recipient may have changed it's address?
797 ProtoAddress probeAddr = report->GetReporterAddr();
798 probeAddr.SetPort(probe_addr.GetPort());
799 SetProbeAddress(probeAddr, GetInterface());
800 ctrl_window->OnUpdateProbeAddress();
801 }
802
803 PruneFlowReports(theTime);
804 } // end MgenderApp::OnRecvReport()
805
806
807 void MgenderApp::OnPruneTimeout(ProtoTimer& /*theTimer*/)
808 {
809 ProtoTime currentTime;
810 currentTime.GetCurrentTime();
811 PruneFlowReports(currentTime);
812 }
813
814 void MgenderApp::PruneFlowReports(const ProtoTime& theTime)
815 {
816 // Oldest flows are at head of report list
817 double ageMax = 10.0*mgen.GetAnalyticWindow();
818 ReportList::Iterator iterator(report_list);
819 Report* nextReport;
820 while (NULL != (nextReport = iterator.GetNextItem()))
821 {
822 double age = theTime - nextReport->GetUpdateTime();
823 if (age > ageMax)
824 {
825 RemoveFlowReport(*nextReport);
826 mgen.RemoveAnalytic(nextReport->GetProtocol(),
827 nextReport->GetSrcAddr(),
828 nextReport->GetDstAddr(),
829 nextReport->GetFlowId());
830 delete nextReport;
831 report_flow_count -= 1;
832 }
833 }
834 } // end MgenderApp::PruneFlowReports()
835
836 void MgenderApp::RemoveFlowReport(Report& report)
837 {
838 // Remove from list and deactivate/remove feedback flow if applicable
839 report_list.Remove(report);
840 report_table.Remove(report);
841 if (0 != report.GetFeedbackId())
842 {
843 MgenFlow* feedbackFlow = mgen.FindFlowById(report.GetFeedbackId());
844 if (NULL != feedbackFlow)
845 {
846 feedbackFlow->StopFlow();
847 mgen.RemoveFlow(*feedbackFlow);
848 delete feedbackFlow;
849 }
850 // Conserve feedback flow id a little if possible
851 if (report.GetFeedbackId() == (next_feedback_flow_id - 1))
852 next_feedback_flow_id -= 1;
853 report.SetFeedbackId(0);
854 }
855 } // end MgenderApp::RemoveFlowReport()
856
857
858 void MgenderApp::AppendReportContent(Report& report, const ProtoTime& theTime)
859 {
860 int64 msec = theTime.sec()*1.0e+03 + theTime.usec()*1.0e-03;
861 Time juceTime(msec);
862 if (report_lines.size() >= MAX_REPORT_LINES)
863 report_lines.remove(0);
864 // Append line to report_lines string array
865 String line = juceTime.toString(false, true, true, true);
866 line += String(".") + String::formatted("%06u", theTime.usec());
867 switch(report.GetProtocol())
868 {
869 case UDP:
870 line += String(" UDP:");
871 break;
872 case TCP:
873 line += String(" TCP:");
874 break;
875 default:
876 line += String(" ???:");
877 break;
878 }
879 line += String(report.GetSrcAddr().GetHostString()) + String("/");
880 line += String(report.GetSrcAddr().GetPort()) + String("->");
881 line += String(report.GetDstAddr().GetHostString()) + String("/");
882 line += String(report.GetDstAddr().GetPort()) + String(",");
883 line += String(report.GetFlowId()) + String(" ");
884 line += String("rate>") + String(report.GetRateAve()*8.0e-03) + String(" kbps loss>");
885 line += String(report.GetLossFraction()) + String(" latency ave>");
886 line += String(report.GetLatencyAve()) + String(" min>");
887 line += String(report.GetLatencyMin()) + String(" max>");
888 line += String(report.GetLatencyMax()) + String(" sec");
889 if (report.GetReporterAddr().IsValid())
890 line += String(" reporter>") + String(report.GetReporterAddr().GetHostString());
891 report_lines.add(line);
892 //const MessageManagerLock mml(Thread::getCurrentThread());;
893 //if (mml.lockWasGained())
894 // ctrl_window->SetReportContentDirect(report_lines.joinIntoString(StringRef("\n\n")));
895 // This invokes the ControlComponent AsyncUpdate for thread safety
896 ctrl_window->SetReportContent(report_lines.joinIntoString(StringRef("\n\n")));
897
898 } // end MgenderApp::AppendReportContent()
899
900 ///////////////////////////////////////////////////
901 // JUCE "boiler plate" stuff we should embed into
902 // a "juceProtoApp" base class
903
904 MgenderApp::MainWindow::MainWindow(String name, ControlComponent* theControl)
905 : DocumentWindow(name,
906 Desktop:: getInstance()
907 .getDefaultLookAndFeel()
908 .findColour(ResizableWindow::backgroundColourId),
909 DocumentWindow::allButtons)
910 {
911 setUsingNativeTitleBar(true);
912 setResizable(true, false);
913 #ifdef LINUX
914 Image mgenIcon = ImageCache::getFromMemory(ControlComponent::mgenLogo_png,
915 ControlComponent::mgenLogo_pngSize);
916 setIcon(mgenIcon);
917 ComponentPeer* peer = getPeer();
918 if (NULL != peer)
919 peer->setIcon(mgenIcon);
920 #endif // LINUX
921 centreWithSize(getWidth(), getHeight());
922 setContentOwned(theControl, true);
923 setVisible (true);
924 #ifdef ANDROID
925 setFullScreen(true);
926 #endif // ANDROID
927 }
928
929 //==============================================================================
930 // This macro generates the main() routine that launches the app.
931 START_JUCE_APPLICATION(MgenderApp)