3 * A NetworkPackage class. This class implements the Deliverable class because
4 * all network packages should be deliverable to other nodes. It further
5 * provides methods for reading raw content from template engines and feeding it
6 * to the stacker 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 instantiated 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 * 1.) Compressor extension
41 * 2.) Raw package data
42 * 3.) Tags, seperated by semicolons, no semicolon is required if only one tag is needed
45 const PACKAGE_MASK = '%s:%s:%s:%s';
48 * Seperator for the above mask
50 const PACKAGE_MASK_SEPERATOR = ':';
53 * Array indexes for above mask, start with zero
55 const INDEX_COMPRESSOR_EXTENSION = 0;
56 const INDEX_PACKAGE_DATA = 1;
58 const INDEX_CHECKSUM = 3;
61 * Array indexes for raw package array
63 const INDEX_PACKAGE_SENDER = 0;
64 const INDEX_PACKAGE_RECIPIENT = 1;
65 const INDEX_PACKAGE_CONTENT = 2;
70 const PACKAGE_TAGS_SEPERATOR = ';';
73 * Raw package data seperator
75 const PACKAGE_DATA_SEPERATOR = '|';
78 * Stacker name for "undeclared" packages
80 const STACKER_NAME_UNDECLARED = 'undeclared';
83 * Stacker name for "declared" packages (which are ready to send out)
85 const STACKER_NAME_DECLARED = 'declared';
88 * Stacker name for "out-going" packages
90 const STACKER_NAME_OUTGOING = 'outgoing';
93 * Stacker name for "back-buffered" packages
95 const STACKER_NAME_BACK_BUFFER = 'backbuffer';
98 * Network target (alias): 'upper hubs'
100 const NETWORK_TARGET_UPPER_HUBS = 'upper';
103 * Network target (alias): 'self'
105 const NETWORK_TARGET_SELF = 'self';
108 * Protected constructor
112 protected function __construct () {
113 // Call parent constructor
114 parent::__construct(__CLASS__);
116 // We need to initialize a stack here for our packages even those
117 // which have no recipient address and stamp... ;-)
118 $stackerInstance = ObjectFactory::createObjectByConfiguredName('network_package_stacker_class');
120 // At last, set it in this class
121 $this->setStackerInstance($stackerInstance);
125 * Creates an instance of this class
127 * @param $compressorInstance A Compressor instance for compressing the content
128 * @return $packageInstance An instance of a Deliverable class
130 public static final function createNetworkPackage (Compressor $compressorInstance) {
132 $packageInstance = new NetworkPackage();
134 // Now set the compressor instance
135 $packageInstance->setCompressorInstance($compressorInstance);
137 // Return the prepared instance
138 return $packageInstance;
142 * "Getter" for hash from given content and helper instance
144 * @param $content Raw package content
145 * @param $helperInstance An instance of a BaseHubHelper class
146 * @param $nodeInstance An instance of a NodeHelper class
147 * @return $hash Hash for given package content
149 private function getHashFromContent ($content, BaseHubHelper $helperInstance, NodeHelper $nodeInstance) {
151 // @TODO crc32 is not good, but it needs to be fast
155 $nodeInstance->getSessionId() .
157 $this->getCompressorInstance()->getCompressorExtension()
165 * Delivers the given raw package data.
167 * @param $packageData Raw package data in an array
170 private function declareRawPackageData (array $packageData) {
172 * We need to disover every recipient, just in case we have a
173 * multi-recipient entry like 'upper' is. 'all' may be a not so good
174 * target because it causes an overload on the network and may be
175 * abused for attacking the network with large packages.
177 $discoveryInstance = PackageDiscoveryFactory::createPackageDiscoveryInstance();
179 // Discover all recipients, this may throw an exception
180 $discoveryInstance->discoverRecipients($packageData);
182 // Now get an iterator
183 $iteratorInstance = $discoveryInstance->getIterator();
185 // ... and begin iteration
186 while ($iteratorInstance->valid()) {
188 $currentRecipient = $iteratorInstance->current();
191 $this->debugOutput('PACKAGE: Package declared for recipient ' . $currentRecipient);
194 $packageData['recipient'] = $currentRecipient;
196 // And enqueue it to the writer class
197 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECLARED, $packageData);
199 // Skip to next entry
200 $iteratorInstance->next();
204 $discoveryInstance->clearRecipients();
208 * Delivers raw package data. In short, this will discover the raw socket
209 * resource through a discovery class (which will analyse the receipient of
210 * the package), register the socket with the connection (handler/helper?)
211 * instance and finally push the raw data on our outgoing queue.
213 * @param $packageData Raw package data in an array
216 private function deliverRawPackageData (array $packageData) {
218 * This package may become big, depending on the shared object size or
219 * delivered message size which shouldn't be so long (to save
220 * bandwidth). Because of the nature of the used protocol (TCP) we need
221 * to split it up into smaller pieces to fit it into a TCP frame.
223 * So first we need (again) a discovery class but now a protocol
224 * discovery to choose the right socket resource. The discovery class
225 * should take a look at the raw package data itself and then decide
226 * which (configurable!) protocol should be used for that type of
229 $discoveryInstance = SocketDiscoveryFactory::createSocketDiscoveryInstance();
231 // Now discover the right protocol
232 $socketResource = $discoveryInstance->discoverSocket($packageData);
234 // We have to put this socket in our registry, so get an instance
235 $registryInstance = SocketRegistry::createSocketRegistry();
237 // Get the listener from registry
238 $connectionInstance = Registry::getRegistry()->getInstance('connection');
241 if (!$registryInstance->isSocketRegistered($connectionInstance, $socketResource)) {
243 $registryInstance->registerSocket($connectionInstance, $socketResource, $packageData);
246 // We enqueue it again, but now in the out-going queue
247 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_OUTGOING, $packageData);
251 * Sends waiting packages
253 * @param $packageData Raw package data
256 private function sendOutgoingRawPackageData (array $packageData) {
257 // Get the right connection instance
258 $connectionInstance = SocketRegistry::createSocketRegistry()->getHandlerInstanceFromPackageData($packageData);
260 // Is this connection still alive?
261 if ($connectionInstance->isShuttedDown()) {
262 // This connection is shutting down
263 // @TODO We may want to do somthing more here?
267 // Sent it away (we catch exceptions one method above
268 $sentBytes = $connectionInstance->sendRawPackageData($packageData);
270 // Remember unsent raw bytes in back-buffer, if any
271 $this->storeUnsentBytesInBackBuffer($packageData, $sentBytes);
275 * "Enqueues" raw content into this delivery class by reading the raw content
276 * from given template instance and pushing it on the 'undeclared' stack.
278 * @param $helperInstance An instance of a BaseHubHelper class
279 * @param $nodeInstance An instance of a NodeHelper class
282 public function enqueueRawDataFromTemplate (BaseHubHelper $helperInstance, NodeHelper $nodeInstance) {
283 // Get the raw content ...
284 $content = $helperInstance->getTemplateInstance()->getRawTemplateData();
286 // ... and compress it
287 $content = $this->getCompressorInstance()->compressStream($content);
289 // Add magic in front of it and hash behind it, including BASE64 encoding
290 $content = sprintf(self::PACKAGE_MASK,
291 // 1.) Compressor's extension
292 $this->getCompressorInstance()->getCompressorExtension(),
293 // 2.) Raw package content, encoded with BASE64
294 base64_encode($content),
296 implode(self::PACKAGE_TAGS_SEPERATOR, $helperInstance->getPackageTags()),
298 $this->getHashFromContent($content, $helperInstance, $nodeInstance)
301 // Now prepare the temporary array and push it on the 'undeclared' stack
302 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_UNDECLARED, array(
303 'sender' => $nodeInstance->getSessionId(),
304 'recipient' => $helperInstance->getRecipientType(),
305 'content' => $content,
310 * Checks wether a package has been enqueued for delivery.
312 * @return $isEnqueued Wether a package is enqueued
314 public function isPackageEnqueued () {
315 // Check wether the stacker is not empty
316 $isEnqueued = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_UNDECLARED)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_UNDECLARED)));
323 * Checks wether a package has been declared
325 * @return $isDeclared Wether a package is declared
327 public function isPackageDeclared () {
328 // Check wether the stacker is not empty
329 $isDeclared = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_DECLARED)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECLARED)));
336 * Checks wether a package should be sent out
338 * @return $isWaitingDelivery Wether a package is waiting for delivery
340 public function isPackageWaitingForDelivery () {
341 // Check wether the stacker is not empty
342 $isWaitingDelivery = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_OUTGOING)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_OUTGOING)));
345 return $isWaitingDelivery;
349 * Delivers an enqueued package to the stated destination. If a non-session
350 * id is provided, recipient resolver is being asked (and instanced once).
351 * This allows that a single package is being delivered to multiple targets
352 * without enqueueing it for every target. If no target is provided or it
353 * can't be determined a NoTargetException is being thrown.
356 * @throws NoTargetException If no target can't be determined
358 public function declareEnqueuedPackage () {
359 // Make sure this method isn't working if there is no package enqueued
360 if (!$this->isPackageEnqueued()) {
361 // This is not fatal but should be avoided
362 // @TODO Add some logging here
366 // Now we know for sure there are packages to deliver, we can start
367 // with the first one.
368 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_UNDECLARED);
370 // Declare the raw package data for delivery
371 $this->declareRawPackageData($packageData);
373 // And remove it finally
374 $this->getStackerInstance()->popNamed(self::STACKER_NAME_UNDECLARED);
378 * Delivers the next declared package. Only one package per time will be sent
379 * because this may take time and slows down the whole delivery
384 public function deliverDeclaredPackage () {
385 // Sanity check if we have packages declared
386 if (!$this->isPackageDeclared()) {
387 // This is not fatal but should be avoided
388 // @TODO Add some logging here
392 // Get the package again
393 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_DECLARED);
396 $this->deliverRawPackageData($packageData);
398 // And remove it finally
399 $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECLARED);
403 * Sends waiting packages out for delivery
407 public function sendWaitingPackage () {
408 // Sent any waiting bytes in the back-buffer
409 $this->sendBackBufferBytes();
411 // Sanity check if we have packages waiting for delivery
412 if (!$this->isPackageWaitingForDelivery()) {
413 // This is not fatal but should be avoided
414 // @TODO Add some logging here
418 // Get the package again
419 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_OUTGOING);
422 // Now try to send it
423 $this->sendOutgoingRawPackageData($packageData);
426 // And remove it finally
427 $this->getStackerInstance()->popNamed(self::STACKER_NAME_OUTGOING);
428 } catch (InvalidSocketException $e) {
429 // Output exception message
430 $this->debugOutput('PACKAGE: Package was not delivered: ' . $e->getMessage());