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%s%s%s';
50 * Separator for the above mask
52 const PACKAGE_MASK_SEPARATOR = '^';
55 * SEPARATOR for checksum
57 const PACKAGE_CHECKSUM_SEPARATOR = '_';
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_SEPARATOR = ';';
95 * Raw package data SEPARATOR
97 const PACKAGE_DATA_SEPARATOR = '#';
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 "chunked" decoded raw data
127 const STACKER_NAME_DECODED_CHUNKED = 'package_chunked_decoded';
130 * Stacker name for "back-buffered" packages
132 const STACKER_NAME_BACK_BUFFER = 'package_backbuffer';
135 * Network target (alias): 'upper hubs'
137 const NETWORK_TARGET_UPPER_HUBS = 'upper';
140 * Network target (alias): 'self'
142 const NETWORK_TARGET_SELF = 'self';
145 * TCP package size in bytes
147 const TCP_PACKAGE_SIZE = 512;
150 * Protected constructor
154 protected function __construct () {
155 // Call parent constructor
156 parent::__construct(__CLASS__);
160 * Creates an instance of this class
162 * @param $compressorInstance A Compressor instance for compressing the content
163 * @return $packageInstance An instance of a Deliverable class
165 public static final function createNetworkPackage (Compressor $compressorInstance) {
167 $packageInstance = new NetworkPackage();
169 // Now set the compressor instance
170 $packageInstance->setCompressorInstance($compressorInstance);
173 * We need to initialize a stack here for our packages even for those
174 * which have no recipient address and stamp... ;-) This stacker will
175 * also be used for incoming raw data to handle it.
177 $stackerInstance = ObjectFactory::createObjectByConfiguredName('network_package_stacker_class');
179 // At last, set it in this class
180 $packageInstance->setStackerInstance($stackerInstance);
183 $packageInstance->initStackers();
185 // Get a visitor instance for speeding up things
186 $visitorInstance = ObjectFactory::createObjectByConfiguredName('node_raw_data_monitor_visitor_class', array($packageInstance));
188 // Set it in this package
189 $packageInstance->setVisitorInstance($visitorInstance);
191 // Return the prepared instance
192 return $packageInstance;
196 * Initialize all stackers
198 * @param $forceReInit Whether to force reinitialization of all stacks
201 protected function initStackers ($forceReInit = false) {
205 self::STACKER_NAME_UNDECLARED,
206 self::STACKER_NAME_DECLARED,
207 self::STACKER_NAME_OUTGOING,
208 self::STACKER_NAME_DECODED_INCOMING,
209 self::STACKER_NAME_DECODED_HANDLED,
210 self::STACKER_NAME_DECODED_CHUNKED,
211 self::STACKER_NAME_BACK_BUFFER
214 $this->getStackerInstance()->initStacker($stackerName, $forceReInit);
219 * "Getter" for hash from given content and helper instance
221 * @param $content Raw package content
222 * @param $helperInstance An instance of a HelpableHub class
223 * @param $nodeInstance An instance of a NodeHelper class
224 * @return $hash Hash for given package content
225 * @todo $helperInstance is unused
227 private function getHashFromContent ($content, HelpableHub $helperInstance, NodeHelper $nodeInstance) {
229 // @TODO crc32() is very weak, but it needs to be fast
232 self::PACKAGE_CHECKSUM_SEPARATOR .
233 $nodeInstance->getSessionId() .
234 self::PACKAGE_CHECKSUM_SEPARATOR .
235 $this->getCompressorInstance()->getCompressorExtension()
243 * Change the package with given status in given stack
245 * @param $packageData Raw package data in an array
246 * @param $stackerName Name of the stacker
247 * @param $newStatus New status to set
250 private function changePackageStatus (array $packageData, $stackerName, $newStatus) {
251 // Skip this for empty stacks
252 if ($this->getStackerInstance()->isStackEmpty($stackerName)) {
253 // This avoids an exception after all packages has failed
257 // Pop the entry (it should be it)
258 $this->getStackerInstance()->popNamed($stackerName);
260 // Temporary set the new status
261 $packageData[self::PACKAGE_DATA_STATUS] = $newStatus;
264 $this->getStackerInstance()->pushNamed($stackerName, $packageData);
267 ///////////////////////////////////////////////////////////////////////////
268 // Delivering packages / raw data
269 ///////////////////////////////////////////////////////////////////////////
272 * Delivers the given raw package data.
274 * @param $packageData Raw package data in an array
277 private function declareRawPackageData (array $packageData) {
279 * We need to disover every recipient, just in case we have a
280 * multi-recipient entry like 'upper' is. 'all' may be a not so good
281 * target because it causes an overload on the network and may be
282 * abused for attacking the network with large packages.
284 $discoveryInstance = PackageDiscoveryFactory::createPackageDiscoveryInstance();
286 // Discover all recipients, this may throw an exception
287 $discoveryInstance->discoverRecipients($packageData);
289 // Now get an iterator
290 $iteratorInstance = $discoveryInstance->getIterator();
292 // ... and begin iteration
293 while ($iteratorInstance->valid()) {
295 $currentRecipient = $iteratorInstance->current();
298 $this->debugOutput('PACKAGE: Package declared for recipient ' . $currentRecipient);
301 $packageData[self::PACKAGE_DATA_RECIPIENT] = $currentRecipient;
302 var_dump($packageData);
304 // And enqueue it to the writer class
305 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECLARED, $packageData);
307 // Skip to next entry
308 $iteratorInstance->next();
312 * The recipient list can be cleaned up here because the package which
313 * shall be delivered has already been added for all entries from the
316 $discoveryInstance->clearRecipients();
320 * Delivers raw package data. In short, this will discover the raw socket
321 * resource through a discovery class (which will analyse the receipient of
322 * the package), register the socket with the connection (handler/helper?)
323 * instance and finally push the raw data on our outgoing queue.
325 * @param $packageData Raw package data in an array
328 private function deliverRawPackageData (array $packageData) {
330 * This package may become big, depending on the shared object size or
331 * delivered message size which shouldn't be so long (to save
332 * bandwidth). Because of the nature of the used protocol (TCP) we need
333 * to split it up into smaller pieces to fit it into a TCP frame.
335 * So first we need (again) a discovery class but now a protocol
336 * discovery to choose the right socket resource. The discovery class
337 * should take a look at the raw package data itself and then decide
338 * which (configurable!) protocol should be used for that type of
341 $discoveryInstance = SocketDiscoveryFactory::createSocketDiscoveryInstance();
343 // Now discover the right protocol
344 $socketResource = $discoveryInstance->discoverSocket($packageData);
347 //* NOISY-DEBUG: */ $this->debugOutput('NETWORK-PACKAGE: Reached line ' . __LINE__ . ' after discoverSocket() has been called.');
349 // We have to put this socket in our registry, so get an instance
350 $registryInstance = SocketRegistry::createSocketRegistry();
352 // Get the listener from registry
353 $helperInstance = Registry::getRegistry()->getInstance('connection');
356 //* NOISY-DEBUG: */ $this->debugOutput('NETWORK-PACKAGE: Reached line ' . __LINE__ . ' before isSocketRegistered() has been called.');
359 if ((is_resource($socketResource)) && (!$registryInstance->isSocketRegistered($helperInstance, $socketResource))) {
361 $registryInstance->registerSocket($helperInstance, $socketResource, $packageData);
365 //* NOISY-DEBUG: */ $this->debugOutput('NETWORK-PACKAGE: Reached line ' . __LINE__ . ' after isSocketRegistered() has been called.');
367 // Make sure the connection is up
368 $helperInstance->getStateInstance()->validatePeerStateConnected();
371 //* NOISY-DEBUG: */ $this->debugOutput('NETWORK-PACKAGE: Reached line ' . __LINE__ . ' after validatePeerStateConnected() has been called.');
373 // Enqueue it again on the out-going queue, the connection is up and working at this point
374 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_OUTGOING, $packageData);
378 * Sends waiting packages
380 * @param $packageData Raw package data
383 private function sendOutgoingRawPackageData (array $packageData) {
387 // Get the right connection instance
388 $helperInstance = SocketRegistry::createSocketRegistry()->getHandlerInstanceFromPackageData($packageData);
390 // Is this connection still alive?
391 if ($helperInstance->isShuttedDown()) {
392 // This connection is shutting down
393 // @TODO We may want to do somthing more here?
397 // Sent out package data
398 $sentBytes = $helperInstance->sendRawPackageData($packageData);
400 // Remember unsent raw bytes in back-buffer, if any
401 $this->storeUnsentBytesInBackBuffer($packageData, $sentBytes);
405 * "Enqueues" raw content into this delivery class by reading the raw content
406 * from given template instance and pushing it on the 'undeclared' stack.
408 * @param $helperInstance An instance of a HelpableHub class
409 * @param $nodeInstance An instance of a NodeHelper class
412 public function enqueueRawDataFromTemplate (HelpableHub $helperInstance, NodeHelper $nodeInstance) {
413 // Get the raw content ...
414 $content = $helperInstance->getTemplateInstance()->getRawTemplateData();
416 // ... and compress it
417 $content = $this->getCompressorInstance()->compressStream($content);
419 // Add magic in front of it and hash behind it, including BASE64 encoding
420 $content = sprintf(self::PACKAGE_MASK,
421 // 1.) Compressor's extension
422 $this->getCompressorInstance()->getCompressorExtension(),
424 self::PACKAGE_MASK_SEPARATOR,
425 // 2.) Raw package content, encoded with BASE64
426 base64_encode($content),
428 self::PACKAGE_MASK_SEPARATOR,
430 implode(self::PACKAGE_TAGS_SEPARATOR, $helperInstance->getPackageTags()),
432 self::PACKAGE_MASK_SEPARATOR,
434 $this->getHashFromContent($content, $helperInstance, $nodeInstance)
437 // Now prepare the temporary array and push it on the 'undeclared' stack
438 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_UNDECLARED, array(
439 self::PACKAGE_DATA_SENDER => $nodeInstance->getSessionId(),
440 self::PACKAGE_DATA_RECIPIENT => $helperInstance->getRecipientType(),
441 self::PACKAGE_DATA_CONTENT => $content,
442 self::PACKAGE_DATA_STATUS => self::PACKAGE_STATUS_NEW
447 * Checks wether a package has been enqueued for delivery.
449 * @return $isEnqueued Wether a package is enqueued
451 public function isPackageEnqueued () {
452 // Check wether the stacker is not empty
453 $isEnqueued = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_UNDECLARED)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_UNDECLARED)));
460 * Checks wether a package has been declared
462 * @return $isDeclared Wether a package is declared
464 public function isPackageDeclared () {
465 // Check wether the stacker is not empty
466 $isDeclared = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_DECLARED)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECLARED)));
473 * Checks wether a package should be sent out
475 * @return $isWaitingDelivery Wether a package is waiting for delivery
477 public function isPackageWaitingForDelivery () {
478 // Check wether the stacker is not empty
479 $isWaitingDelivery = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_OUTGOING)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_OUTGOING)));
482 return $isWaitingDelivery;
486 * Delivers an enqueued package to the stated destination. If a non-session
487 * id is provided, recipient resolver is being asked (and instanced once).
488 * This allows that a single package is being delivered to multiple targets
489 * without enqueueing it for every target. If no target is provided or it
490 * can't be determined a NoTargetException is being thrown.
493 * @throws NoTargetException If no target can't be determined
495 public function declareEnqueuedPackage () {
496 // Make sure this method isn't working if there is no package enqueued
497 if (!$this->isPackageEnqueued()) {
498 // This is not fatal but should be avoided
499 // @TODO Add some logging here
503 // Now we know for sure there are packages to deliver, we can start
504 // with the first one.
505 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_UNDECLARED);
507 // Declare the raw package data for delivery
508 $this->declareRawPackageData($packageData);
510 // And remove it finally
511 $this->getStackerInstance()->popNamed(self::STACKER_NAME_UNDECLARED);
515 * Delivers the next declared package. Only one package per time will be sent
516 * because this may take time and slows down the whole delivery
521 public function deliverDeclaredPackage () {
522 // Sanity check if we have packages declared
523 if (!$this->isPackageDeclared()) {
524 // This is not fatal but should be avoided
525 // @TODO Add some logging here
530 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_DECLARED);
533 // And try to send it
534 $this->deliverRawPackageData($packageData);
536 // And remove it finally
537 $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECLARED);
538 } catch (InvalidStateException $e) {
539 // The state is not excepected (shall be 'connected')
540 $this->debugOutput('PACKAGE: Caught exception ' . $e->__toString() . ' with message=' . $e->getMessage());
542 // Mark the package with status failed
543 $this->changePackageStatus($packageData, self::STACKER_NAME_DECLARED, self::PACKAGE_STATUS_FAILED);
548 * Sends waiting packages out for delivery
552 public function sendWaitingPackage () {
553 // Send any waiting bytes in the back-buffer before sending a new package
554 $this->sendBackBufferBytes();
556 // Sanity check if we have packages waiting for delivery
557 if (!$this->isPackageWaitingForDelivery()) {
558 // This is not fatal but should be avoided
559 $this->debugOutput('PACKAGE: No package is waiting for delivery, but ' . __METHOD__ . ' was called.');
564 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_OUTGOING);
567 // Now try to send it
568 $this->sendOutgoingRawPackageData($packageData);
570 // And remove it finally
571 $this->getStackerInstance()->popNamed(self::STACKER_NAME_OUTGOING);
572 } catch (InvalidSocketException $e) {
573 // Output exception message
574 $this->debugOutput('PACKAGE: Package was not delivered: ' . $e->getMessage());
576 // Mark package as failed
577 $this->changePackageStatus($packageData, self::STACKER_NAME_OUTGOING, self::PACKAGE_STATUS_FAILED);
581 ///////////////////////////////////////////////////////////////////////////
582 // Receiving packages / raw data
583 ///////////////////////////////////////////////////////////////////////////
586 * Checks wether decoded raw data is pending
588 * @return $isPending Wether decoded raw data is pending
590 private function isDecodedDataPending () {
591 // Just return wether the stack is not empty
592 $isPending = (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECODED_INCOMING));
599 * Checks wether new raw package data has arrived at a socket
601 * @param $poolInstance An instance of a PoolableListener class
602 * @return $hasArrived Wether new raw package data has arrived for processing
604 public function isNewRawDataPending (PoolableListener $poolInstance) {
605 // Visit the pool. This monitors the pool for incoming raw data.
606 $poolInstance->accept($this->getVisitorInstance());
608 // Check for new data arrival
609 $hasArrived = $this->isDecodedDataPending();
616 * Handles the incoming decoded raw data. This method does not "convert" the
617 * decoded data back into a package array, it just "handles" it and pushs it
622 public function handleIncomingDecodedData () {
624 * This method should only be called if decoded raw data is pending,
627 if (!$this->isDecodedDataPending()) {
628 // This is not fatal but should be avoided
629 // @TODO Add some logging here
633 // Very noisy debug message:
634 /* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: Stacker size is ' . $this->getStackerInstance()->getStackCount(self::STACKER_NAME_DECODED_INCOMING) . ' entries.');
636 // "Pop" the next entry (the same array again) from the stack
637 $decodedData = $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECODED_INCOMING);
639 // Make sure both array elements are there
641 (is_array($decodedData)) &&
642 (isset($decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA])) &&
643 (isset($decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE]))
647 * Also make sure the error code is SOCKET_ERROR_UNHANDLED because we
648 * only want to handle unhandled packages here.
650 assert($decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE] == BaseRawDataHandler::SOCKET_ERROR_UNHANDLED);
652 // Remove the last chunk SEPARATOR (because it is being added and we don't need it)
653 if (substr($decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA], -1, 1) == PackageFragmenter::CHUNK_SEPARATOR) {
654 // It is there and should be removed
655 $decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA] = substr($decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA], 0, -1);
658 // This package is "handled" and can be pushed on the next stack
659 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECODED_HANDLED, $decodedData);
663 * Adds raw decoded data from the given handler instance to this receiver
665 * @param $handlerInstance An instance of a Networkable class
668 public function addDecodedDataToIncomingStack (Networkable $handlerInstance) {
670 * Get the decoded data from the handler, this is an array with
671 * 'decoded_data' and 'error_code' as elements.
673 $decodedData = $handlerInstance->getNextDecodedData();
675 // Very noisy debug message:
676 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: decodedData[' . gettype($decodedData) . ']=' . print_r($decodedData, true));
678 // And push it on our stack
679 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECODED_INCOMING, $decodedData);
683 * Checks wether incoming decoded data is handled.
685 * @return $isHandled Wether incoming decoded data is handled
687 public function isIncomingDecodedDataHandled () {
688 // Determine if the stack is not empty
689 $isHandled = (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECODED_HANDLED));
696 * Assembles incoming decoded data so it will become an abstract network
697 * package again. The assembler does later do it's job by an other task,
698 * not this one to keep best speed possible.
702 public function assembleDecodedDataToPackage () {
703 // Make sure the raw decoded package data is handled
704 assert($this->isIncomingDecodedDataHandled());
706 // Get current package content (an array with two elements; see handleIncomingDecodedData() for details)
707 $packageContent = $this->getStackerInstance()->getNamed(self::STACKER_NAME_DECODED_HANDLED);
709 // Get a singleton package assembler instance from factory
710 $assemblerInstance = PackageAssemblerFactory::createAssemblerInstance();
712 // Start assembling the raw package data array by chunking it
713 $assemblerInstance->chunkPackageContent($packageContent);
715 // Remove the package from 'handled_decoded' stack ...
716 $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECODED_HANDLED);
718 // ... and push it on the 'chunked' stacker
719 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECODED_CHUNKED, $packageContent);
723 * Checks wether a new package has arrived
725 * @return $hasArrived Wether a new package has arrived for processing
727 public function isNewPackageArrived () {
728 // @TODO Add some content here
732 * Accepts the visitor to process the visit "request"
734 * @param $visitorInstance An instance of a Visitor class
737 public function accept (Visitor $visitorInstance) {
739 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: ' . $visitorInstance->__toString() . ' has visited - START');
742 $visitorInstance->visitNetworkPackage($this);
745 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: ' . $visitorInstance->__toString() . ' has visited - FINISHED');
753 public function clearAllStacker () {
754 // Call the init method to force re-initialization
755 $this->initStackers(true);
758 /* DEBUG: */ $this->debugOutput('PACKAGE: All stacker have been re-initialized.');
762 * Removes the first failed outoging package from the stack to continue
763 * with next one (it will never work until the issue is fixed by you).
766 * @throws UnexpectedPackageStatusException If the package status is not 'failed'
767 * @todo This may be enchanced for outgoing packages?
769 public function removeFirstFailedPackage () {
770 // Get the package again
771 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_DECLARED);
773 // Is the package status 'failed'?
774 if ($packageData[self::PACKAGE_DATA_STATUS] != self::PACKAGE_STATUS_FAILED) {
776 throw new UnexpectedPackageStatusException(array($this, $packageData, self::PACKAGE_STATUS_FAILED), BaseListener::EXCEPTION_UNEXPECTED_PACKAGE_STATUS);
780 $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECLARED);