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;
77 const PACKAGE_TAGS_SEPERATOR = ';';
80 * Raw package data seperator
82 const PACKAGE_DATA_SEPERATOR = '|';
85 * Stacker name for "undeclared" packages
87 const STACKER_NAME_UNDECLARED = 'undeclared';
90 * Stacker name for "declared" packages (which are ready to send out)
92 const STACKER_NAME_DECLARED = 'declared';
95 * Stacker name for "out-going" packages
97 const STACKER_NAME_OUTGOING = 'outgoing';
100 * Stacker name for "back-buffered" packages
102 const STACKER_NAME_BACK_BUFFER = 'backbuffer';
105 * Network target (alias): 'upper hubs'
107 const NETWORK_TARGET_UPPER_HUBS = 'upper';
110 * Network target (alias): 'self'
112 const NETWORK_TARGET_SELF = 'self';
115 * TCP package size in bytes
117 const TCP_PACKAGE_SIZE = 512;
120 * Protected constructor
124 protected function __construct () {
125 // Call parent constructor
126 parent::__construct(__CLASS__);
128 // We need to initialize a stack here for our packages even those
129 // which have no recipient address and stamp... ;-)
130 $stackerInstance = ObjectFactory::createObjectByConfiguredName('network_package_stacker_class');
132 // At last, set it in this class
133 $this->setStackerInstance($stackerInstance);
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 // Return the prepared instance
150 return $packageInstance;
154 * "Getter" for hash from given content and helper instance
156 * @param $content Raw package content
157 * @param $helperInstance An instance of a BaseHubHelper class
158 * @param $nodeInstance An instance of a NodeHelper class
159 * @return $hash Hash for given package content
160 * @todo $helperInstance is unused
162 private function getHashFromContent ($content, BaseHubHelper $helperInstance, NodeHelper $nodeInstance) {
164 // @TODO crc32 is not very strong, but it needs to be fast
167 self::PACKAGE_CHECKSUM_SEPERATOR .
168 $nodeInstance->getSessionId() .
169 self::PACKAGE_CHECKSUM_SEPERATOR .
170 $this->getCompressorInstance()->getCompressorExtension()
177 ///////////////////////////////////////////////////////////////////////////
178 // Delivering packages / raw data
179 ///////////////////////////////////////////////////////////////////////////
182 * Delivers the given raw package data.
184 * @param $packageData Raw package data in an array
187 private function declareRawPackageData (array $packageData) {
189 * We need to disover every recipient, just in case we have a
190 * multi-recipient entry like 'upper' is. 'all' may be a not so good
191 * target because it causes an overload on the network and may be
192 * abused for attacking the network with large packages.
194 $discoveryInstance = PackageDiscoveryFactory::createPackageDiscoveryInstance();
196 // Discover all recipients, this may throw an exception
197 $discoveryInstance->discoverRecipients($packageData);
199 // Now get an iterator
200 $iteratorInstance = $discoveryInstance->getIterator();
202 // ... and begin iteration
203 while ($iteratorInstance->valid()) {
205 $currentRecipient = $iteratorInstance->current();
208 $this->debugOutput('PACKAGE: Package declared for recipient ' . $currentRecipient);
211 $packageData['recipient'] = $currentRecipient;
213 // And enqueue it to the writer class
214 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECLARED, $packageData);
216 // Skip to next entry
217 $iteratorInstance->next();
221 $discoveryInstance->clearRecipients();
225 * Delivers raw package data. In short, this will discover the raw socket
226 * resource through a discovery class (which will analyse the receipient of
227 * the package), register the socket with the connection (handler/helper?)
228 * instance and finally push the raw data on our outgoing queue.
230 * @param $packageData Raw package data in an array
233 private function deliverRawPackageData (array $packageData) {
235 * This package may become big, depending on the shared object size or
236 * delivered message size which shouldn't be so long (to save
237 * bandwidth). Because of the nature of the used protocol (TCP) we need
238 * to split it up into smaller pieces to fit it into a TCP frame.
240 * So first we need (again) a discovery class but now a protocol
241 * discovery to choose the right socket resource. The discovery class
242 * should take a look at the raw package data itself and then decide
243 * which (configurable!) protocol should be used for that type of
246 $discoveryInstance = SocketDiscoveryFactory::createSocketDiscoveryInstance();
248 // Now discover the right protocol
249 $socketResource = $discoveryInstance->discoverSocket($packageData);
251 // We have to put this socket in our registry, so get an instance
252 $registryInstance = SocketRegistry::createSocketRegistry();
254 // Get the listener from registry
255 $connectionInstance = Registry::getRegistry()->getInstance('connection');
258 if (!$registryInstance->isSocketRegistered($connectionInstance, $socketResource)) {
260 $registryInstance->registerSocket($connectionInstance, $socketResource, $packageData);
263 // We enqueue it again, but now in the out-going queue
264 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_OUTGOING, $packageData);
268 * Sends waiting packages
270 * @param $packageData Raw package data
273 private function sendOutgoingRawPackageData (array $packageData) {
274 // Get the right connection instance
275 $connectionInstance = SocketRegistry::createSocketRegistry()->getHandlerInstanceFromPackageData($packageData);
277 // Is this connection still alive?
278 if ($connectionInstance->isShuttedDown()) {
279 // This connection is shutting down
280 // @TODO We may want to do somthing more here?
284 // Sent it away (we catch exceptions one method above)
285 $sentBytes = $connectionInstance->sendRawPackageData($packageData);
287 // Remember unsent raw bytes in back-buffer, if any
288 $this->storeUnsentBytesInBackBuffer($packageData, $sentBytes);
292 * "Enqueues" raw content into this delivery class by reading the raw content
293 * from given template instance and pushing it on the 'undeclared' stack.
295 * @param $helperInstance An instance of a BaseHubHelper class
296 * @param $nodeInstance An instance of a NodeHelper class
299 public function enqueueRawDataFromTemplate (BaseHubHelper $helperInstance, NodeHelper $nodeInstance) {
300 // Get the raw content ...
301 $content = $helperInstance->getTemplateInstance()->getRawTemplateData();
303 // ... and compress it
304 $content = $this->getCompressorInstance()->compressStream($content);
306 // Add magic in front of it and hash behind it, including BASE64 encoding
307 $content = sprintf(self::PACKAGE_MASK,
308 // 1.) Compressor's extension
309 $this->getCompressorInstance()->getCompressorExtension(),
310 // 2.) Raw package content, encoded with BASE64
311 base64_encode($content),
313 implode(self::PACKAGE_TAGS_SEPERATOR, $helperInstance->getPackageTags()),
315 $this->getHashFromContent($content, $helperInstance, $nodeInstance)
318 // Now prepare the temporary array and push it on the 'undeclared' stack
319 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_UNDECLARED, array(
320 'sender' => $nodeInstance->getSessionId(),
321 'recipient' => $helperInstance->getRecipientType(),
322 'content' => $content,
327 * Checks wether a package has been enqueued for delivery.
329 * @return $isEnqueued Wether a package is enqueued
331 public function isPackageEnqueued () {
332 // Check wether the stacker is not empty
333 $isEnqueued = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_UNDECLARED)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_UNDECLARED)));
340 * Checks wether a package has been declared
342 * @return $isDeclared Wether a package is declared
344 public function isPackageDeclared () {
345 // Check wether the stacker is not empty
346 $isDeclared = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_DECLARED)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECLARED)));
353 * Checks wether a package should be sent out
355 * @return $isWaitingDelivery Wether a package is waiting for delivery
357 public function isPackageWaitingForDelivery () {
358 // Check wether the stacker is not empty
359 $isWaitingDelivery = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_OUTGOING)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_OUTGOING)));
362 return $isWaitingDelivery;
366 * Delivers an enqueued package to the stated destination. If a non-session
367 * id is provided, recipient resolver is being asked (and instanced once).
368 * This allows that a single package is being delivered to multiple targets
369 * without enqueueing it for every target. If no target is provided or it
370 * can't be determined a NoTargetException is being thrown.
373 * @throws NoTargetException If no target can't be determined
375 public function declareEnqueuedPackage () {
376 // Make sure this method isn't working if there is no package enqueued
377 if (!$this->isPackageEnqueued()) {
378 // This is not fatal but should be avoided
379 // @TODO Add some logging here
383 // Now we know for sure there are packages to deliver, we can start
384 // with the first one.
385 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_UNDECLARED);
387 // Declare the raw package data for delivery
388 $this->declareRawPackageData($packageData);
390 // And remove it finally
391 $this->getStackerInstance()->popNamed(self::STACKER_NAME_UNDECLARED);
395 * Delivers the next declared package. Only one package per time will be sent
396 * because this may take time and slows down the whole delivery
401 public function deliverDeclaredPackage () {
402 // Sanity check if we have packages declared
403 if (!$this->isPackageDeclared()) {
404 // This is not fatal but should be avoided
405 // @TODO Add some logging here
409 // Get the package again
410 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_DECLARED);
413 $this->deliverRawPackageData($packageData);
415 // And remove it finally
416 $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECLARED);
420 * Sends waiting packages out for delivery
424 public function sendWaitingPackage () {
425 // Send any waiting bytes in the back-buffer before sending a new package
426 $this->sendBackBufferBytes();
428 // Sanity check if we have packages waiting for delivery
429 if (!$this->isPackageWaitingForDelivery()) {
430 // This is not fatal but should be avoided
431 $this->debugOutput('PACKAGE: No package is waiting for delivery, but ' . __FUNCTION__ . ' was called.');
435 // Get the package again
436 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_OUTGOING);
439 // Now try to send it
440 $this->sendOutgoingRawPackageData($packageData);
442 // And remove it finally
443 $this->getStackerInstance()->popNamed(self::STACKER_NAME_OUTGOING);
444 } catch (InvalidSocketException $e) {
445 // Output exception message
446 $this->debugOutput('PACKAGE: Package was not delivered: ' . $e->getMessage());
450 ///////////////////////////////////////////////////////////////////////////
451 // Receiving packages / raw data
452 ///////////////////////////////////////////////////////////////////////////
455 * Checks wether new raw package data has arrived at a socket
457 * @return $hasArrived Wether new raw package data has arrived for processing
459 public function isNewRawDataPending () {
460 // @TODO Add some content here
464 * Checks wether a new package has arrived
466 * @return $hasArrived Wether a new package has arrived for processing
468 public function isNewPackageArrived () {
469 // @TODO Add some content here