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 * Array indexes for above mask, start with zero
57 const INDEX_COMPRESSOR_EXTENSION = 0;
58 const INDEX_PACKAGE_DATA = 1;
60 const INDEX_CHECKSUM = 3;
63 * Array indexes for raw package array
65 const INDEX_PACKAGE_SENDER = 0;
66 const INDEX_PACKAGE_RECIPIENT = 1;
67 const INDEX_PACKAGE_CONTENT = 2;
72 const PACKAGE_TAGS_SEPERATOR = ';';
75 * Raw package data seperator
77 const PACKAGE_DATA_SEPERATOR = '|';
80 * Stacker name for "undeclared" packages
82 const STACKER_NAME_UNDECLARED = 'undeclared';
85 * Stacker name for "declared" packages (which are ready to send out)
87 const STACKER_NAME_DECLARED = 'declared';
90 * Stacker name for "out-going" packages
92 const STACKER_NAME_OUTGOING = 'outgoing';
95 * Stacker name for "back-buffered" packages
97 const STACKER_NAME_BACK_BUFFER = 'backbuffer';
100 * Network target (alias): 'upper hubs'
102 const NETWORK_TARGET_UPPER_HUBS = 'upper';
105 * Network target (alias): 'self'
107 const NETWORK_TARGET_SELF = 'self';
110 * TCP package size in bytes
112 const TCP_PACKAGE_SIZE = 512;
115 * Protected constructor
119 protected function __construct () {
120 // Call parent constructor
121 parent::__construct(__CLASS__);
123 // We need to initialize a stack here for our packages even those
124 // which have no recipient address and stamp... ;-)
125 $stackerInstance = ObjectFactory::createObjectByConfiguredName('network_package_stacker_class');
127 // At last, set it in this class
128 $this->setStackerInstance($stackerInstance);
132 * Creates an instance of this class
134 * @param $compressorInstance A Compressor instance for compressing the content
135 * @return $packageInstance An instance of a Deliverable class
137 public static final function createNetworkPackage (Compressor $compressorInstance) {
139 $packageInstance = new NetworkPackage();
141 // Now set the compressor instance
142 $packageInstance->setCompressorInstance($compressorInstance);
144 // Return the prepared instance
145 return $packageInstance;
149 * "Getter" for hash from given content and helper instance
151 * @param $content Raw package content
152 * @param $helperInstance An instance of a BaseHubHelper class
153 * @param $nodeInstance An instance of a NodeHelper class
154 * @return $hash Hash for given package content
156 private function getHashFromContent ($content, BaseHubHelper $helperInstance, NodeHelper $nodeInstance) {
158 // @TODO crc32 is not good, but it needs to be fast
162 $nodeInstance->getSessionId() .
164 $this->getCompressorInstance()->getCompressorExtension()
171 ///////////////////////////////////////////////////////////////////////////
172 // Delivering packages / raw data
173 ///////////////////////////////////////////////////////////////////////////
176 * Delivers the given raw package data.
178 * @param $packageData Raw package data in an array
181 private function declareRawPackageData (array $packageData) {
183 * We need to disover every recipient, just in case we have a
184 * multi-recipient entry like 'upper' is. 'all' may be a not so good
185 * target because it causes an overload on the network and may be
186 * abused for attacking the network with large packages.
188 $discoveryInstance = PackageDiscoveryFactory::createPackageDiscoveryInstance();
190 // Discover all recipients, this may throw an exception
191 $discoveryInstance->discoverRecipients($packageData);
193 // Now get an iterator
194 $iteratorInstance = $discoveryInstance->getIterator();
196 // ... and begin iteration
197 while ($iteratorInstance->valid()) {
199 $currentRecipient = $iteratorInstance->current();
202 $this->debugOutput('PACKAGE: Package declared for recipient ' . $currentRecipient);
205 $packageData['recipient'] = $currentRecipient;
207 // And enqueue it to the writer class
208 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECLARED, $packageData);
210 // Skip to next entry
211 $iteratorInstance->next();
215 $discoveryInstance->clearRecipients();
219 * Delivers raw package data. In short, this will discover the raw socket
220 * resource through a discovery class (which will analyse the receipient of
221 * the package), register the socket with the connection (handler/helper?)
222 * instance and finally push the raw data on our outgoing queue.
224 * @param $packageData Raw package data in an array
227 private function deliverRawPackageData (array $packageData) {
229 * This package may become big, depending on the shared object size or
230 * delivered message size which shouldn't be so long (to save
231 * bandwidth). Because of the nature of the used protocol (TCP) we need
232 * to split it up into smaller pieces to fit it into a TCP frame.
234 * So first we need (again) a discovery class but now a protocol
235 * discovery to choose the right socket resource. The discovery class
236 * should take a look at the raw package data itself and then decide
237 * which (configurable!) protocol should be used for that type of
240 $discoveryInstance = SocketDiscoveryFactory::createSocketDiscoveryInstance();
242 // Now discover the right protocol
243 $socketResource = $discoveryInstance->discoverSocket($packageData);
245 // We have to put this socket in our registry, so get an instance
246 $registryInstance = SocketRegistry::createSocketRegistry();
248 // Get the listener from registry
249 $connectionInstance = Registry::getRegistry()->getInstance('connection');
252 if (!$registryInstance->isSocketRegistered($connectionInstance, $socketResource)) {
254 $registryInstance->registerSocket($connectionInstance, $socketResource, $packageData);
257 // We enqueue it again, but now in the out-going queue
258 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_OUTGOING, $packageData);
262 * Sends waiting packages
264 * @param $packageData Raw package data
267 private function sendOutgoingRawPackageData (array $packageData) {
268 // Get the right connection instance
269 $connectionInstance = SocketRegistry::createSocketRegistry()->getHandlerInstanceFromPackageData($packageData);
271 // Is this connection still alive?
272 if ($connectionInstance->isShuttedDown()) {
273 // This connection is shutting down
274 // @TODO We may want to do somthing more here?
278 // Sent it away (we catch exceptions one method above)
279 $sentBytes = $connectionInstance->sendRawPackageData($packageData);
281 // Remember unsent raw bytes in back-buffer, if any
282 $this->storeUnsentBytesInBackBuffer($packageData, $sentBytes);
286 * "Enqueues" raw content into this delivery class by reading the raw content
287 * from given template instance and pushing it on the 'undeclared' stack.
289 * @param $helperInstance An instance of a BaseHubHelper class
290 * @param $nodeInstance An instance of a NodeHelper class
293 public function enqueueRawDataFromTemplate (BaseHubHelper $helperInstance, NodeHelper $nodeInstance) {
294 // Get the raw content ...
295 $content = $helperInstance->getTemplateInstance()->getRawTemplateData();
297 // ... and compress it
298 $content = $this->getCompressorInstance()->compressStream($content);
300 // Add magic in front of it and hash behind it, including BASE64 encoding
301 $content = sprintf(self::PACKAGE_MASK,
302 // 1.) Compressor's extension
303 $this->getCompressorInstance()->getCompressorExtension(),
304 // 2.) Raw package content, encoded with BASE64
305 base64_encode($content),
307 implode(self::PACKAGE_TAGS_SEPERATOR, $helperInstance->getPackageTags()),
309 $this->getHashFromContent($content, $helperInstance, $nodeInstance)
312 // Now prepare the temporary array and push it on the 'undeclared' stack
313 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_UNDECLARED, array(
314 'sender' => $nodeInstance->getSessionId(),
315 'recipient' => $helperInstance->getRecipientType(),
316 'content' => $content,
321 * Checks wether a package has been enqueued for delivery.
323 * @return $isEnqueued Wether a package is enqueued
325 public function isPackageEnqueued () {
326 // Check wether the stacker is not empty
327 $isEnqueued = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_UNDECLARED)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_UNDECLARED)));
334 * Checks wether a package has been declared
336 * @return $isDeclared Wether a package is declared
338 public function isPackageDeclared () {
339 // Check wether the stacker is not empty
340 $isDeclared = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_DECLARED)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECLARED)));
347 * Checks wether a package should be sent out
349 * @return $isWaitingDelivery Wether a package is waiting for delivery
351 public function isPackageWaitingForDelivery () {
352 // Check wether the stacker is not empty
353 $isWaitingDelivery = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_OUTGOING)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_OUTGOING)));
356 return $isWaitingDelivery;
360 * Delivers an enqueued package to the stated destination. If a non-session
361 * id is provided, recipient resolver is being asked (and instanced once).
362 * This allows that a single package is being delivered to multiple targets
363 * without enqueueing it for every target. If no target is provided or it
364 * can't be determined a NoTargetException is being thrown.
367 * @throws NoTargetException If no target can't be determined
369 public function declareEnqueuedPackage () {
370 // Make sure this method isn't working if there is no package enqueued
371 if (!$this->isPackageEnqueued()) {
372 // This is not fatal but should be avoided
373 // @TODO Add some logging here
377 // Now we know for sure there are packages to deliver, we can start
378 // with the first one.
379 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_UNDECLARED);
381 // Declare the raw package data for delivery
382 $this->declareRawPackageData($packageData);
384 // And remove it finally
385 $this->getStackerInstance()->popNamed(self::STACKER_NAME_UNDECLARED);
389 * Delivers the next declared package. Only one package per time will be sent
390 * because this may take time and slows down the whole delivery
395 public function deliverDeclaredPackage () {
396 // Sanity check if we have packages declared
397 if (!$this->isPackageDeclared()) {
398 // This is not fatal but should be avoided
399 // @TODO Add some logging here
403 // Get the package again
404 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_DECLARED);
407 $this->deliverRawPackageData($packageData);
409 // And remove it finally
410 $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECLARED);
414 * Sends waiting packages out for delivery
418 public function sendWaitingPackage () {
419 // Send any waiting bytes in the back-buffer before sending a new package
420 $this->sendBackBufferBytes();
422 // Sanity check if we have packages waiting for delivery
423 if (!$this->isPackageWaitingForDelivery()) {
424 // This is not fatal but should be avoided
425 $this->debugOutput('PACKAGE: No package is waiting for delivery, but ' . __FUNCTION__ . ' was called.');
429 // Get the package again
430 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_OUTGOING);
433 // Now try to send it
434 $this->sendOutgoingRawPackageData($packageData);
436 // And remove it finally
437 $this->getStackerInstance()->popNamed(self::STACKER_NAME_OUTGOING);
438 } catch (InvalidSocketException $e) {
439 // Output exception message
440 $this->debugOutput('PACKAGE: Package was not delivered: ' . $e->getMessage());
444 ///////////////////////////////////////////////////////////////////////////
445 // Receiving packages / raw data
446 ///////////////////////////////////////////////////////////////////////////
449 * Checks wether new raw package data has arrived at a socket
451 * @return $hasArrived Wether new raw package data has arrived for processing
453 public function isNewRawDataPending () {
454 // @TODO Add some content here
458 * Checks wether a new package has arrived
460 * @return $hasArrived Wether a new package has arrived for processing
462 public function isNewPackageArrived () {
463 // @TODO Add some content here