ridelogic_avlsd 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. #!/usr/bin/perl -Tw
  2. #
  3. # Copyright (c) 2019 Clementine Computing LLC.
  4. #
  5. # This file is part of PopuFare.
  6. #
  7. # PopuFare is free software: you can redistribute it and/or modify
  8. # it under the terms of the GNU Affero General Public License as published by
  9. # the Free Software Foundation, either version 3 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # PopuFare is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU Affero General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU Affero General Public License
  18. # along with PopuFare. If not, see <https://www.gnu.org/licenses/>.
  19. #
  20. require 5.002;
  21. use strict;
  22. use Socket;
  23. use Switch;
  24. use Carp;
  25. use DBI;
  26. use FileHandle;
  27. use Fcntl;
  28. use Compress::Zlib;
  29. use Getopt::Long qw(:config no_ignore_case);
  30. use POSIX;
  31. use RideLogic;
  32. my $database_path = 'DBI:mysql:busdb';
  33. my $database_user = '';
  34. my $database_pass = '';
  35. my $bind_ip = '127.0.0.1';
  36. my $bind_port = 2857;
  37. #--------------------------------------------------------------------------------------------------------------------
  38. my $DebugMode = 0;
  39. # This function only executes the passed code reference if the global variable $DebugMode is non-zero.
  40. # The reason for this is that any calculation (like a FooBar::ComplexObject->toString call) will not be
  41. # performed if we are not in debug mode, sort of like a very limited form of lazy evaluation.
  42. #
  43. sub ifdebug(&@)
  44. {
  45. my ($cmd) = @_;
  46. &$cmd() if($DebugMode);
  47. }
  48. sub StoreAvls
  49. {
  50. my $client_query = $_[0];
  51. chomp($client_query);
  52. my $dbh = DBI->connect($database_path, $database_user, $database_pass)
  53. or die "Couldn't connect to database: " . DBI->errstr;
  54. my $sth_avls = $dbh->prepare('INSERT INTO avls_data (equip_num, driver, paddle, route, trip, stop, chirp_time, latitude, longitude, heading, velocity) VALUES (?, ?, ?, ?, ?, ?, FROM_UNIXTIME(?), ?, ?, ?, ?)')
  55. or die "Couldn't prepare statement: " . $dbh->errstr;
  56. #store avls data
  57. $sth_avls->execute(split("\t", $client_query)) # Execute the query
  58. or die "Couldn't execute statement: " . $sth_avls->errstr;
  59. $sth_avls->finish;
  60. $dbh->disconnect;
  61. }
  62. sub handle_client()
  63. {
  64. close SERVER;
  65. CLIENT->autoflush(1);
  66. my $linebuffer;
  67. while($linebuffer = <CLIENT>)
  68. {
  69. StoreAvls($linebuffer);
  70. } #while data from client
  71. close CLIENT;
  72. }
  73. my $waitedpid = 0;
  74. my $sigreceived = 0;
  75. sub REAPER
  76. {
  77. while (($waitedpid = waitpid(-1, WNOHANG))>0) { }
  78. $SIG{CHLD} = \&REAPER; # loathe sysV
  79. $sigreceived = 1;
  80. }
  81. sub spawn
  82. {
  83. my $coderef = shift; #grab the first parameter
  84. unless (@_ == 0 && $coderef && ref($coderef) eq 'CODE') #verify that it consists of a non-null block of executable perl code
  85. {
  86. confess "usage: spawn CODEREF"; #complain if this is not the case
  87. }
  88. my $pid;
  89. if (!defined($pid = fork)) #attempt a fork, remembering the returned PID value
  90. {
  91. close CLIENT;
  92. return; #failed to fork, we'd better close the client
  93. }
  94. elsif ($pid) #If the returned process ID is non-zero, that indicates that we are the parent process
  95. {
  96. return; # i'm the parent
  97. }
  98. else #otherwise, if the returned process ID is 0, that means we're the child process
  99. {
  100. exit &$coderef(); #in which case, we want to execute the child handler that was passed in, and then
  101. #exit this (child) process when we've finished our conversation(s) with the
  102. #other (client) end of the socket.
  103. }
  104. }
  105. sub show_help_and_exit {
  106. print "usage:\n";
  107. print " [-i] interactive, do not daemonize\n";
  108. print " [-c cfg] use cfg as config file (default to " . $RideLogic::RIDELOGIC_DAEMON_CONF . ") \n";
  109. print " [-h] show help (this screen)\n";
  110. exit;
  111. }
  112. #----------------------------------------------------------------------
  113. #
  114. #----------------------------------------------------------------------
  115. my $daemonize = 1;
  116. my $interactive = 0;
  117. my $show_help = 0;
  118. my $cfg_file = $RideLogic::RIDELOGIC_DAEMON_CONF;
  119. GetOptions(
  120. 'i|interactive' => \$interactive,
  121. 'c|config=s' => \$cfg_file,
  122. 'h|help' => \$show_help );
  123. show_help_and_exit() if ($show_help);
  124. $daemonize=0 if ($interactive);
  125. #----------------------------------------------------------------------
  126. # Local network settings for Inter-Process communication.
  127. #----------------------------------------------------------------------
  128. my $proto = getprotobyname('tcp');
  129. my $addr = sockaddr_in( $bind_port ,inet_aton($bind_ip));;
  130. #----------------------------------------------------------------------
  131. my $max_retries = 10; #Maximum number of address-binding retries before we give up.
  132. my $retry_count = $max_retries; #number of retries left...
  133. my $retry_delay = 3; #number of seconds to wait between retries at binding to our designated IPC address
  134. my $got_network = 0; #flag to let us know that we can quit retrying once we have gotten a valid listening socket
  135. my %CFG_VAR;
  136. read_config($cfg_file, \%CFG_VAR) if ($cfg_file);
  137. my $logfile = ($CFG_VAR{"RIDELOGIC_DAEMON_LOG_DIR"} || $RideLogic::RIDELOGIC_DAEMON_LOG_DIR) . "/ridelogic_avlsd.log";
  138. my $pidfile = ($CFG_VAR{"RIDELOGIC_DAEMON_PID_DIR"} || $RideLogic::RIDELOGIC_DAEMON_PID_DIR) . "/ridelogic_avlsd.pid";
  139. daemonize($logfile, $pidfile) if ($daemonize);
  140. # set our pipes to be piping hot
  141. $|=1;
  142. while( ($retry_count > 0) && (!$got_network) )
  143. {
  144. try #Try and allocate a socket, bind it to our IPC address, and set it to listen for connections
  145. {
  146. socket(SERVER,PF_INET,SOCK_STREAM,$proto) || die "socket: $!";
  147. setsockopt(SERVER, SOL_SOCKET, SO_REUSEADDR, 1);
  148. bind (SERVER, $addr) || die "bind: $!";
  149. listen(SERVER,5) || die "listen: $!";
  150. $got_network = 1;
  151. }
  152. catch #If that didn't work for some reason, log the error, clean up, and prepair to retry
  153. {
  154. my $errmsg = $_; #Remember the error message
  155. close(SERVER); #Clean up the server socket if it needs it
  156. #Decrement our remaining retry counter
  157. $retry_count = $retry_count - 1;
  158. #Log the message to our debug log
  159. print "Failed to allocate socket, will retry $retry_count times: $errmsg\n";
  160. #Wait a reasonable period before trying again
  161. sleep $retry_delay;
  162. };
  163. }
  164. if($got_network) #If we met with success binding to the network, report it
  165. {
  166. my $logmsg = "Socket setup successful. Listening for clients at $bind_ip:$bind_port\n";
  167. print $logmsg;
  168. }
  169. else #If we ran out of patience and gave up, report that as well and exit
  170. {
  171. my $errmsg = "Could not allocate and bind listening socket at $bind_ip:$bind_port after $max_retries attempts.\n";
  172. die $errmsg;
  173. }
  174. # Set up our signal handler which will clean up defunct child processes and let the main
  175. # accept() loop know that the reason accept returned was due to a signal, not a legit connection.
  176. $SIG{CHLD} = \&REAPER;
  177. #This for loop is efficient, but confusting, so I'll break it down by clause
  178. #
  179. # The first clause ($sigreceived = 0) clears the signal received flag that will be set if the
  180. # accept() call was interrupted by a signal. This clause runs once before the first run of the loop
  181. #
  182. # The second clause is the test clause, it will process the contents of the loop if EITHER
  183. # accept() has returned (presumably generating a valid file handle for the CLIENT end of the
  184. # socket, OR the signal received flag is set (thus accept would have returned early without
  185. # having actually accepted a connection.
  186. #
  187. # The third clause (the 'incrementer') is run after each time the body is executed, before the
  188. # test clause is executed again (deciding whether to run the body or drop out... This test
  189. # clause will close the parent process' copy of the CLIENT file handle since (see body below)
  190. # after the body executes, all communication with the socket referred to by that file handle
  191. # will be carried out by the spawned child process. This frees the parent's copy of the CLIENT
  192. # file handle to be used again in the parent process for the next accepted incoming connection.
  193. for ( $sigreceived = 0; accept(CLIENT,SERVER) || $sigreceived; $sigreceived = 0, close CLIENT)
  194. {
  195. next if $sigreceived; #If we were interrupted by a signal, there is no real client, just go back and try to accept a new one
  196. print "connection received.\n"; #Print a diagnostic message confirming that we have made a connection
  197. spawn sub {handle_client();}; #fork() off a child process that will handle communication with the socket pointed to by the CLIENT file handle
  198. }