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__);
137 * Creates an instance of this class
139 * @param $compressorInstance A Compressor instance for compressing the content
140 * @return $packageInstance An instance of a Deliverable class
142 public static final function createNetworkPackage (Compressor $compressorInstance) {
144 $packageInstance = new NetworkPackage();
146 // Now set the compressor instance
147 $packageInstance->setCompressorInstance($compressorInstance);
149 // We need to initialize a stack here for our packages even those
150 // which have no recipient address and stamp... ;-)
151 $stackerInstance = ObjectFactory::createObjectByConfiguredName('network_package_stacker_class');
153 // At last, set it in this class
154 $packageInstance->setStackerInstance($stackerInstance);
156 // Get a visitor instance for speeding up things
157 $visitorInstance = ObjectFactory::createObjectByConfiguredName('node_raw_data_monitor_visitor_class', array($packageInstance));
159 // Set it in this package
160 $packageInstance->setVisitorInstance($visitorInstance);
162 // Return the prepared instance
163 return $packageInstance;
167 * "Getter" for hash from given content and helper instance
169 * @param $content Raw package content
170 * @param $helperInstance An instance of a BaseHubHelper class
171 * @param $nodeInstance An instance of a NodeHelper class
172 * @return $hash Hash for given package content
173 * @todo $helperInstance is unused
175 private function getHashFromContent ($content, BaseHubHelper $helperInstance, NodeHelper $nodeInstance) {
177 // @TODO crc32 is not very strong, but it needs to be fast
180 self::PACKAGE_CHECKSUM_SEPERATOR .
181 $nodeInstance->getSessionId() .
182 self::PACKAGE_CHECKSUM_SEPERATOR .
183 $this->getCompressorInstance()->getCompressorExtension()
190 ///////////////////////////////////////////////////////////////////////////
191 // Delivering packages / raw data
192 ///////////////////////////////////////////////////////////////////////////
195 * Delivers the given raw package data.
197 * @param $packageData Raw package data in an array
200 private function declareRawPackageData (array $packageData) {
202 * We need to disover every recipient, just in case we have a
203 * multi-recipient entry like 'upper' is. 'all' may be a not so good
204 * target because it causes an overload on the network and may be
205 * abused for attacking the network with large packages.
207 $discoveryInstance = PackageDiscoveryFactory::createPackageDiscoveryInstance();
209 // Discover all recipients, this may throw an exception
210 $discoveryInstance->discoverRecipients($packageData);
212 // Now get an iterator
213 $iteratorInstance = $discoveryInstance->getIterator();
215 // ... and begin iteration
216 while ($iteratorInstance->valid()) {
218 $currentRecipient = $iteratorInstance->current();
221 $this->debugOutput('PACKAGE: Package declared for recipient ' . $currentRecipient);
224 $packageData[self::PACKAGE_DATA_RECIPIENT] = $currentRecipient;
226 // And enqueue it to the writer class
227 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECLARED, $packageData);
229 // Skip to next entry
230 $iteratorInstance->next();
234 $discoveryInstance->clearRecipients();
238 * Delivers raw package data. In short, this will discover the raw socket
239 * resource through a discovery class (which will analyse the receipient of
240 * the package), register the socket with the connection (handler/helper?)
241 * instance and finally push the raw data on our outgoing queue.
243 * @param $packageData Raw package data in an array
246 private function deliverRawPackageData (array $packageData) {
248 * This package may become big, depending on the shared object size or
249 * delivered message size which shouldn't be so long (to save
250 * bandwidth). Because of the nature of the used protocol (TCP) we need
251 * to split it up into smaller pieces to fit it into a TCP frame.
253 * So first we need (again) a discovery class but now a protocol
254 * discovery to choose the right socket resource. The discovery class
255 * should take a look at the raw package data itself and then decide
256 * which (configurable!) protocol should be used for that type of
259 $discoveryInstance = SocketDiscoveryFactory::createSocketDiscoveryInstance();
261 // Now discover the right protocol
262 $socketResource = $discoveryInstance->discoverSocket($packageData);
264 // We have to put this socket in our registry, so get an instance
265 $registryInstance = SocketRegistry::createSocketRegistry();
267 // Get the listener from registry
268 $connectionInstance = Registry::getRegistry()->getInstance('connection');
271 if (!$registryInstance->isSocketRegistered($connectionInstance, $socketResource)) {
273 $registryInstance->registerSocket($connectionInstance, $socketResource, $packageData);
276 // We enqueue it again, but now in the out-going queue
277 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_OUTGOING, $packageData);
281 * Sends waiting packages
283 * @param $packageData Raw package data
286 private function sendOutgoingRawPackageData (array $packageData) {
287 // Get the right connection instance
288 $connectionInstance = SocketRegistry::createSocketRegistry()->getHandlerInstanceFromPackageData($packageData);
290 // Is this connection still alive?
291 if ($connectionInstance->isShuttedDown()) {
292 // This connection is shutting down
293 // @TODO We may want to do somthing more here?
297 // Sent it away (we catch exceptions one method above)
298 $sentBytes = $connectionInstance->sendRawPackageData($packageData);
300 // Remember unsent raw bytes in back-buffer, if any
301 $this->storeUnsentBytesInBackBuffer($packageData, $sentBytes);
305 * "Enqueues" raw content into this delivery class by reading the raw content
306 * from given template instance and pushing it on the 'undeclared' stack.
308 * @param $helperInstance An instance of a BaseHubHelper class
309 * @param $nodeInstance An instance of a NodeHelper class
312 public function enqueueRawDataFromTemplate (BaseHubHelper $helperInstance, NodeHelper $nodeInstance) {
313 // Get the raw content ...
314 $content = $helperInstance->getTemplateInstance()->getRawTemplateData();
316 // ... and compress it
317 $content = $this->getCompressorInstance()->compressStream($content);
319 // Add magic in front of it and hash behind it, including BASE64 encoding
320 $content = sprintf(self::PACKAGE_MASK,
321 // 1.) Compressor's extension
322 $this->getCompressorInstance()->getCompressorExtension(),
323 // 2.) Raw package content, encoded with BASE64
324 base64_encode($content),
326 implode(self::PACKAGE_TAGS_SEPERATOR, $helperInstance->getPackageTags()),
328 $this->getHashFromContent($content, $helperInstance, $nodeInstance)
331 // Now prepare the temporary array and push it on the 'undeclared' stack
332 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_UNDECLARED, array(
333 self::PACKAGE_DATA_SENDER => $nodeInstance->getSessionId(),
334 self::PACKAGE_DATA_RECIPIENT => $helperInstance->getRecipientType(),
335 self::PACKAGE_DATA_CONTENT => $content,
340 * Checks wether a package has been enqueued for delivery.
342 * @return $isEnqueued Wether a package is enqueued
344 public function isPackageEnqueued () {
345 // Check wether the stacker is not empty
346 $isEnqueued = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_UNDECLARED)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_UNDECLARED)));
353 * Checks wether a package has been declared
355 * @return $isDeclared Wether a package is declared
357 public function isPackageDeclared () {
358 // Check wether the stacker is not empty
359 $isDeclared = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_DECLARED)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECLARED)));
366 * Checks wether a package should be sent out
368 * @return $isWaitingDelivery Wether a package is waiting for delivery
370 public function isPackageWaitingForDelivery () {
371 // Check wether the stacker is not empty
372 $isWaitingDelivery = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_OUTGOING)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_OUTGOING)));
375 return $isWaitingDelivery;
379 * Delivers an enqueued package to the stated destination. If a non-session
380 * id is provided, recipient resolver is being asked (and instanced once).
381 * This allows that a single package is being delivered to multiple targets
382 * without enqueueing it for every target. If no target is provided or it
383 * can't be determined a NoTargetException is being thrown.
386 * @throws NoTargetException If no target can't be determined
388 public function declareEnqueuedPackage () {
389 // Make sure this method isn't working if there is no package enqueued
390 if (!$this->isPackageEnqueued()) {
391 // This is not fatal but should be avoided
392 // @TODO Add some logging here
396 // Now we know for sure there are packages to deliver, we can start
397 // with the first one.
398 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_UNDECLARED);
400 // Declare the raw package data for delivery
401 $this->declareRawPackageData($packageData);
403 // And remove it finally
404 $this->getStackerInstance()->popNamed(self::STACKER_NAME_UNDECLARED);
408 * Delivers the next declared package. Only one package per time will be sent
409 * because this may take time and slows down the whole delivery
414 public function deliverDeclaredPackage () {
415 // Sanity check if we have packages declared
416 if (!$this->isPackageDeclared()) {
417 // This is not fatal but should be avoided
418 // @TODO Add some logging here
422 // Get the package again
423 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_DECLARED);
426 $this->deliverRawPackageData($packageData);
428 // And remove it finally
429 $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECLARED);
433 * Sends waiting packages out for delivery
437 public function sendWaitingPackage () {
438 // Send any waiting bytes in the back-buffer before sending a new package
439 $this->sendBackBufferBytes();
441 // Sanity check if we have packages waiting for delivery
442 if (!$this->isPackageWaitingForDelivery()) {
443 // This is not fatal but should be avoided
444 $this->debugOutput('PACKAGE: No package is waiting for delivery, but ' . __METHOD__ . ' was called.');
448 // Get the package again
449 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_OUTGOING);
452 // Now try to send it
453 $this->sendOutgoingRawPackageData($packageData);
455 // And remove it finally
456 $this->getStackerInstance()->popNamed(self::STACKER_NAME_OUTGOING);
457 } catch (InvalidSocketException $e) {
458 // Output exception message
459 $this->debugOutput('PACKAGE: Package was not delivered: ' . $e->getMessage());
463 ///////////////////////////////////////////////////////////////////////////
464 // Receiving packages / raw data
465 ///////////////////////////////////////////////////////////////////////////
468 * Checks wether new raw package data has arrived at a socket
470 * @param $poolInstance An instance of a PoolableListener class
471 * @return $hasArrived Wether new raw package data has arrived for processing
473 public function isNewRawDataPending (PoolableListener $poolInstance) {
474 // By default no new data has arrived
478 $poolInstance->accept($this->getVisitorInstance());
479 // @TODO Check for if new data has arrived
486 * Checks wether a new package has arrived
488 * @return $hasArrived Wether a new package has arrived for processing
490 public function isNewPackageArrived () {
491 // @TODO Add some content here