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 {
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_RECIPIENT = 'recipient';
78 const PACKAGE_DATA_SENDER = 'sender';
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 = 'undeclared';
97 * Stacker name for "declared" packages (which are ready to send out)
99 const STACKER_NAME_DECLARED = 'declared';
102 * Stacker name for "out-going" packages
104 const STACKER_NAME_OUTGOING = 'outgoing';
107 * Stacker name for "back-buffered" packages
109 const STACKER_NAME_BACK_BUFFER = 'backbuffer';
112 * Network target (alias): 'upper hubs'
114 const NETWORK_TARGET_UPPER_HUBS = 'upper';
117 * Network target (alias): 'self'
119 const NETWORK_TARGET_SELF = 'self';
122 * TCP package size in bytes
124 const TCP_PACKAGE_SIZE = 512;
127 * Protected constructor
131 protected function __construct () {
132 // Call parent constructor
133 parent::__construct(__CLASS__);
135 // We need to initialize a stack here for our packages even those
136 // which have no recipient address and stamp... ;-)
137 $stackerInstance = ObjectFactory::createObjectByConfiguredName('network_package_stacker_class');
139 // At last, set it in this class
140 $this->setStackerInstance($stackerInstance);
144 * Creates an instance of this class
146 * @param $compressorInstance A Compressor instance for compressing the content
147 * @return $packageInstance An instance of a Deliverable class
149 public static final function createNetworkPackage (Compressor $compressorInstance) {
151 $packageInstance = new NetworkPackage();
153 // Now set the compressor instance
154 $packageInstance->setCompressorInstance($compressorInstance);
156 // Return the prepared instance
157 return $packageInstance;
161 * "Getter" for hash from given content and helper instance
163 * @param $content Raw package content
164 * @param $helperInstance An instance of a BaseHubHelper class
165 * @param $nodeInstance An instance of a NodeHelper class
166 * @return $hash Hash for given package content
167 * @todo $helperInstance is unused
169 private function getHashFromContent ($content, BaseHubHelper $helperInstance, NodeHelper $nodeInstance) {
171 // @TODO crc32 is not very strong, but it needs to be fast
174 self::PACKAGE_CHECKSUM_SEPERATOR .
175 $nodeInstance->getSessionId() .
176 self::PACKAGE_CHECKSUM_SEPERATOR .
177 $this->getCompressorInstance()->getCompressorExtension()
184 ///////////////////////////////////////////////////////////////////////////
185 // Delivering packages / raw data
186 ///////////////////////////////////////////////////////////////////////////
189 * Delivers the given raw package data.
191 * @param $packageData Raw package data in an array
194 private function declareRawPackageData (array $packageData) {
196 * We need to disover every recipient, just in case we have a
197 * multi-recipient entry like 'upper' is. 'all' may be a not so good
198 * target because it causes an overload on the network and may be
199 * abused for attacking the network with large packages.
201 $discoveryInstance = PackageDiscoveryFactory::createPackageDiscoveryInstance();
203 // Discover all recipients, this may throw an exception
204 $discoveryInstance->discoverRecipients($packageData);
206 // Now get an iterator
207 $iteratorInstance = $discoveryInstance->getIterator();
209 // ... and begin iteration
210 while ($iteratorInstance->valid()) {
212 $currentRecipient = $iteratorInstance->current();
215 $this->debugOutput('PACKAGE: Package declared for recipient ' . $currentRecipient);
218 $packageData[self::PACKAGE_DATA_RECIPIENT] = $currentRecipient;
220 // And enqueue it to the writer class
221 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECLARED, $packageData);
223 // Skip to next entry
224 $iteratorInstance->next();
228 $discoveryInstance->clearRecipients();
232 * Delivers raw package data. In short, this will discover the raw socket
233 * resource through a discovery class (which will analyse the receipient of
234 * the package), register the socket with the connection (handler/helper?)
235 * instance and finally push the raw data on our outgoing queue.
237 * @param $packageData Raw package data in an array
240 private function deliverRawPackageData (array $packageData) {
242 * This package may become big, depending on the shared object size or
243 * delivered message size which shouldn't be so long (to save
244 * bandwidth). Because of the nature of the used protocol (TCP) we need
245 * to split it up into smaller pieces to fit it into a TCP frame.
247 * So first we need (again) a discovery class but now a protocol
248 * discovery to choose the right socket resource. The discovery class
249 * should take a look at the raw package data itself and then decide
250 * which (configurable!) protocol should be used for that type of
253 $discoveryInstance = SocketDiscoveryFactory::createSocketDiscoveryInstance();
255 // Now discover the right protocol
256 $socketResource = $discoveryInstance->discoverSocket($packageData);
258 // We have to put this socket in our registry, so get an instance
259 $registryInstance = SocketRegistry::createSocketRegistry();
261 // Get the listener from registry
262 $connectionInstance = Registry::getRegistry()->getInstance('connection');
265 if (!$registryInstance->isSocketRegistered($connectionInstance, $socketResource)) {
267 $registryInstance->registerSocket($connectionInstance, $socketResource, $packageData);
270 // We enqueue it again, but now in the out-going queue
271 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_OUTGOING, $packageData);
275 * Sends waiting packages
277 * @param $packageData Raw package data
280 private function sendOutgoingRawPackageData (array $packageData) {
281 // Get the right connection instance
282 $connectionInstance = SocketRegistry::createSocketRegistry()->getHandlerInstanceFromPackageData($packageData);
284 // Is this connection still alive?
285 if ($connectionInstance->isShuttedDown()) {
286 // This connection is shutting down
287 // @TODO We may want to do somthing more here?
291 // Sent it away (we catch exceptions one method above)
292 $sentBytes = $connectionInstance->sendRawPackageData($packageData);
294 // Remember unsent raw bytes in back-buffer, if any
295 $this->storeUnsentBytesInBackBuffer($packageData, $sentBytes);
299 * "Enqueues" raw content into this delivery class by reading the raw content
300 * from given template instance and pushing it on the 'undeclared' stack.
302 * @param $helperInstance An instance of a BaseHubHelper class
303 * @param $nodeInstance An instance of a NodeHelper class
306 public function enqueueRawDataFromTemplate (BaseHubHelper $helperInstance, NodeHelper $nodeInstance) {
307 // Get the raw content ...
308 $content = $helperInstance->getTemplateInstance()->getRawTemplateData();
310 // ... and compress it
311 $content = $this->getCompressorInstance()->compressStream($content);
313 // Add magic in front of it and hash behind it, including BASE64 encoding
314 $content = sprintf(self::PACKAGE_MASK,
315 // 1.) Compressor's extension
316 $this->getCompressorInstance()->getCompressorExtension(),
317 // 2.) Raw package content, encoded with BASE64
318 base64_encode($content),
320 implode(self::PACKAGE_TAGS_SEPERATOR, $helperInstance->getPackageTags()),
322 $this->getHashFromContent($content, $helperInstance, $nodeInstance)
325 // Now prepare the temporary array and push it on the 'undeclared' stack
326 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_UNDECLARED, array(
327 self::PACKAGE_DATA_SENDER => $nodeInstance->getSessionId(),
328 self::PACKAGE_DATA_RECIPIENT => $helperInstance->getRecipientType(),
329 self::PACKAGE_DATA_CONTENT => $content,
334 * Checks wether a package has been enqueued for delivery.
336 * @return $isEnqueued Wether a package is enqueued
338 public function isPackageEnqueued () {
339 // Check wether the stacker is not empty
340 $isEnqueued = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_UNDECLARED)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_UNDECLARED)));
347 * Checks wether a package has been declared
349 * @return $isDeclared Wether a package is declared
351 public function isPackageDeclared () {
352 // Check wether the stacker is not empty
353 $isDeclared = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_DECLARED)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECLARED)));
360 * Checks wether a package should be sent out
362 * @return $isWaitingDelivery Wether a package is waiting for delivery
364 public function isPackageWaitingForDelivery () {
365 // Check wether the stacker is not empty
366 $isWaitingDelivery = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_OUTGOING)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_OUTGOING)));
369 return $isWaitingDelivery;
373 * Delivers an enqueued package to the stated destination. If a non-session
374 * id is provided, recipient resolver is being asked (and instanced once).
375 * This allows that a single package is being delivered to multiple targets
376 * without enqueueing it for every target. If no target is provided or it
377 * can't be determined a NoTargetException is being thrown.
380 * @throws NoTargetException If no target can't be determined
382 public function declareEnqueuedPackage () {
383 // Make sure this method isn't working if there is no package enqueued
384 if (!$this->isPackageEnqueued()) {
385 // This is not fatal but should be avoided
386 // @TODO Add some logging here
390 // Now we know for sure there are packages to deliver, we can start
391 // with the first one.
392 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_UNDECLARED);
394 // Declare the raw package data for delivery
395 $this->declareRawPackageData($packageData);
397 // And remove it finally
398 $this->getStackerInstance()->popNamed(self::STACKER_NAME_UNDECLARED);
402 * Delivers the next declared package. Only one package per time will be sent
403 * because this may take time and slows down the whole delivery
408 public function deliverDeclaredPackage () {
409 // Sanity check if we have packages declared
410 if (!$this->isPackageDeclared()) {
411 // This is not fatal but should be avoided
412 // @TODO Add some logging here
416 // Get the package again
417 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_DECLARED);
420 $this->deliverRawPackageData($packageData);
422 // And remove it finally
423 $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECLARED);
427 * Sends waiting packages out for delivery
431 public function sendWaitingPackage () {
432 // Send any waiting bytes in the back-buffer before sending a new package
433 $this->sendBackBufferBytes();
435 // Sanity check if we have packages waiting for delivery
436 if (!$this->isPackageWaitingForDelivery()) {
437 // This is not fatal but should be avoided
438 $this->debugOutput('PACKAGE: No package is waiting for delivery, but ' . __FUNCTION__ . ' was called.');
442 // Get the package again
443 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_OUTGOING);
446 // Now try to send it
447 $this->sendOutgoingRawPackageData($packageData);
449 // And remove it finally
450 $this->getStackerInstance()->popNamed(self::STACKER_NAME_OUTGOING);
451 } catch (InvalidSocketException $e) {
452 // Output exception message
453 $this->debugOutput('PACKAGE: Package was not delivered: ' . $e->getMessage());
457 ///////////////////////////////////////////////////////////////////////////
458 // Receiving packages / raw data
459 ///////////////////////////////////////////////////////////////////////////
462 * Checks wether new raw package data has arrived at a socket
464 * @return $hasArrived Wether new raw package data has arrived for processing
466 public function isNewRawDataPending () {
467 // @TODO Add some content here
471 * Checks wether a new package has arrived
473 * @return $hasArrived Wether a new package has arrived for processing
475 public function isNewPackageArrived () {
476 // @TODO Add some content here