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;
75 * Named array elements for package data
77 const PACKAGE_DATA_SENDER = 'sender';
78 const PACKAGE_DATA_RECIPIENT = 'recipient';
79 const PACKAGE_DATA_CONTENT = 'content';
84 const PACKAGE_TAGS_SEPERATOR = ';';
87 * Raw package data seperator
89 const PACKAGE_DATA_SEPERATOR = '#';
92 * Stacker name for "undeclared" packages
94 const STACKER_NAME_UNDECLARED = 'package_undeclared';
97 * Stacker name for "declared" packages (which are ready to send out)
99 const STACKER_NAME_DECLARED = 'package_declared';
102 * Stacker name for "out-going" packages
104 const STACKER_NAME_OUTGOING = 'package_outgoing';
107 * Stacker name for "incoming" decoded raw data
109 const STACKER_NAME_DECODED_INCOMING = 'package_decoded_data';
112 * Stacker name for handled decoded raw data
114 const STACKER_NAME_DECODED_HANDLED = 'package_handled_decoded';
117 * Stacker name for "back-buffered" packages
119 const STACKER_NAME_BACK_BUFFER = 'package_backbuffer';
122 * Network target (alias): 'upper hubs'
124 const NETWORK_TARGET_UPPER_HUBS = 'upper';
127 * Network target (alias): 'self'
129 const NETWORK_TARGET_SELF = 'self';
132 * TCP package size in bytes
134 const TCP_PACKAGE_SIZE = 512;
137 * Protected constructor
141 protected function __construct () {
142 // Call parent constructor
143 parent::__construct(__CLASS__);
147 * Creates an instance of this class
149 * @param $compressorInstance A Compressor instance for compressing the content
150 * @return $packageInstance An instance of a Deliverable class
152 public static final function createNetworkPackage (Compressor $compressorInstance) {
154 $packageInstance = new NetworkPackage();
156 // Now set the compressor instance
157 $packageInstance->setCompressorInstance($compressorInstance);
160 * We need to initialize a stack here for our packages even for those
161 * which have no recipient address and stamp... ;-) This stacker will
162 * also be used for incoming raw data to handle it.
164 $stackerInstance = ObjectFactory::createObjectByConfiguredName('network_package_stacker_class');
166 // At last, set it in this class
167 $packageInstance->setStackerInstance($stackerInstance);
170 $packageInstance->initStackers();
172 // Get a visitor instance for speeding up things
173 $visitorInstance = ObjectFactory::createObjectByConfiguredName('node_raw_data_monitor_visitor_class', array($packageInstance));
175 // Set it in this package
176 $packageInstance->setVisitorInstance($visitorInstance);
178 // Return the prepared instance
179 return $packageInstance;
183 * Initialize all stackers
187 protected function initStackers () {
191 self::STACKER_NAME_UNDECLARED,
192 self::STACKER_NAME_DECLARED,
193 self::STACKER_NAME_OUTGOING,
194 self::STACKER_NAME_DECODED_INCOMING,
195 self::STACKER_NAME_DECODED_HANDLED,
196 self::STACKER_NAME_BACK_BUFFER
199 $this->getStackerInstance()->initStacker($stackerName);
204 * "Getter" for hash from given content and helper instance
206 * @param $content Raw package content
207 * @param $helperInstance An instance of a HelpableHub class
208 * @param $nodeInstance An instance of a NodeHelper class
209 * @return $hash Hash for given package content
210 * @todo $helperInstance is unused
212 private function getHashFromContent ($content, HelpableHub $helperInstance, NodeHelper $nodeInstance) {
214 // @TODO crc32() is not very strong, but it needs to be fast
217 self::PACKAGE_CHECKSUM_SEPERATOR .
218 $nodeInstance->getSessionId() .
219 self::PACKAGE_CHECKSUM_SEPERATOR .
220 $this->getCompressorInstance()->getCompressorExtension()
227 ///////////////////////////////////////////////////////////////////////////
228 // Delivering packages / raw data
229 ///////////////////////////////////////////////////////////////////////////
232 * Delivers the given raw package data.
234 * @param $packageData Raw package data in an array
237 private function declareRawPackageData (array $packageData) {
239 * We need to disover every recipient, just in case we have a
240 * multi-recipient entry like 'upper' is. 'all' may be a not so good
241 * target because it causes an overload on the network and may be
242 * abused for attacking the network with large packages.
244 $discoveryInstance = PackageDiscoveryFactory::createPackageDiscoveryInstance();
246 // Discover all recipients, this may throw an exception
247 $discoveryInstance->discoverRecipients($packageData);
249 // Now get an iterator
250 $iteratorInstance = $discoveryInstance->getIterator();
252 // ... and begin iteration
253 while ($iteratorInstance->valid()) {
255 $currentRecipient = $iteratorInstance->current();
258 $this->debugOutput('PACKAGE: Package declared for recipient ' . $currentRecipient);
261 $packageData[self::PACKAGE_DATA_RECIPIENT] = $currentRecipient;
263 // And enqueue it to the writer class
264 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECLARED, $packageData);
266 // Skip to next entry
267 $iteratorInstance->next();
271 * The recipient list can be cleaned up here because the package which
272 * shall be delivered has already been added for all entries from the
275 $discoveryInstance->clearRecipients();
279 * Delivers raw package data. In short, this will discover the raw socket
280 * resource through a discovery class (which will analyse the receipient of
281 * the package), register the socket with the connection (handler/helper?)
282 * instance and finally push the raw data on our outgoing queue.
284 * @param $packageData Raw package data in an array
287 private function deliverRawPackageData (array $packageData) {
289 * This package may become big, depending on the shared object size or
290 * delivered message size which shouldn't be so long (to save
291 * bandwidth). Because of the nature of the used protocol (TCP) we need
292 * to split it up into smaller pieces to fit it into a TCP frame.
294 * So first we need (again) a discovery class but now a protocol
295 * discovery to choose the right socket resource. The discovery class
296 * should take a look at the raw package data itself and then decide
297 * which (configurable!) protocol should be used for that type of
300 $discoveryInstance = SocketDiscoveryFactory::createSocketDiscoveryInstance();
302 // Now discover the right protocol
303 $socketResource = $discoveryInstance->discoverSocket($packageData);
306 //* NOISY-DEBUG: */ $this->debugOutput('NETWORK-PACKAGE: Reached line ' . __LINE__ . ' after discoverSocket() has been called.');
308 // We have to put this socket in our registry, so get an instance
309 $registryInstance = SocketRegistry::createSocketRegistry();
311 // Get the listener from registry
312 $helperInstance = Registry::getRegistry()->getInstance('connection');
315 //* NOISY-DEBUG: */ $this->debugOutput('NETWORK-PACKAGE: Reached line ' . __LINE__ . ' before isSocketRegistered() has been called.');
318 if ((is_resource($socketResource)) && (!$registryInstance->isSocketRegistered($helperInstance, $socketResource))) {
320 $registryInstance->registerSocket($helperInstance, $socketResource, $packageData);
324 //* NOISY-DEBUG: */ $this->debugOutput('NETWORK-PACKAGE: Reached line ' . __LINE__ . ' after isSocketRegistered() has been called.');
326 // Make sure the connection is up
327 $helperInstance->getStateInstance()->validatePeerStateConnected();
330 //* NOISY-DEBUG: */ $this->debugOutput('NETWORK-PACKAGE: Reached line ' . __LINE__ . ' after validatePeerStateConnected() has been called.');
332 // We enqueue it again, but now in the out-going queue
333 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_OUTGOING, $packageData);
337 * Sends waiting packages
339 * @param $packageData Raw package data
342 private function sendOutgoingRawPackageData (array $packageData) {
346 // Get the right connection instance
347 $helperInstance = SocketRegistry::createSocketRegistry()->getHandlerInstanceFromPackageData($packageData);
349 // Is this connection still alive?
350 if ($helperInstance->isShuttedDown()) {
351 // This connection is shutting down
352 // @TODO We may want to do somthing more here?
356 // Sent out package data
357 $sentBytes = $helperInstance->sendRawPackageData($packageData);
359 // Remember unsent raw bytes in back-buffer, if any
360 $this->storeUnsentBytesInBackBuffer($packageData, $sentBytes);
364 * "Enqueues" raw content into this delivery class by reading the raw content
365 * from given template instance and pushing it on the 'undeclared' stack.
367 * @param $helperInstance An instance of a HelpableHub class
368 * @param $nodeInstance An instance of a NodeHelper class
371 public function enqueueRawDataFromTemplate (HelpableHub $helperInstance, NodeHelper $nodeInstance) {
372 // Get the raw content ...
373 $content = $helperInstance->getTemplateInstance()->getRawTemplateData();
375 // ... and compress it
376 $content = $this->getCompressorInstance()->compressStream($content);
378 // Add magic in front of it and hash behind it, including BASE64 encoding
379 $content = sprintf(self::PACKAGE_MASK,
380 // 1.) Compressor's extension
381 $this->getCompressorInstance()->getCompressorExtension(),
382 // 2.) Raw package content, encoded with BASE64
383 base64_encode($content),
385 implode(self::PACKAGE_TAGS_SEPERATOR, $helperInstance->getPackageTags()),
387 $this->getHashFromContent($content, $helperInstance, $nodeInstance)
390 // Now prepare the temporary array and push it on the 'undeclared' stack
391 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_UNDECLARED, array(
392 self::PACKAGE_DATA_SENDER => $nodeInstance->getSessionId(),
393 self::PACKAGE_DATA_RECIPIENT => $helperInstance->getRecipientType(),
394 self::PACKAGE_DATA_CONTENT => $content,
399 * Checks wether a package has been enqueued for delivery.
401 * @return $isEnqueued Wether a package is enqueued
403 public function isPackageEnqueued () {
404 // Check wether the stacker is not empty
405 $isEnqueued = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_UNDECLARED)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_UNDECLARED)));
412 * Checks wether a package has been declared
414 * @return $isDeclared Wether a package is declared
416 public function isPackageDeclared () {
417 // Check wether the stacker is not empty
418 $isDeclared = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_DECLARED)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECLARED)));
425 * Checks wether a package should be sent out
427 * @return $isWaitingDelivery Wether a package is waiting for delivery
429 public function isPackageWaitingForDelivery () {
430 // Check wether the stacker is not empty
431 $isWaitingDelivery = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_OUTGOING)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_OUTGOING)));
434 return $isWaitingDelivery;
438 * Delivers an enqueued package to the stated destination. If a non-session
439 * id is provided, recipient resolver is being asked (and instanced once).
440 * This allows that a single package is being delivered to multiple targets
441 * without enqueueing it for every target. If no target is provided or it
442 * can't be determined a NoTargetException is being thrown.
445 * @throws NoTargetException If no target can't be determined
447 public function declareEnqueuedPackage () {
448 // Make sure this method isn't working if there is no package enqueued
449 if (!$this->isPackageEnqueued()) {
450 // This is not fatal but should be avoided
451 // @TODO Add some logging here
455 // Now we know for sure there are packages to deliver, we can start
456 // with the first one.
457 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_UNDECLARED);
459 // Declare the raw package data for delivery
460 $this->declareRawPackageData($packageData);
462 // And remove it finally
463 $this->getStackerInstance()->popNamed(self::STACKER_NAME_UNDECLARED);
467 * Delivers the next declared package. Only one package per time will be sent
468 * because this may take time and slows down the whole delivery
473 public function deliverDeclaredPackage () {
474 // Sanity check if we have packages declared
475 if (!$this->isPackageDeclared()) {
476 // This is not fatal but should be avoided
477 // @TODO Add some logging here
481 // Get the package again
482 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_DECLARED);
485 // And try to send it
486 $this->deliverRawPackageData($packageData);
488 // And remove it finally
489 $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECLARED);
490 } catch (InvalidStateException $e) {
491 // The state is not excepected (shall be 'connected')
492 $this->debugOutput('PACKAGE: Caught exception ' . $e->__toString() . ' with message=' . $e->getMessage());
497 * Sends waiting packages out for delivery
501 public function sendWaitingPackage () {
502 // Send any waiting bytes in the back-buffer before sending a new package
503 $this->sendBackBufferBytes();
505 // Sanity check if we have packages waiting for delivery
506 if (!$this->isPackageWaitingForDelivery()) {
507 // This is not fatal but should be avoided
508 $this->debugOutput('PACKAGE: No package is waiting for delivery, but ' . __METHOD__ . ' was called.');
512 // Get the package again
513 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_OUTGOING);
516 // Now try to send it
517 $this->sendOutgoingRawPackageData($packageData);
519 // And remove it finally
520 $this->getStackerInstance()->popNamed(self::STACKER_NAME_OUTGOING);
521 } catch (InvalidSocketException $e) {
522 // Output exception message
523 $this->debugOutput('PACKAGE: Package was not delivered: ' . $e->getMessage());
527 ///////////////////////////////////////////////////////////////////////////
528 // Receiving packages / raw data
529 ///////////////////////////////////////////////////////////////////////////
532 * Checks wether decoded raw data is pending
534 * @return $isPending Wether decoded raw data is pending
536 private function isDecodedDataPending () {
537 // Just return wether the stack is not empty
538 $isPending = (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECODED_INCOMING));
545 * Checks wether new raw package data has arrived at a socket
547 * @param $poolInstance An instance of a PoolableListener class
548 * @return $hasArrived Wether new raw package data has arrived for processing
550 public function isNewRawDataPending (PoolableListener $poolInstance) {
551 // Visit the pool. This monitors the pool for incoming raw data.
552 $poolInstance->accept($this->getVisitorInstance());
554 // Check for new data arrival
555 $hasArrived = $this->isDecodedDataPending();
562 * Handles the incoming decoded raw data. This method does not "convert" the
563 * decoded data back into a package array, it just "handles" it and pushs it
568 public function handleIncomingDecodedData () {
570 * This method should only be called if decoded raw data is pending,
573 if (!$this->isDecodedDataPending()) {
574 // This is not fatal but should be avoided
575 // @TODO Add some logging here
579 // Very noisy debug message:
580 /* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: Stacker size is ' . $this->getStackerInstance()->getStackCount(self::STACKER_NAME_DECODED_INCOMING) . ' entries.');
582 // "Pop" the next entry (the same array again) from the stack
583 $decodedData = $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECODED_INCOMING);
585 // Make sure both array elements are there
586 assert((is_array($decodedData)) && (isset($decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA])) && (isset($decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE])));
589 * Also make sure the error code is SOCKET_ERROR_UNHANDLED because we
590 * only want to handle unhandled packages here.
592 assert($decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE] == BaseRawDataHandler::SOCKET_ERROR_UNHANDLED);
594 // Remove the last chunk seperator (because it is being added and we don't need it)
595 if (substr($decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA], -1, 1) == PackageFragmenter::CHUNK_SEPERATOR) {
596 // It is there and should be removed
597 $decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA] = substr($decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA], 0, -1);
600 // This package is "handled" and can be pushed on the next stack
601 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECODED_HANDLED, $decodedData);
605 * Adds raw decoded data from the given handler instance to this receiver
607 * @param $handlerInstance An instance of a Networkable class
610 public function addDecodedDataToIncomingStack (Networkable $handlerInstance) {
612 * Get the decoded data from the handler, this is an array with
613 * 'decoded_data' and 'error_code' as elements.
615 $decodedData = $handlerInstance->getNextDecodedData();
617 // Very noisy debug message:
618 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: decodedData[' . gettype($decodedData) . ']=' . print_r($decodedData, true));
620 // And push it on our stack
621 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECODED_INCOMING, $decodedData);
625 * Checks wether incoming decoded data is handled.
627 * @return $isHandled Wether incoming decoded data is handled
629 public function isIncomingDecodedDataHandled () {
630 // Determine if the stack is not empty
631 $isHandled = (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECODED_HANDLED));
638 * Assembles incoming decoded data so it will become an abstract network
643 public function assembleDecodedDataToPackage () {
644 $this->partialStub('Please implement this method.');
648 * Checks wether a new package has arrived
650 * @return $hasArrived Wether a new package has arrived for processing
652 public function isNewPackageArrived () {
653 // @TODO Add some content here
657 * Accepts the visitor to process the visit "request"
659 * @param $visitorInstance An instance of a Visitor class
662 public function accept (Visitor $visitorInstance) {
664 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: ' . $visitorInstance->__toString() . ' has visited - START');
667 $visitorInstance->visitNetworkPackage($this);
670 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: ' . $visitorInstance->__toString() . ' has visited - FINISHED');
678 public function clearAllStacker () {
679 // Do the cleanup (no flushing)
682 self::STACKER_NAME_UNDECLARED,
683 self::STACKER_NAME_DECLARED,
684 self::STACKER_NAME_OUTGOING,
685 self::STACKER_NAME_DECODED_INCOMING,
686 self::STACKER_NAME_DECODED_HANDLED,
687 self::STACKER_NAME_BACK_BUFFER
689 // Clear this stacker by forcing an init
690 $this->getStackerInstance()->initStacker($stackerName, true);
694 /* DEBUG: */ $this->debugOutput('PACKAGE: All stacker have been re-initialized.');