3 * A NetworkPackage class. This class implements Deliverable because all network
4 * packages should be deliverable to other nodes. It further provides methods
5 * for reading raw content from template engines and feeding it to the stacker
6 * for undeclared packages.
8 * The factory method requires you to provide a compressor class (which must
9 * implement the Compressor interface). If you don't want any compression (not
10 * adviceable due to increased network load), please use the NullCompressor
11 * class and encode it with BASE64 for a more error-free transfer over the
14 * For performance reasons, this class should only be instanciated once and then
15 * used as a "pipe-through" class.
17 * @author Roland Haeder <webmaster@ship-simu.org>
19 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2011 Hub Developer Team
20 * @license GNU GPL 3.0 or any newer version
21 * @link http://www.ship-simu.org
22 * @todo Needs to add functionality for handling the object's type
24 * This program is free software: you can redistribute it and/or modify
25 * it under the terms of the GNU General Public License as published by
26 * the Free Software Foundation, either version 3 of the License, or
27 * (at your option) any later version.
29 * This program is distributed in the hope that it will be useful,
30 * but WITHOUT ANY WARRANTY; without even the implied warranty of
31 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
32 * GNU General Public License for more details.
34 * You should have received a copy of the GNU General Public License
35 * along with this program. If not, see <http://www.gnu.org/licenses/>.
37 class NetworkPackage extends BaseFrameworkSystem implements Deliverable, Registerable {
39 * Package mask for compressing package data:
40 * 0: Compressor extension
42 * 2: Tags, seperated by semicolons, no semicolon is required if only one tag is needed
46 const PACKAGE_MASK = '%s:%s:%s:%s';
49 * Seperator for the above mask
51 const PACKAGE_MASK_SEPERATOR = ':';
54 * Array indexes for above mask, start with zero
56 const INDEX_COMPRESSOR_EXTENSION = 0;
57 const INDEX_PACKAGE_DATA = 1;
59 const INDEX_CHECKSUM = 3;
62 * Array indexes for raw package array
64 const INDEX_PACKAGE_SENDER = 0;
65 const INDEX_PACKAGE_RECIPIENT = 1;
66 const INDEX_PACKAGE_CONTENT = 2;
71 const PACKAGE_TAGS_SEPERATOR = ';';
74 * Raw package data seperator
76 const PACKAGE_DATA_SEPERATOR = '|';
79 * Stacker name for "undeclared" packages
81 const STACKER_NAME_UNDECLARED = 'undeclared';
84 * Stacker name for "declared" packages (which are ready to send out)
86 const STACKER_NAME_DECLARED = 'declared';
89 * Stacker name for "out-going" packages
91 const STACKER_NAME_OUTGOING = 'outgoing';
94 * Stacker name for "back-buffered" packages
96 const STACKER_NAME_BACK_BUFFER = 'backbuffer';
99 * Network target (alias): 'upper hubs'
101 const NETWORK_TARGET_UPPER_HUBS = 'upper';
104 * Network target (alias): 'self'
106 const NETWORK_TARGET_SELF = 'self';
111 const TCP_PACKAGE_SIZE = 512;
114 * Protected constructor
118 protected function __construct () {
119 // Call parent constructor
120 parent::__construct(__CLASS__);
122 // We need to initialize a stack here for our packages even those
123 // which have no recipient address and stamp... ;-)
124 $stackerInstance = ObjectFactory::createObjectByConfiguredName('network_package_stacker_class');
126 // At last, set it in this class
127 $this->setStackerInstance($stackerInstance);
131 * Creates an instance of this class
133 * @param $compressorInstance A Compressor instance for compressing the content
134 * @return $packageInstance An instance of a Deliverable class
136 public static final function createNetworkPackage (Compressor $compressorInstance) {
138 $packageInstance = new NetworkPackage();
140 // Now set the compressor instance
141 $packageInstance->setCompressorInstance($compressorInstance);
143 // Return the prepared instance
144 return $packageInstance;
148 * "Getter" for hash from given content and helper instance
150 * @param $content Raw package content
151 * @param $helperInstance An instance of a BaseHubHelper class
152 * @param $nodeInstance An instance of a NodeHelper class
153 * @return $hash Hash for given package content
155 private function getHashFromContent ($content, BaseHubHelper $helperInstance, NodeHelper $nodeInstance) {
157 // @TODO crc32 is not good, but it needs to be fast
161 $nodeInstance->getSessionId() .
163 $this->getCompressorInstance()->getCompressorExtension()
171 * Delivers the given raw package data.
173 * @param $packageData Raw package data in an array
176 private function declareRawPackageData (array $packageData) {
178 * We need to disover every recipient, just in case we have a
179 * multi-recipient entry like 'upper' is. 'all' may be a not so good
180 * target because it causes an overload on the network and may be
181 * abused for attacking the network with large packages.
183 $discoveryInstance = PackageDiscoveryFactory::createPackageDiscoveryInstance();
185 // Discover all recipients, this may throw an exception
186 $discoveryInstance->discoverRecipients($packageData);
188 // Now get an iterator
189 $iteratorInstance = $discoveryInstance->getIterator();
191 // ... and begin iteration
192 while ($iteratorInstance->valid()) {
194 $currentRecipient = $iteratorInstance->current();
197 $this->debugOutput('PACKAGE: Package declared for recipient ' . $currentRecipient);
200 $packageData['recipient'] = $currentRecipient;
202 // And enqueue it to the writer class
203 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECLARED, $packageData);
205 // Skip to next entry
206 $iteratorInstance->next();
210 $discoveryInstance->clearRecipients();
214 * Delivers raw package data. In short, this will discover the raw socket
215 * resource through a discovery class (which will analyse the receipient of
216 * the package), register the socket with the connection (handler/helper?)
217 * instance and finally push the raw data on our outgoing queue.
219 * @param $packageData Raw package data in an array
222 private function deliverRawPackageData (array $packageData) {
224 * This package may become big, depending on the shared object size or
225 * delivered message size which shouldn't be so long (to save
226 * bandwidth). Because of the nature of the used protocol (TCP) we need
227 * to split it up into smaller pieces to fit it into a TCP frame.
229 * So first we need (again) a discovery class but now a protocol
230 * discovery to choose the right socket resource. The discovery class
231 * should take a look at the raw package data itself and then decide
232 * which (configurable!) protocol should be used for that type of
235 $discoveryInstance = SocketDiscoveryFactory::createSocketDiscoveryInstance();
237 // Now discover the right protocol
238 $socketResource = $discoveryInstance->discoverSocket($packageData);
240 // We have to put this socket in our registry, so get an instance
241 $registryInstance = SocketRegistry::createSocketRegistry();
243 // Get the listener from registry
244 $connectionInstance = Registry::getRegistry()->getInstance('connection');
247 if (!$registryInstance->isSocketRegistered($connectionInstance, $socketResource)) {
249 $registryInstance->registerSocket($connectionInstance, $socketResource, $packageData);
252 // We enqueue it again, but now in the out-going queue
253 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_OUTGOING, $packageData);
257 * Sends waiting packages
259 * @param $packageData Raw package data
262 private function sendOutgoingRawPackageData (array $packageData) {
263 // Get the right connection instance
264 $connectionInstance = SocketRegistry::createSocketRegistry()->getHandlerInstanceFromPackageData($packageData);
266 // Is this connection still alive?
267 if ($connectionInstance->isShuttedDown()) {
268 // This connection is shutting down
269 // @TODO We may want to do somthing more here?
273 // Sent it away (we catch exceptions one method above
274 $sentBytes = $connectionInstance->sendRawPackageData($packageData);
276 // Remember unsent raw bytes in back-buffer, if any
277 $this->storeUnsentBytesInBackBuffer($packageData, $sentBytes);
281 * "Enqueues" raw content into this delivery class by reading the raw content
282 * from given template instance and pushing it on the 'undeclared' stack.
284 * @param $helperInstance An instance of a BaseHubHelper class
285 * @param $nodeInstance An instance of a NodeHelper class
288 public function enqueueRawDataFromTemplate (BaseHubHelper $helperInstance, NodeHelper $nodeInstance) {
289 // Get the raw content ...
290 $content = $helperInstance->getTemplateInstance()->getRawTemplateData();
292 // ... and compress it
293 $content = $this->getCompressorInstance()->compressStream($content);
295 // Add magic in front of it and hash behind it, including BASE64 encoding
296 $content = sprintf(self::PACKAGE_MASK,
297 // 1.) Compressor's extension
298 $this->getCompressorInstance()->getCompressorExtension(),
299 // 2.) Raw package content, encoded with BASE64
300 base64_encode($content),
302 implode(self::PACKAGE_TAGS_SEPERATOR, $helperInstance->getPackageTags()),
304 $this->getHashFromContent($content, $helperInstance, $nodeInstance)
307 // Now prepare the temporary array and push it on the 'undeclared' stack
308 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_UNDECLARED, array(
309 'sender' => $nodeInstance->getSessionId(),
310 'recipient' => $helperInstance->getRecipientType(),
311 'content' => $content,
316 * Checks wether a package has been enqueued for delivery.
318 * @return $isEnqueued Wether a package is enqueued
320 public function isPackageEnqueued () {
321 // Check wether the stacker is not empty
322 $isEnqueued = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_UNDECLARED)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_UNDECLARED)));
329 * Checks wether a package has been declared
331 * @return $isDeclared Wether a package is declared
333 public function isPackageDeclared () {
334 // Check wether the stacker is not empty
335 $isDeclared = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_DECLARED)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECLARED)));
342 * Checks wether a package should be sent out
344 * @return $isWaitingDelivery Wether a package is waiting for delivery
346 public function isPackageWaitingForDelivery () {
347 // Check wether the stacker is not empty
348 $isWaitingDelivery = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_OUTGOING)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_OUTGOING)));
351 return $isWaitingDelivery;
355 * Delivers an enqueued package to the stated destination. If a non-session
356 * id is provided, recipient resolver is being asked (and instanced once).
357 * This allows that a single package is being delivered to multiple targets
358 * without enqueueing it for every target. If no target is provided or it
359 * can't be determined a NoTargetException is being thrown.
362 * @throws NoTargetException If no target can't be determined
364 public function declareEnqueuedPackage () {
365 // Make sure this method isn't working if there is no package enqueued
366 if (!$this->isPackageEnqueued()) {
367 // This is not fatal but should be avoided
368 // @TODO Add some logging here
372 // Now we know for sure there are packages to deliver, we can start
373 // with the first one.
374 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_UNDECLARED);
376 // Declare the raw package data for delivery
377 $this->declareRawPackageData($packageData);
379 // And remove it finally
380 $this->getStackerInstance()->popNamed(self::STACKER_NAME_UNDECLARED);
384 * Delivers the next declared package. Only one package per time will be sent
385 * because this may take time and slows down the whole delivery
390 public function deliverDeclaredPackage () {
391 // Sanity check if we have packages declared
392 if (!$this->isPackageDeclared()) {
393 // This is not fatal but should be avoided
394 // @TODO Add some logging here
398 // Get the package again
399 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_DECLARED);
402 $this->deliverRawPackageData($packageData);
404 // And remove it finally
405 $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECLARED);
409 * Sends waiting packages out for delivery
413 public function sendWaitingPackage () {
414 // Send any waiting bytes in the back-buffer before sending a new package
415 $this->sendBackBufferBytes();
417 // Sanity check if we have packages waiting for delivery
418 if (!$this->isPackageWaitingForDelivery()) {
419 // This is not fatal but should be avoided
420 $this->debugOutput('PACKAGE: No package is waiting for delivery, but ' . __FUNCTION__ . ' was called.');
424 // Get the package again
425 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_OUTGOING);
428 // Now try to send it
429 $this->sendOutgoingRawPackageData($packageData);
432 // And remove it finally
433 $this->getStackerInstance()->popNamed(self::STACKER_NAME_OUTGOING);
434 } catch (InvalidSocketException $e) {
435 // Output exception message
436 $this->debugOutput('PACKAGE: Package was not delivered: ' . $e->getMessage());