3 * A NetworkPackage class. This class implements Deliverable and Receivable
4 * because all network packages should be deliverable to other nodes and
5 * receivable from other nodes. It further provides methods for reading raw
6 * content from template engines and feeding it to the stacker for undeclared
9 * The factory method requires you to provide a compressor class (which must
10 * implement the Compressor interface). If you don't want any compression (not
11 * adviceable due to increased network load), please use the NullCompressor
12 * class and encode it with BASE64 for a more error-free transfer over the
15 * For performance reasons, this class should only be instanciated once and then
16 * used as a "pipe-through" class.
18 * @author Roland Haeder <webmaster@ship-simu.org>
20 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2011 Hub Developer Team
21 * @license GNU GPL 3.0 or any newer version
22 * @link http://www.ship-simu.org
23 * @todo Needs to add functionality for handling the object's type
25 * This program is free software: you can redistribute it and/or modify
26 * it under the terms of the GNU General Public License as published by
27 * the Free Software Foundation, either version 3 of the License, or
28 * (at your option) any later version.
30 * This program is distributed in the hope that it will be useful,
31 * but WITHOUT ANY WARRANTY; without even the implied warranty of
32 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
33 * GNU General Public License for more details.
35 * You should have received a copy of the GNU General Public License
36 * along with this program. If not, see <http://www.gnu.org/licenses/>.
38 class NetworkPackage extends BaseFrameworkSystem implements Deliverable, Receivable, Registerable, Visitable {
40 * Package mask for compressing package data:
41 * 0: Compressor extension
43 * 2: Tags, seperated by semicolons, no semicolon is required if only one tag is needed
47 const PACKAGE_MASK = '%s^%s^%s^%s';
50 * Seperator for the above mask
52 const PACKAGE_MASK_SEPERATOR = '^';
55 * Seperator for checksum
57 const PACKAGE_CHECKSUM_SEPERATOR = '_';
60 * Array indexes for above mask, start with zero
62 const INDEX_COMPRESSOR_EXTENSION = 0;
63 const INDEX_PACKAGE_DATA = 1;
65 const INDEX_CHECKSUM = 3;
68 * Array indexes for raw package array
70 const INDEX_PACKAGE_SENDER = 0;
71 const INDEX_PACKAGE_RECIPIENT = 1;
72 const INDEX_PACKAGE_CONTENT = 2;
73 const INDEX_PACKAGE_STATUS = 3;
76 * Named array elements for package data
78 const PACKAGE_DATA_SENDER = 'sender';
79 const PACKAGE_DATA_RECIPIENT = 'recipient';
80 const PACKAGE_DATA_CONTENT = 'content';
81 const PACKAGE_DATA_STATUS = 'status';
86 const PACKAGE_STATUS_NEW = 'new';
87 const PACKAGE_STATUS_FAILED = 'failed';
92 const PACKAGE_TAGS_SEPERATOR = ';';
95 * Raw package data seperator
97 const PACKAGE_DATA_SEPERATOR = '#';
100 * Stacker name for "undeclared" packages
102 const STACKER_NAME_UNDECLARED = 'package_undeclared';
105 * Stacker name for "declared" packages (which are ready to send out)
107 const STACKER_NAME_DECLARED = 'package_declared';
110 * Stacker name for "out-going" packages
112 const STACKER_NAME_OUTGOING = 'package_outgoing';
115 * Stacker name for "incoming" decoded raw data
117 const STACKER_NAME_DECODED_INCOMING = 'package_decoded_data';
120 * Stacker name for handled decoded raw data
122 const STACKER_NAME_DECODED_HANDLED = 'package_handled_decoded';
125 * Stacker name for "back-buffered" packages
127 const STACKER_NAME_BACK_BUFFER = 'package_backbuffer';
130 * Network target (alias): 'upper hubs'
132 const NETWORK_TARGET_UPPER_HUBS = 'upper';
135 * Network target (alias): 'self'
137 const NETWORK_TARGET_SELF = 'self';
140 * TCP package size in bytes
142 const TCP_PACKAGE_SIZE = 512;
145 * Protected constructor
149 protected function __construct () {
150 // Call parent constructor
151 parent::__construct(__CLASS__);
155 * Creates an instance of this class
157 * @param $compressorInstance A Compressor instance for compressing the content
158 * @return $packageInstance An instance of a Deliverable class
160 public static final function createNetworkPackage (Compressor $compressorInstance) {
162 $packageInstance = new NetworkPackage();
164 // Now set the compressor instance
165 $packageInstance->setCompressorInstance($compressorInstance);
168 * We need to initialize a stack here for our packages even for those
169 * which have no recipient address and stamp... ;-) This stacker will
170 * also be used for incoming raw data to handle it.
172 $stackerInstance = ObjectFactory::createObjectByConfiguredName('network_package_stacker_class');
174 // At last, set it in this class
175 $packageInstance->setStackerInstance($stackerInstance);
178 $packageInstance->initStackers();
180 // Get a visitor instance for speeding up things
181 $visitorInstance = ObjectFactory::createObjectByConfiguredName('node_raw_data_monitor_visitor_class', array($packageInstance));
183 // Set it in this package
184 $packageInstance->setVisitorInstance($visitorInstance);
186 // Return the prepared instance
187 return $packageInstance;
191 * Initialize all stackers
195 protected function initStackers () {
199 self::STACKER_NAME_UNDECLARED,
200 self::STACKER_NAME_DECLARED,
201 self::STACKER_NAME_OUTGOING,
202 self::STACKER_NAME_DECODED_INCOMING,
203 self::STACKER_NAME_DECODED_HANDLED,
204 self::STACKER_NAME_BACK_BUFFER
207 $this->getStackerInstance()->initStacker($stackerName);
212 * "Getter" for hash from given content and helper instance
214 * @param $content Raw package content
215 * @param $helperInstance An instance of a HelpableHub class
216 * @param $nodeInstance An instance of a NodeHelper class
217 * @return $hash Hash for given package content
218 * @todo $helperInstance is unused
220 private function getHashFromContent ($content, HelpableHub $helperInstance, NodeHelper $nodeInstance) {
222 // @TODO crc32() is very weak, but it needs to be fast
225 self::PACKAGE_CHECKSUM_SEPERATOR .
226 $nodeInstance->getSessionId() .
227 self::PACKAGE_CHECKSUM_SEPERATOR .
228 $this->getCompressorInstance()->getCompressorExtension()
236 * Change the package with given status in given stack
238 * @param $packageData Raw package data in an array
239 * @param $stackerName Name of the stacker
240 * @param $newStatus New status to set
243 private function changePackageStatus (array $packageData, $stackerName, $newStatus) {
244 // Skip this for empty stacks
245 if ($this->getStackerInstance()->isStackEmpty($stackerName)) {
246 // This avoids an exception after all packages has failed
250 // Pop the entry (it should be it)
251 $this->getStackerInstance()->popNamed($stackerName);
253 // Temporary set the new status
254 $packageData[self::PACKAGE_DATA_STATUS] = $newStatus;
257 $this->getStackerInstance()->pushNamed($stackerName, $packageData);
260 ///////////////////////////////////////////////////////////////////////////
261 // Delivering packages / raw data
262 ///////////////////////////////////////////////////////////////////////////
265 * Delivers the given raw package data.
267 * @param $packageData Raw package data in an array
270 private function declareRawPackageData (array $packageData) {
272 * We need to disover every recipient, just in case we have a
273 * multi-recipient entry like 'upper' is. 'all' may be a not so good
274 * target because it causes an overload on the network and may be
275 * abused for attacking the network with large packages.
277 $discoveryInstance = PackageDiscoveryFactory::createPackageDiscoveryInstance();
279 // Discover all recipients, this may throw an exception
280 $discoveryInstance->discoverRecipients($packageData);
282 // Now get an iterator
283 $iteratorInstance = $discoveryInstance->getIterator();
285 // ... and begin iteration
286 while ($iteratorInstance->valid()) {
288 $currentRecipient = $iteratorInstance->current();
291 $this->debugOutput('PACKAGE: Package declared for recipient ' . $currentRecipient);
294 $packageData[self::PACKAGE_DATA_RECIPIENT] = $currentRecipient;
295 var_dump($packageData);
297 // And enqueue it to the writer class
298 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECLARED, $packageData);
300 // Skip to next entry
301 $iteratorInstance->next();
305 * The recipient list can be cleaned up here because the package which
306 * shall be delivered has already been added for all entries from the
309 $discoveryInstance->clearRecipients();
313 * Delivers raw package data. In short, this will discover the raw socket
314 * resource through a discovery class (which will analyse the receipient of
315 * the package), register the socket with the connection (handler/helper?)
316 * instance and finally push the raw data on our outgoing queue.
318 * @param $packageData Raw package data in an array
321 private function deliverRawPackageData (array $packageData) {
323 * This package may become big, depending on the shared object size or
324 * delivered message size which shouldn't be so long (to save
325 * bandwidth). Because of the nature of the used protocol (TCP) we need
326 * to split it up into smaller pieces to fit it into a TCP frame.
328 * So first we need (again) a discovery class but now a protocol
329 * discovery to choose the right socket resource. The discovery class
330 * should take a look at the raw package data itself and then decide
331 * which (configurable!) protocol should be used for that type of
334 $discoveryInstance = SocketDiscoveryFactory::createSocketDiscoveryInstance();
336 // Now discover the right protocol
337 $socketResource = $discoveryInstance->discoverSocket($packageData);
340 //* NOISY-DEBUG: */ $this->debugOutput('NETWORK-PACKAGE: Reached line ' . __LINE__ . ' after discoverSocket() has been called.');
342 // We have to put this socket in our registry, so get an instance
343 $registryInstance = SocketRegistry::createSocketRegistry();
345 // Get the listener from registry
346 $helperInstance = Registry::getRegistry()->getInstance('connection');
349 //* NOISY-DEBUG: */ $this->debugOutput('NETWORK-PACKAGE: Reached line ' . __LINE__ . ' before isSocketRegistered() has been called.');
352 if ((is_resource($socketResource)) && (!$registryInstance->isSocketRegistered($helperInstance, $socketResource))) {
354 $registryInstance->registerSocket($helperInstance, $socketResource, $packageData);
358 //* NOISY-DEBUG: */ $this->debugOutput('NETWORK-PACKAGE: Reached line ' . __LINE__ . ' after isSocketRegistered() has been called.');
360 // Make sure the connection is up
361 $helperInstance->getStateInstance()->validatePeerStateConnected();
364 //* NOISY-DEBUG: */ $this->debugOutput('NETWORK-PACKAGE: Reached line ' . __LINE__ . ' after validatePeerStateConnected() has been called.');
366 // Enqueue it again on the out-going queue, the connection is up and working at this point
367 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_OUTGOING, $packageData);
371 * Sends waiting packages
373 * @param $packageData Raw package data
376 private function sendOutgoingRawPackageData (array $packageData) {
380 // Get the right connection instance
381 $helperInstance = SocketRegistry::createSocketRegistry()->getHandlerInstanceFromPackageData($packageData);
383 // Is this connection still alive?
384 if ($helperInstance->isShuttedDown()) {
385 // This connection is shutting down
386 // @TODO We may want to do somthing more here?
390 // Sent out package data
391 $sentBytes = $helperInstance->sendRawPackageData($packageData);
393 // Remember unsent raw bytes in back-buffer, if any
394 $this->storeUnsentBytesInBackBuffer($packageData, $sentBytes);
398 * "Enqueues" raw content into this delivery class by reading the raw content
399 * from given template instance and pushing it on the 'undeclared' stack.
401 * @param $helperInstance An instance of a HelpableHub class
402 * @param $nodeInstance An instance of a NodeHelper class
405 public function enqueueRawDataFromTemplate (HelpableHub $helperInstance, NodeHelper $nodeInstance) {
406 // Get the raw content ...
407 $content = $helperInstance->getTemplateInstance()->getRawTemplateData();
409 // ... and compress it
410 $content = $this->getCompressorInstance()->compressStream($content);
412 // Add magic in front of it and hash behind it, including BASE64 encoding
413 $content = sprintf(self::PACKAGE_MASK,
414 // 1.) Compressor's extension
415 $this->getCompressorInstance()->getCompressorExtension(),
416 // 2.) Raw package content, encoded with BASE64
417 base64_encode($content),
419 implode(self::PACKAGE_TAGS_SEPERATOR, $helperInstance->getPackageTags()),
421 $this->getHashFromContent($content, $helperInstance, $nodeInstance)
424 // Now prepare the temporary array and push it on the 'undeclared' stack
425 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_UNDECLARED, array(
426 self::PACKAGE_DATA_SENDER => $nodeInstance->getSessionId(),
427 self::PACKAGE_DATA_RECIPIENT => $helperInstance->getRecipientType(),
428 self::PACKAGE_DATA_CONTENT => $content,
429 self::PACKAGE_DATA_STATUS => self::PACKAGE_STATUS_NEW
434 * Checks wether a package has been enqueued for delivery.
436 * @return $isEnqueued Wether a package is enqueued
438 public function isPackageEnqueued () {
439 // Check wether the stacker is not empty
440 $isEnqueued = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_UNDECLARED)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_UNDECLARED)));
447 * Checks wether a package has been declared
449 * @return $isDeclared Wether a package is declared
451 public function isPackageDeclared () {
452 // Check wether the stacker is not empty
453 $isDeclared = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_DECLARED)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECLARED)));
460 * Checks wether a package should be sent out
462 * @return $isWaitingDelivery Wether a package is waiting for delivery
464 public function isPackageWaitingForDelivery () {
465 // Check wether the stacker is not empty
466 $isWaitingDelivery = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_OUTGOING)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_OUTGOING)));
469 return $isWaitingDelivery;
473 * Delivers an enqueued package to the stated destination. If a non-session
474 * id is provided, recipient resolver is being asked (and instanced once).
475 * This allows that a single package is being delivered to multiple targets
476 * without enqueueing it for every target. If no target is provided or it
477 * can't be determined a NoTargetException is being thrown.
480 * @throws NoTargetException If no target can't be determined
482 public function declareEnqueuedPackage () {
483 // Make sure this method isn't working if there is no package enqueued
484 if (!$this->isPackageEnqueued()) {
485 // This is not fatal but should be avoided
486 // @TODO Add some logging here
490 // Now we know for sure there are packages to deliver, we can start
491 // with the first one.
492 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_UNDECLARED);
494 // Declare the raw package data for delivery
495 $this->declareRawPackageData($packageData);
497 // And remove it finally
498 $this->getStackerInstance()->popNamed(self::STACKER_NAME_UNDECLARED);
502 * Delivers the next declared package. Only one package per time will be sent
503 * because this may take time and slows down the whole delivery
508 public function deliverDeclaredPackage () {
509 // Sanity check if we have packages declared
510 if (!$this->isPackageDeclared()) {
511 // This is not fatal but should be avoided
512 // @TODO Add some logging here
517 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_DECLARED);
520 // And try to send it
521 $this->deliverRawPackageData($packageData);
523 // And remove it finally
524 $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECLARED);
525 } catch (InvalidStateException $e) {
526 // The state is not excepected (shall be 'connected')
527 $this->debugOutput('PACKAGE: Caught exception ' . $e->__toString() . ' with message=' . $e->getMessage());
529 // Mark the package with status failed
530 $this->changePackageStatus($packageData, self::STACKER_NAME_DECLARED, self::PACKAGE_STATUS_FAILED);
535 * Sends waiting packages out for delivery
539 public function sendWaitingPackage () {
540 // Send any waiting bytes in the back-buffer before sending a new package
541 $this->sendBackBufferBytes();
543 // Sanity check if we have packages waiting for delivery
544 if (!$this->isPackageWaitingForDelivery()) {
545 // This is not fatal but should be avoided
546 $this->debugOutput('PACKAGE: No package is waiting for delivery, but ' . __METHOD__ . ' was called.');
551 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_OUTGOING);
554 // Now try to send it
555 $this->sendOutgoingRawPackageData($packageData);
557 // And remove it finally
558 $this->getStackerInstance()->popNamed(self::STACKER_NAME_OUTGOING);
559 } catch (InvalidSocketException $e) {
560 // Output exception message
561 $this->debugOutput('PACKAGE: Package was not delivered: ' . $e->getMessage());
563 // Mark package as failed
564 $this->changePackageStatus($packageData, self::STACKER_NAME_OUTGOING, self::PACKAGE_STATUS_FAILED);
568 ///////////////////////////////////////////////////////////////////////////
569 // Receiving packages / raw data
570 ///////////////////////////////////////////////////////////////////////////
573 * Checks wether decoded raw data is pending
575 * @return $isPending Wether decoded raw data is pending
577 private function isDecodedDataPending () {
578 // Just return wether the stack is not empty
579 $isPending = (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECODED_INCOMING));
586 * Checks wether new raw package data has arrived at a socket
588 * @param $poolInstance An instance of a PoolableListener class
589 * @return $hasArrived Wether new raw package data has arrived for processing
591 public function isNewRawDataPending (PoolableListener $poolInstance) {
592 // Visit the pool. This monitors the pool for incoming raw data.
593 $poolInstance->accept($this->getVisitorInstance());
595 // Check for new data arrival
596 $hasArrived = $this->isDecodedDataPending();
603 * Handles the incoming decoded raw data. This method does not "convert" the
604 * decoded data back into a package array, it just "handles" it and pushs it
609 public function handleIncomingDecodedData () {
611 * This method should only be called if decoded raw data is pending,
614 if (!$this->isDecodedDataPending()) {
615 // This is not fatal but should be avoided
616 // @TODO Add some logging here
620 // Very noisy debug message:
621 /* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: Stacker size is ' . $this->getStackerInstance()->getStackCount(self::STACKER_NAME_DECODED_INCOMING) . ' entries.');
623 // "Pop" the next entry (the same array again) from the stack
624 $decodedData = $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECODED_INCOMING);
626 // Make sure both array elements are there
627 assert((is_array($decodedData)) && (isset($decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA])) && (isset($decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE])));
630 * Also make sure the error code is SOCKET_ERROR_UNHANDLED because we
631 * only want to handle unhandled packages here.
633 assert($decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE] == BaseRawDataHandler::SOCKET_ERROR_UNHANDLED);
635 // Remove the last chunk seperator (because it is being added and we don't need it)
636 if (substr($decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA], -1, 1) == PackageFragmenter::CHUNK_SEPERATOR) {
637 // It is there and should be removed
638 $decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA] = substr($decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA], 0, -1);
641 // This package is "handled" and can be pushed on the next stack
642 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECODED_HANDLED, $decodedData);
646 * Adds raw decoded data from the given handler instance to this receiver
648 * @param $handlerInstance An instance of a Networkable class
651 public function addDecodedDataToIncomingStack (Networkable $handlerInstance) {
653 * Get the decoded data from the handler, this is an array with
654 * 'decoded_data' and 'error_code' as elements.
656 $decodedData = $handlerInstance->getNextDecodedData();
658 // Very noisy debug message:
659 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: decodedData[' . gettype($decodedData) . ']=' . print_r($decodedData, true));
661 // And push it on our stack
662 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECODED_INCOMING, $decodedData);
666 * Checks wether incoming decoded data is handled.
668 * @return $isHandled Wether incoming decoded data is handled
670 public function isIncomingDecodedDataHandled () {
671 // Determine if the stack is not empty
672 $isHandled = (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECODED_HANDLED));
679 * Assembles incoming decoded data so it will become an abstract network
684 public function assembleDecodedDataToPackage () {
685 $this->getStackerInstance()->debugInstance();
686 $this->partialStub('Please implement this method.');
690 * Checks wether a new package has arrived
692 * @return $hasArrived Wether a new package has arrived for processing
694 public function isNewPackageArrived () {
695 // @TODO Add some content here
699 * Accepts the visitor to process the visit "request"
701 * @param $visitorInstance An instance of a Visitor class
704 public function accept (Visitor $visitorInstance) {
706 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: ' . $visitorInstance->__toString() . ' has visited - START');
709 $visitorInstance->visitNetworkPackage($this);
712 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: ' . $visitorInstance->__toString() . ' has visited - FINISHED');
720 public function clearAllStacker () {
721 // Do the cleanup (no flushing)
724 self::STACKER_NAME_UNDECLARED,
725 self::STACKER_NAME_DECLARED,
726 self::STACKER_NAME_OUTGOING,
727 self::STACKER_NAME_DECODED_INCOMING,
728 self::STACKER_NAME_DECODED_HANDLED,
729 self::STACKER_NAME_BACK_BUFFER
731 // Clear this stacker by forcing an init
732 $this->getStackerInstance()->initStacker($stackerName, true);
736 /* DEBUG: */ $this->debugOutput('PACKAGE: All stacker have been re-initialized.');
740 * Removes the first failed outoging package from the stack to continue
741 * with next one (it will never work until the issue is fixed by you).
744 * @throws UnexpectedPackageStatusException If the package status is not 'failed'
745 * @todo This may be enchanced for outgoing packages?
747 public function removeFirstFailedPackage () {
748 // Get the package again
749 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_DECLARED);
751 // Is the package status 'failed'?
752 if ($packageData[self::PACKAGE_DATA_STATUS] != self::PACKAGE_STATUS_FAILED) {
754 throw new UnexpectedPackageStatusException(array($this, $packageData, self::PACKAGE_STATUS_FAILED), BaseListener::EXCEPTION_UNEXPECTED_PACKAGE_STATUS);
758 $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECLARED);