You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

snfXCImgr.cpp 50KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806
  1. // snfXCImgr.cpp
  2. // Copyright (C) 2007 - 2009 ARM Research Labs, LLC
  3. // See www.armresearch.com for the copyright terms.
  4. //
  5. // See snfXCImgr.hpp for details.
  6. #include "SNFMulti/SNFMulti.hpp"
  7. #include "SNFMulti/snfXCImgr.hpp"
  8. using namespace std;
  9. using namespace CodeDweller;
  10. namespace SNFMulti {
  11. // snfXCIServerCommandHandler Virtual Base Class Default Processor.
  12. const string XCIServerCommandDefaultResponse =
  13. "<snf><xci><server><response message=\'Not Implemented\' code=\'-1\'/></server></xci></snf>\n";
  14. string snfXCIServerCommandHandler::processXCIRequest(snf_xci& X) { // A Server using SNFMulti
  15. return XCIServerCommandDefaultResponse; // can provide a useful processor.
  16. }
  17. // snfXCIJob encapsulates a single XCI transaction.
  18. void snfXCIJob::clear() { // Clear the buffers.
  19. Request.clear(); // Clear the request and
  20. Response.clear(); // response buffers.
  21. SetupTime = 0; // No setup time yet.
  22. }
  23. // snfXCIJobProcessor encapsulates the logic to respond to an XCI request.
  24. snfXCIJobProcessor::snfXCIJobProcessor(snf_RulebaseHandler* H) : // Setup scanner.
  25. myHome(H) { // Establish myHome from H.
  26. myEngine = new snf_EngineHandler(); // Create an engine handler and
  27. myEngine->open(H); // tie it in to our home rulebase.
  28. }
  29. snfXCIJobProcessor::~snfXCIJobProcessor() { // Tear down scanner.
  30. if(myEngine) { // Checking first that we have one,
  31. myEngine->close(); // close the engine and then
  32. delete myEngine; // delete it. Set the pointer to
  33. myEngine = 0; // NULL to enforce the point.
  34. }
  35. myHome = 0; // NULL out our home too.
  36. }
  37. //// This collection of functions handle the processing of all XCI requests.
  38. bool snfXCIJobProcessor::isScanJob() { // True if myXCI is a scan job.
  39. if(0 < myXCI.scanner_scan_file.length()) return true; // If we have a scan file: true!
  40. return false; // otherwise false.
  41. }
  42. bool snfXCIJobProcessor::isGBUdbJob() { // True if myXCI is a GBUdb job.
  43. if( // GBUdb jobs have either
  44. 0 < myXCI.gbudb_test_ip.length() || // an IP to test or
  45. 0 < myXCI.gbudb_set_ip.length() || // an IP to setup or
  46. 0 < myXCI.gbudb_bad_ip.length() || // a bad IP to flag or
  47. 0 < myXCI.gbudb_good_ip.length() || // a good IP to flag or
  48. 0 < myXCI.gbudb_drop_ip.length()
  49. ) return true; // If we have one of these: true!
  50. return false; // otherwise false.
  51. }
  52. bool snfXCIJobProcessor::isReportJob() { // True if myXCI is a Report job.
  53. if(0 < myXCI.report_request_status_class.length()) return true; // If we have a report status class
  54. return false; // it's a report otherwise it's not.
  55. }
  56. bool snfXCIJobProcessor::isCommandJob() { // True if myXCI is a Command job.
  57. if(0 < myXCI.xci_server_command.length()) return true; // If we have a command string: true!
  58. return false; // otherwise false.
  59. }
  60. void snfXCIJobProcessor::processScan(snfXCIJob& J) { // Process a scan request.
  61. try { // Safely perform our scan.
  62. // Check for forced IP.
  63. IP4Address ForcedIP = 0UL; // Don't expect a forced IP.
  64. if(0 < myXCI.scanner_scan_ip.length()) { // If we have one then
  65. ForcedIP = myXCI.scanner_scan_ip; // convert it from the string.
  66. }
  67. // Scan the message file.
  68. int ScanResult = // Scan the file using our
  69. myEngine->scanMessageFile( // engine. Use the file
  70. myXCI.scanner_scan_file.c_str(), // path in the XCI request, and
  71. J.SetupTime, // the recorded setup time. Use the
  72. ForcedIP // forced IP if provided.
  73. );
  74. // Create a proper xci resposne.
  75. ostringstream ResultString; // Use a stringstream to make it easier.
  76. ResultString
  77. << "<snf><xci><scanner><result code=\'" // Emit the preamble.
  78. << ScanResult << "\'"; // Emit the scan result.
  79. if( // Check for optional data requests.
  80. false == myXCI.scanner_scan_xhdr &&
  81. false == myXCI.scanner_scan_log
  82. ) { // If no optional data was requested
  83. ResultString // then close the <request/> and
  84. << "/></scanner></xci></snf>\n" // emit the closing elements.
  85. << endl; // End of the line.
  86. } else { // If optional data is requested:
  87. ResultString << ">" << endl; // Complete the <result> open tag.
  88. if(true == myXCI.scanner_scan_xhdr) { // Optionally include XHDR data.
  89. ResultString // If xheaders are requested...
  90. << "<xhdr>" << myEngine->getXHDRs() // Emit the xhdr element & contents.
  91. << "</xhdr>" << endl; // End the xhdr and end of line.
  92. }
  93. if(true == myXCI.scanner_scan_log) { // Optionally include XMLLog data.
  94. ResultString // If the log data is requested...
  95. << "<log>" << myEngine->getXMLLog() // Emit the log element & data.
  96. << "</log>" << endl; // End the log data and end of line.
  97. }
  98. ResultString << "</result></scanner></xci></snf>\n"; // Emit the closing elements.
  99. }
  100. J.Response = ResultString.str(); // Capture the formatted response.
  101. }
  102. // Decode the known exceptions
  103. catch(snf_EngineHandler::AllocationError& e) {
  104. J.Response = "<snf><xci><error message=\'AllocationError ";
  105. J.Response.append(e.what());
  106. J.Response.append("\'/></xci></snf>\n");
  107. }
  108. catch(snf_EngineHandler::BadMatrix& e) {
  109. J.Response = "<snf><xci><error message=\'BadMatrix ";
  110. J.Response.append(e.what());
  111. J.Response.append("\'/></xci></snf>\n");
  112. }
  113. catch(snf_EngineHandler::Busy& e) {
  114. J.Response = "<snf><xci><error message=\'Busy ";
  115. J.Response.append(e.what());
  116. J.Response.append("\'/></xci></snf>\n");
  117. }
  118. catch(snf_EngineHandler::FileError& e) {
  119. J.Response = "<snf><xci><error message=\'FileError ";
  120. J.Response.append(e.what());
  121. J.Response.append("\'/></xci></snf>\n");
  122. }
  123. catch(snf_EngineHandler::MaxEvals& e) {
  124. J.Response = "<snf><xci><error message=\'MaxEvals ";
  125. J.Response.append(e.what());
  126. J.Response.append("\'/></xci></snf>\n");
  127. }
  128. catch(snf_EngineHandler::Panic& e) {
  129. J.Response = "<snf><xci><error message=\'Panic ";
  130. J.Response.append(e.what());
  131. J.Response.append("\'/></xci></snf>\n");
  132. }
  133. catch(snf_EngineHandler::XHDRError& e) {
  134. J.Response = "<snf><xci><error message=\'XHDRError ";
  135. J.Response.append(e.what());
  136. J.Response.append("\'/></xci></snf>\n");
  137. }
  138. // Decode the unknown exceptions
  139. catch(exception& e) {
  140. J.Response = "<snf><xci><error message=\'Exception! ";
  141. J.Response.append(e.what());
  142. J.Response.append("\'/></xci></snf>\n");
  143. }
  144. catch(...) {
  145. J.Response = "<snf><xci><error message=\'... Thrown!\'/></xci></snf>\n";
  146. }
  147. }
  148. string snfXCIJobProcessor::processGBUdb() { // Process a GBUdb request.
  149. GBUdb& myGBUdb = myHome->MyGBUdb; // Make a convenient GBUdb handle.
  150. IP4Address IP; // We will work with an IP.
  151. GBUdbRecord R; // We will get a record to return.
  152. // Test an IP - return it's current data.
  153. if(0 < myXCI.gbudb_test_ip.length()) { // IF: Test an IP
  154. IP = myXCI.gbudb_test_ip; // Convert the IP.
  155. } else
  156. // Set or update an IP's data.
  157. if(0 < myXCI.gbudb_set_ip.length()) { // IF: Set an IP's data.
  158. IP = myXCI.gbudb_set_ip; // Convert the IP.
  159. if( // Check for a compound update:
  160. 0 <= myXCI.gbudb_set_bad_count || // If we are changing the bad
  161. 0 <= myXCI.gbudb_set_good_count // or good count then this is
  162. ) { // a compound update (read then write).
  163. R = myGBUdb.getRecord(IP); // Get the record (or a safe blank).
  164. if(0 <= myXCI.gbudb_set_bad_count) // If we have a bad count to set
  165. R.Bad(myXCI.gbudb_set_bad_count); // then set the bad count.
  166. if(0 <= myXCI.gbudb_set_good_count) // If we have a good count to set
  167. R.Good(myXCI.gbudb_set_good_count); // then set the good count.
  168. if(0 < myXCI.gbudb_set_type.length()) { // If type, set type...
  169. switch(myXCI.gbudb_set_type.at(0)) { // Determine the type based on the
  170. case 'g': case 'G': { R.Flag(Good); break; } // first character of the name and
  171. case 'b': case 'B': { R.Flag(Bad); break; } // set the appropriate flag.
  172. case 'u': case 'U': { R.Flag(Ugly); break; }
  173. case 'i': case 'I': { R.Flag(Ignore); break; }
  174. }
  175. }
  176. myGBUdb.setRecord(IP, R); // Save the data.
  177. } else // This might be a simple flag change.
  178. if(0 < myXCI.gbudb_set_type.length()) { // If type, set type...
  179. switch(myXCI.gbudb_set_type.at(0)) { // Determine the type based on the
  180. case 'g': case 'G': { R = myGBUdb.setGood(IP); break; } // first character of the name and
  181. case 'b': case 'B': { R = myGBUdb.setBad(IP); break; } // set the appropriate flag. Simple
  182. case 'u': case 'U': { R = myGBUdb.setUgly(IP); break; } // flag changes are atomic so there is
  183. case 'i': case 'I': { R = myGBUdb.setIgnore(IP); break; } // no need to "save" later.
  184. }
  185. } else { // Empty set command?
  186. return XCIBadSetResponse; // That's bad. Use test!
  187. }
  188. } else
  189. // Add a bad event to an IPs data.
  190. if(0 < myXCI.gbudb_bad_ip.length()) { // IF: Add a bad mark for this IP
  191. IP = myXCI.gbudb_bad_ip; // Convert the IP.
  192. R = myGBUdb.addBad(IP); // Add a bad mark.
  193. } else
  194. // Add a good event to an IPs data.
  195. if(0 < myXCI.gbudb_good_ip.length()) { // IF: Add a good mark for this IP
  196. IP = myXCI.gbudb_good_ip; // Convert the IP.
  197. R = myGBUdb.addGood(IP); // Add a bad mark.
  198. } else
  199. // Drop an IP from the database.
  200. if(0 < myXCI.gbudb_drop_ip.length()) { // IF: Drop an IP's data.
  201. IP = myXCI.gbudb_drop_ip; // Convert the IP.
  202. myGBUdb.dropRecord(IP); // Forget about it.
  203. }
  204. // Return the final state of the IP's data.
  205. IPTestRecord IPState(IP);
  206. myHome->performIPTest(IPState);
  207. ostringstream Response; // Use a stringstream for our output.
  208. Response
  209. << "<snf><xci><gbudb><result " // Get the response started.
  210. << "ip=\'" << (string) IP // Emit the ip.
  211. << "\' type=\'" // Emit the type.
  212. << ((Good == IPState.G.Flag()) ? "good" :
  213. ((Bad == IPState.G.Flag()) ? "bad" :
  214. ((Ugly == IPState.G.Flag()) ? "ugly" :
  215. ((Ignore == IPState.G.Flag()) ? "ignore" : "error"))))
  216. << "\' p=\'" << IPState.G.Probability() // Emit the probability.
  217. << "\' c=\'" << IPState.G.Confidence() // Emit the confidence.
  218. << "\' b=\'" << IPState.G.Bad() // Emit the bad count.
  219. << "\' g=\'" << IPState.G.Good() // Emit the good count.
  220. << "\' range=\'"
  221. << ((Unknown == IPState.R) ? "unknown" :
  222. ((White == IPState.R) ? "white" :
  223. ((Normal == IPState.R) ? "normal" :
  224. ((New == IPState.R) ? "new" :
  225. ((Caution == IPState.R) ? "caution" :
  226. ((Black == IPState.R) ? "black" :
  227. ((Truncate == IPState.R) ? "truncate" : "error")))))))
  228. << "\' code=\'" << IPState.Code
  229. << "\'"
  230. << "/></gbudb></xci></snf>" // Finish it up.
  231. << endl;
  232. return Response.str(); // Return the formatted response.
  233. }
  234. string snfXCIJobProcessor::processStatusReport() { // Process a report request.
  235. string ReportToSend; // Keep this in scope.
  236. if(0 == myXCI.report_request_status_class.find("hour")) { // Please send the hour report.
  237. ReportToSend = myHome->MyLOGmgr.getStatusHourReport();
  238. } else
  239. if(0 == myXCI.report_request_status_class.find("minute")) { // Please send the minute report.
  240. ReportToSend = myHome->MyLOGmgr.getStatusMinuteReport();
  241. } else { // Please send the second report.
  242. ReportToSend = myHome->MyLOGmgr.getStatusSecondReport();
  243. }
  244. string Response = "<snf><xci><report><response>"; // Construct the response using the
  245. Response.append(ReportToSend); // snf/xci template and the selected
  246. Response.append("</response></report></xci></snf>"); // status report text.
  247. return Response; // Return the response.
  248. }
  249. void snfXCIJobProcessor::process(snfXCIJob& J) { // Process a Job.
  250. // Parse the XCI request and check for an error.
  251. myXCI.read(J.Request); // Parse the request.
  252. if(myXCI.bad()) { // If it's bad then
  253. J.Response = XCIErrorResponse; // respond with an error.
  254. myHome->logThisError("XCI",-1,"Bad Request"); // Log the error.
  255. return; // Done.
  256. } else
  257. // Process scan requests.
  258. if(isScanJob()) { // If this is a Scan request
  259. processScan(J); // respond with the result.
  260. return; // Done.
  261. } else
  262. // Process gbudb requests.
  263. if(isGBUdbJob()) { // If this is a GBUdb request
  264. J.Response = processGBUdb(); // respond with the result.
  265. return; // Done.
  266. } else
  267. // Process report requests.
  268. if(isReportJob()) { // If this is a Status report request
  269. J.Response = processStatusReport(); // respond with the desired report.
  270. return; // Done.
  271. } else
  272. // Process server commands.
  273. if(isCommandJob()) { // If this is a server command
  274. J.Response = myHome->processXCIServerCommandRequest(myXCI); // pass it up and return the
  275. return; // result. Done.
  276. } else
  277. // If we get to this point we don't understand the well formed request.
  278. J.Response = XCIErrorResponse; // Don't understand?
  279. myHome->logThisError("XCI",-2,"Unrecognized Request"); // Log the error. Respond with
  280. return; // the standard error response.
  281. }
  282. // ChannelJob encapsulates a Client Job while in the queue and how long it has
  283. // been in the system (since created).
  284. ChannelJob::ChannelJob() : myClient(0) {} // Empty is the null client.
  285. ChannelJob::ChannelJob(TCPClient* C) : // We are created like this.
  286. myClient(C) { // We capture the client and
  287. } // our timer starts automaticially.
  288. msclock ChannelJob::Age() { // How old is this job?
  289. return Lifetime.getElapsedTime(); // Return the elapsed time in ms.
  290. }
  291. TCPClient* ChannelJob::Client() { // What client does it hold?
  292. return myClient; // Return the Client pointer.
  293. }
  294. // snfXCITCPChannel encapsulates the logic to queue and handle TCPClients for
  295. // the XCI interface. The queued TCPClients each represent a single request.
  296. // Each request is handled in turn by reading the request into an snfXCIJob,
  297. // handing that snfXCIJob to an snfXCIJobProcessor, transmitting the result
  298. // back to the TCPClient, closing the connection, and recycling the snfXCIJob
  299. // object for the next round.
  300. // snfXCITCPChannel shuts down when given a NULL TCPClient; This allows any
  301. // jobs in queue to be handled before the thread stops. To shut down a channel
  302. // { C->submit(NULL); C->join(); delete C; C = NULL;}
  303. void snfXCITCPChannel::give(ChannelJob& J) { // Give a job to the queue.
  304. ScopeMutex OneAtATimePlease(QueueMutex); // Protected with a mutex...
  305. JobQueue.push(J); // Push the job in.
  306. LatestSize = JobQueue.size(); // Set the blinking light.
  307. QueueGateway.produce(); // Add the item to our gateway.
  308. }
  309. ChannelJob snfXCITCPChannel::take() { // Take a job from the queue.
  310. QueueGateway.consume(); // Hold on until there is work.
  311. ScopeMutex OneAtATimePlease(QueueMutex); // Queue Data Protected with a mutex.
  312. ChannelJob J = JobQueue.front(); // Grab the next job in the queue.
  313. JobQueue.pop(); // Pop that job out of the queue.
  314. LatestSize = JobQueue.size(); // Set the blinking light.
  315. return J; // Return the Job.
  316. }
  317. const int RWTimeLimit = 30000; // RWTimeLimit in ms. 30 seconds.
  318. const string endSNF = "</snf>"; // snf_xci snf element terminator.
  319. const int RWPollMin = 15; // Minimum time between polls.
  320. const int RWPollMax = 75; // Maximum time between polls.
  321. const int MaxQueueLength = 32; // Most waiting in any queue.
  322. const int MaxTCPQueueLength = 4 * MaxQueueLength; // Most connections waiting.
  323. void snfXCITCPChannel::readRequest(TCPClient* Client) { // Read Job.Request from Client.
  324. Timeout ReadTimeLimit(RWTimeLimit); // We have time limits.
  325. PollTimer ReadThrottle(RWPollMin, RWPollMax); // Throttle with a spiral delay.
  326. while(
  327. false == ReadTimeLimit.isExpired() && // Read stuff until we're out of time
  328. string::npos == Job.Request.find(endSNF,0) // or we have a complete request.
  329. ) {
  330. memset(LineBuffer, 0, sizeof(LineBuffer)); // Clear the buffer.
  331. int bytes = Client->delimited_receive( // Read up to all but one byte
  332. LineBuffer, sizeof(LineBuffer)-1, '\n'); // of the buffer up to the first \n.
  333. if(0 < bytes) { // If we got some bytes
  334. Job.Request.append(LineBuffer); // Append the data we got and
  335. ReadThrottle.reset(); // reset the throttle.
  336. } else { // If we didn't get any bytes then
  337. ReadThrottle.pause(); // wait a little bit more each round.
  338. }
  339. } // When we're done we will return.
  340. }
  341. void snfXCITCPChannel::writeResponse(TCPClient* Client) { // Write Job.Request from Client.
  342. Timeout WriteTimeLimit(RWTimeLimit); // We have a time limit.
  343. PollTimer WriteThrottle(RWPollMin, RWPollMax); // Throttle with a spiral delay.
  344. for( // For all the bytes in the response:
  345. int Length = Job.Response.length(), BytesThisTime = 0, Bytes = 0; // Bytes to send, this time and sent.
  346. Bytes < Length && // Keep going if we've got more to
  347. false == WriteTimeLimit.isExpired(); // send and we still have time.
  348. ) {
  349. BytesThisTime = Client->transmit( // Transmit some bytes.
  350. &Job.Response[Bytes], Job.Response.length()-Bytes); // from where we are, what is left.
  351. if(0 < BytesThisTime) { // If we sent bytes
  352. Bytes += BytesThisTime; // then keep track of how many
  353. WriteThrottle.reset(); // and reset our throttle to min.
  354. } else { // If we didn't then pause a bit
  355. WriteThrottle.pause(); // and let our delay grow.
  356. }
  357. }
  358. }
  359. const int XCI_Reading = 0; // XCI Mode Flags.
  360. const int XCI_Processing = 1;
  361. const int XCI_Writing = 2;
  362. void snfXCITCPChannel::myTask() { // Thread's main loop.
  363. bool WeAreAlive = true; // It's not over 'til it's over.
  364. while(WeAreAlive) { // While we are alive:
  365. CurrentThreadState(XCI_Wait); // Mark our state.
  366. ChannelJob J = take(); // Pull a Client Job from the queue.
  367. if(0 == J.Client()) { // If the job is empty we're done.
  368. CurrentThreadState(XCI_Shutdown); // Mark our state.
  369. WeAreAlive = false; // Turn off the alive flag and
  370. break; // break out of the loop.
  371. } else { // When we have a job to do:
  372. int XCIMode = XCI_Reading;
  373. try {
  374. CurrentThreadState(XCI_Read);
  375. XCIMode = XCI_Reading; // Now we are reading.
  376. readRequest(J.Client()); // Read the client job.
  377. CurrentThreadState(XCI_Process);
  378. XCIMode = XCI_Processing; // Now we are processing.
  379. Job.SetupTime = J.Age(); // Capture the read and queue time.
  380. Processor.process(Job); // Pass the XCIJob to our processor.
  381. CurrentThreadState(XCI_Write);
  382. XCIMode = XCI_Writing; // Now we are writing.
  383. writeResponse(J.Client()); // Write the response.
  384. }
  385. // Log any exceptions that were thrown.
  386. catch(...) {
  387. switch(XCIMode) {
  388. case XCI_Reading: {
  389. myHome->logThisError("XCI",-5,"SocketReadError");
  390. break;
  391. }
  392. case XCI_Processing: {
  393. myHome->logThisError("XCI",-6,"ProcessError");
  394. break;
  395. }
  396. case XCI_Writing: {
  397. myHome->logThisError("XCI",-7,"SocketWriteError");
  398. break;
  399. }
  400. }
  401. }
  402. }
  403. // At the end of every job we clean up no matter what.
  404. if(0 != J.Client()) { // If we have a client
  405. CurrentThreadState(XCI_Close);
  406. J.Client()->close(); // Close the client.
  407. delete J.Client(); // Delete the client.
  408. }
  409. CurrentThreadState(XCI_Clear);
  410. Job.clear(); // Clear the job buffer.
  411. } // Go again.
  412. }
  413. const ThreadType snfXCITCPChannel::Type("snfXCITCPChannel"); // The thread's type.
  414. //// XCI Thread States
  415. const ThreadState snfXCITCPChannel::XCI_Wait("Waiting For Take()");
  416. const ThreadState snfXCITCPChannel::XCI_Read("Reading Request");
  417. const ThreadState snfXCITCPChannel::XCI_Process("Processing Job");
  418. const ThreadState snfXCITCPChannel::XCI_Write("Writing Results");
  419. const ThreadState snfXCITCPChannel::XCI_Close("Closing Connection");
  420. const ThreadState snfXCITCPChannel::XCI_Clear("Clearing Workspace");
  421. const ThreadState snfXCITCPChannel::XCI_Shutdown("Shutting Down");
  422. snfXCITCPChannel::snfXCITCPChannel(snf_RulebaseHandler* H, string N) : // Create these with a home rulebase.
  423. Thread(snfXCITCPChannel::Type, N), // XCI TCP Channel Type & name.
  424. myHome(H), // We know our home.
  425. Processor(H), // Our processor has a rulebase.
  426. LatestSize(0) { // Our job queue size is zero.
  427. run(); // We start our thread.
  428. }
  429. snfXCITCPChannel::~snfXCITCPChannel() { // Destroy them very carefully.
  430. ChannelJob EndJob; // On the way down feed ourselves
  431. give(EndJob); // an empty job - that will end our
  432. join(); // thread once other jobs are done.
  433. myHome = 0; // Once joined our home is gone.
  434. } // We're done.
  435. int snfXCITCPChannel::Size() { // Keep track of how full they are.
  436. return LatestSize; // Flash the blinking light.
  437. }
  438. void snfXCITCPChannel::submit(TCPClient* C) { // This is how we submit jobs.
  439. ChannelJob J(C); // Create a Job for this client.
  440. give(J); // Give it (copy) to the queue.
  441. }
  442. // snfXCImgr encapsulates a service engine that takes XCI requests via TCP,
  443. // performs the required actions, and returns an XCI response. It also checks
  444. // to see if the configuration for the XCI interface has changed.
  445. void snfXCImgr::checkCFG() { // Checks the configuration.
  446. CurrentThreadState(XCI_CheckConfig); // Update our status.
  447. int NEW_XCI_Port; // Prepare for a change in port.
  448. // Quickly as we can, grab a config packet, capture the XCI parts, and
  449. // then let it go.
  450. if(myHome->isReady()) { // If we know our home then
  451. snfCFGPacket MyCFGPacket(myHome); // Grab a configuration packet.
  452. if(MyCFGPacket.bad()) { // If it's not valid then
  453. return; // wait (skip this) till next time.
  454. } else { // If we've got a good config then
  455. CFG_XCI_ON = MyCFGPacket.Config()->XCI_OnOff; // Is XCI turned on?
  456. NEW_XCI_Port = MyCFGPacket.Config()->XCI_Port; // What port we listen to?
  457. } // If our rulebase manager was
  458. } else return; // not ready (skip this) for now.
  459. if(CFG_XCI_ON) { // If the XCI is configured up:
  460. if(NEW_XCI_Port != CFG_XCI_PORT) { // Check for a port change. If the
  461. CFG_XCI_PORT = NEW_XCI_Port; // port changed then check for a live
  462. if(Listener) { // listener. For a live port change
  463. shutdown_Listener(); // shut down the current listener and
  464. myHome->logThisInfo("XCI", 0, "ListenerDown:PortChanged"); // log the activity.
  465. startup_Listener(); // Restart the listener with the new
  466. myHome->logThisInfo("XCI", 0, "ListenerUp:PortChanged"); // port and log the event.
  467. }
  468. }
  469. startup_XCI(); // Make sure the XCI is up.
  470. } else { // If the XCI is configured down
  471. shutdown_XCI(); // then make sure it is down.
  472. }
  473. }
  474. snfXCITCPChannel* LowestQueue(snfXCITCPChannel* A, snfXCITCPChannel* B) { // Pick the lowest queue of two.
  475. return ((A->Size() < B->Size()) ? A : B); // Pick one and return it.
  476. }
  477. snfXCITCPChannel* snfXCImgr::BestAvailableChannel() { // Selects XCI channel w/ lowest queue.
  478. return LowestQueue( // Pick the lowest of the lowest.
  479. LowestQueue(
  480. LowestQueue(C0, C1),
  481. LowestQueue(C2, C3)
  482. ),
  483. LowestQueue(
  484. LowestQueue(C4, C5),
  485. LowestQueue(C6, C7)
  486. )
  487. );
  488. }
  489. void snfXCImgr::startup_Listener() { // Listener startup function.
  490. if(0 == Listener) { // If we need a new listener:
  491. Listener = new TCPListener(CFG_XCI_PORT); // Create a new listener.
  492. Listener->MaxPending = MaxTCPQueueLength; // We may get a lot of hits ;-)
  493. Listener->open(); // Open it for business.
  494. Listener->makeNonBlocking(); // Make it non-blocking.
  495. }
  496. }
  497. void snfXCImgr::shutdown_Listener() { // Listener shutdown function.
  498. if(Listener) { // Only act if there is a listener:
  499. Listener->close(); // The listener gets closed,
  500. delete Listener; // then deleted, then the
  501. Listener = 0; // Listener pointer is zeroed.
  502. }
  503. }
  504. void snfXCImgr::startup_XCI() { // XCI startup function.
  505. if(true == XCI_UP) return; // If we're already up we're done.
  506. ScopeMutex IGotIt(ChannelMutex); // Serialize state control for safety.
  507. if(myHome) { // We need to know our home.
  508. if(CFG_XCI_ON) { // If XCI is configured on, startup!
  509. C0 = new snfXCITCPChannel(myHome, "C0"); // Launch our 8 processing channels.
  510. C1 = new snfXCITCPChannel(myHome, "C1");
  511. C2 = new snfXCITCPChannel(myHome, "C2");
  512. C3 = new snfXCITCPChannel(myHome, "C3");
  513. C4 = new snfXCITCPChannel(myHome, "C4");
  514. C5 = new snfXCITCPChannel(myHome, "C5");
  515. C6 = new snfXCITCPChannel(myHome, "C6");
  516. C7 = new snfXCITCPChannel(myHome, "C7");
  517. startup_Listener(); // Start up our listener.
  518. myHome->logThisInfo("XCI", 0, "Startup"); // Log the startup.
  519. XCI_UP = true; // Set the flag. We're up!
  520. }
  521. }
  522. }
  523. void snfXCImgr::shutdown_XCI() { // XCI shutdown function.
  524. if(false == XCI_UP) return; // If we're already down we're done.
  525. ScopeMutex IGotIt(ChannelMutex); // Serialize state control for safety.
  526. shutdown_Listener(); // If up, take down & 0 the Listener.
  527. if(C0) { delete C0; C0 = 0; } // If up, take C0 down and NULL it.
  528. if(C1) { delete C1; C1 = 0; } // If up, take C1 down and NULL it.
  529. if(C2) { delete C2; C2 = 0; } // If up, take C2 down and NULL it.
  530. if(C3) { delete C3; C3 = 0; } // If up, take C3 down and NULL it.
  531. if(C4) { delete C4; C4 = 0; } // If up, take C4 down and NULL it.
  532. if(C5) { delete C5; C5 = 0; } // If up, take C5 down and NULL it.
  533. if(C6) { delete C6; C6 = 0; } // If up, take C6 down and NULL it.
  534. if(C7) { delete C7; C7 = 0; } // If up, take C7 down and NULL it.
  535. myHome->logThisInfo("XCI", 0, "Shutdown"); // Log the shutdown.
  536. XCI_UP = false; // Set the flag. We're down!
  537. }
  538. int snfXCImgr::pollLoopCount() { // Retrieve & reset Loop Count.
  539. int x = diagLoopCount;
  540. diagLoopCount = 0;
  541. return x;
  542. }
  543. int snfXCImgr::pollClientCount() { // Retrieve & reset Client Count.
  544. int x = diagClientCount;
  545. diagClientCount = 0;
  546. return x;
  547. }
  548. const ThreadState snfXCImgr::XCI_InitialConfig("Initial Config"); // Getting initial configuration.
  549. const ThreadState snfXCImgr::XCI_InitialStartup("Initial Startup"); // Performing first startup.
  550. const ThreadState snfXCImgr::XCI_CheckConfig("Checking Config"); // Checking configuration.
  551. const ThreadState snfXCImgr::XCI_PollingListener("Polling Listener"); // Polling Listener for jobs.
  552. const ThreadState snfXCImgr::XCI_SubmittingJob("Submitting Job"); // Submitting a new job.
  553. const ThreadState snfXCImgr::XCI_ListenerDown("Listener Down!"); // Listener is down.
  554. const ThreadState snfXCImgr::XCI_Stopping("Exited Polling Loop"); // XCImgr Exiting Big Loop
  555. void snfXCImgr::myTask() { // Main thread task.
  556. PollTimer PollingThrottle(RWPollMin, RWPollMax); // Set up a dynamic delay.
  557. Timeout WaitForCFG(1000); // CFG Check every second or so.
  558. // Wait for our initial configuration.
  559. CurrentThreadState(XCI_InitialConfig); // Update our status.
  560. Sleeper WaitATic(1000); // One second sleeper.
  561. while(false == CFG_XCI_ON) { // Before we've been turned on
  562. if(TimeToStop) return; // loop unless it's time to stop.
  563. checkCFG(); WaitForCFG.restart(); // Check our configuration
  564. WaitATic(); // every second or so.
  565. }
  566. // Once our configuration is good and we are turned on we get here.
  567. try { // Safely accept/process requests.
  568. CurrentThreadState(XCI_InitialStartup); // Update our status.
  569. startup_XCI(); // We're on, so turn on!
  570. while(false == TimeToStop) { // While it is not time to stop:
  571. // Occasionally we check to see what our configuration says. If
  572. // the XCI is configured up, or down, or if the port changes then
  573. // the checkCFG() function handles the changes. After that all we
  574. // need to do here is check for a listener -- if we're up we will
  575. // have one and if not then we won't. Without a listener we will
  576. // slow down and keep checking for a configuration change.
  577. if(WaitForCFG.isExpired()) { checkCFG(); WaitForCFG.restart(); } // Check the CFG periodically.
  578. // Get a new client if we have room in the queue
  579. // and the listener is live.
  580. int JobsThisRound = 0; // Keep track of each batch.
  581. if(Listener) { // Check for a good listener.
  582. CurrentThreadState(XCI_PollingListener); // Update our status.
  583. TCPClient* NewClient; // This will be our client.
  584. do { // Fast as we can - grab the work:
  585. ++diagLoopCount; // Count Polling Loops.
  586. NewClient = 0; // Clear our client pointer.
  587. snfXCITCPChannel* Channel = BestAvailableChannel(); // Pick a channel to use then
  588. if(MaxQueueLength > Channel->Size()) { // If we have room in the queue
  589. NewClient = Listener->acceptClient(); // get a new client.
  590. if(NewClient) { // If we got one:
  591. CurrentThreadState(XCI_SubmittingJob); // Update our status.
  592. ++diagClientCount; // Count Clients.
  593. NewClient->makeNonBlocking(); // Make the client non-blocking.
  594. Channel->submit(NewClient); // Submit the new client.
  595. }
  596. }
  597. } while( // Keep getting work in this tight
  598. (0 != NewClient)&& // loop until we run out of work
  599. (MaxTCPQueueLength > diagClientCount) // or we've pulled a full queue.
  600. );
  601. } else {
  602. CurrentThreadState(XCI_ListenerDown); // Update our status.
  603. } // Throttle our loop to keep it real:
  604. if(0 == JobsThisRound) PollingThrottle.pause(); // If we got nothing then slow down.
  605. else PollingThrottle.reset(); // If we got some, keep getting it!
  606. } // When we're done with the big loop:
  607. CurrentThreadState(XCI_Stopping); // Update our status.
  608. shutdown_XCI(); // Shutdown if we're not already.
  609. } // End of the active section.
  610. catch(exception& e) { // If we get a knowable exception
  611. myHome->logThisError("XCI", -9, e.what()); // then we report it in detail,
  612. try { shutdown_XCI(); } catch(...) {} // shutdown if we're not already,
  613. WaitATic(); // wait a tic and try again.
  614. }
  615. catch(...) { // If we have an unhandled exception
  616. myHome->logThisError("XCI", -10, "Panic!"); // Panic and reset. Notify the log.
  617. try { shutdown_XCI(); } catch(...) {} // Shutdown if we're not already.
  618. WaitATic(); // Pause to let things settle.
  619. } // Let's try this again.
  620. }
  621. const ThreadType snfXCImgr::Type("snfXCIManager"); // The thread's type.
  622. const int XCI_Default_Port = 9001; // Listener Default port = 9001.
  623. snfXCImgr::snfXCImgr() : // Construct with no home.
  624. Thread(snfXCImgr::Type, "XCI Manager"), // XCI Manager type and Name.
  625. CFG_XCI_ON(false), // Everything starts off,
  626. CFG_XCI_PORT(XCI_Default_Port), // default, and
  627. myHome(0), // nulled.
  628. C0(0), C1(0), C2(0), C3(0),
  629. Listener(0),
  630. XCI_UP(false),
  631. diagLoopCount(0), diagClientCount(0),
  632. TimeToStop(true) { // We don't run until linkHome().
  633. }
  634. snfXCImgr::~snfXCImgr() { // Stop when we are destroyed.
  635. stop(); // Like I said, stop().
  636. }
  637. void snfXCImgr::linkHome(snf_RulebaseHandler* Home) { // Link to Home and set up shop.
  638. if(0 != Home && 0 == myHome) { // If we are getting our home
  639. myHome = Home; // then capture it,
  640. myHome->use(); // Update it's use count.
  641. TimeToStop = false; // clear the time to stop bit,
  642. run(); // run our thread.
  643. }
  644. }
  645. int snfXCImgr::TotalQueue() { // Return the total work queue size.
  646. ScopeMutex IGotIt(ChannelMutex); // Serialize state control for safety.
  647. return (
  648. ((0 == C0) ? 0 : C0->Size()) +
  649. ((0 == C1) ? 0 : C1->Size()) +
  650. ((0 == C2) ? 0 : C2->Size()) +
  651. ((0 == C3) ? 0 : C3->Size())
  652. );
  653. }
  654. void snfXCImgr::stop() { // Called to shut down.
  655. if(false == TimeToStop) { // If we are not stopped then
  656. TimeToStop = true; // it is time to stop.
  657. join(); // Wait for our main thread first,
  658. shutdown_XCI(); // then shut down the XCI.
  659. myHome->unuse(); // Let go of the rulebase manager.
  660. myHome = 0; // Null it out for safety.
  661. }
  662. }
  663. }