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, 2010 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 * Network target (alias): 'upper hubs'
95 const NETWORK_TARGET_UPPER_HUBS = 'upper';
98 * Protected constructor
102 protected function __construct () {
103 // Call parent constructor
104 parent::__construct(__CLASS__);
106 // We need to initialize a stack here for our packages even those
107 // which have no recipient address and stamp... ;-)
108 $stackerInstance = ObjectFactory::createObjectByConfiguredName('package_stacker_class');
110 // At last, set it in this class
111 $this->setStackerInstance($stackerInstance);
115 * Creates an instance of this class
117 * @param $compressorInstance A Compressor instance for compressing the content
118 * @return $packageInstance An instance of a Deliverable class
120 public final static function createNetworkPackage (Compressor $compressorInstance) {
122 $packageInstance = new NetworkPackage();
124 // Now set the compressor instance
125 $packageInstance->setCompressorInstance($compressorInstance);
127 // Return the prepared instance
128 return $packageInstance;
132 * "Getter" for hash from given content and helper instance
134 * @param $content Raw package content
135 * @param $helperInstance A BaseHubHelper instance
136 * @return $hash Hash for given package content
138 private function getHashFromContent ($content, BaseHubHelper $helperInstance) {
140 // @TODO crc32 is not good, but it needs to be fast
144 $helperInstance->getNodeInstance()->getSessionId() .
146 $this->getCompressorInstance()->getCompressorExtension()
154 * Delivers the given raw package data.
156 * @param $packageData Raw package data in an array
159 private function deliverPackage (array $packageData) {
161 * We need to disover every recipient, just in case we have a
162 * multi-recipient entry like 'upper' is. 'all' may be a not so good
163 * target because it causes an overload on the network and may be
164 * abused for attacking the network with large packages.
166 $discoveryInstance = PackageDiscoveryFactory::createPackageDiscoveryInstance();
168 // Discover all recipients, this may throw an exception
169 $discoveryInstance->discoverRecipients($packageData);
171 // Now get an iterator
172 $iteratorInstance = $discoveryInstance->getIterator();
174 // ... and begin iteration
175 while ($iteratorInstance->valid()) {
177 $currentRecipient = $iteratorInstance->current();
180 $this->debugOutput('PACKAGE: Package declared for recipient ' . $currentRecipient);
183 $packageData['recipient'] = $currentRecipient;
185 // And enqueue it to the writer class
186 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECLARED, $packageData);
188 // Skip to next entry
189 $iteratorInstance->next();
193 $discoveryInstance->clearRecipients();
197 * Sends a raw package out
199 * @param $packageData Raw package data in an array
202 private function sendRawPackage (array $packageData) {
204 * This package may become big, depending on the shared object size or
205 * delivered message size which shouldn't be so long (to save
206 * bandwidth). Because of the nature of the used protocol (TCP) we need
207 * to split it up into smaller pieces to fit it into a TCP frame.
209 * So first we need (again) a discovery class but now a protocol
210 * discovery to choose the right socket resource. The discovery class
211 * should take a look at the raw package data itself and then decide
212 * which (configurable!) protocol should be used for that type of
215 $discoveryInstance = SocketDiscoveryFactory::createSocketDiscoveryInstance();
217 // Now discover the right protocol
218 $socketResource = $discoveryInstance->discoverSocket($packageData);
220 // We have to put this socket in our registry, so get an instance
221 $registryInstance = SocketRegistry::createSocketRegistry();
223 // Get the listener from registry
224 $connectionInstance = Registry::getRegistry()->getInstance('connection');
227 if (!$registryInstance->isSocketRegistered($connectionInstance, $socketResource)) {
229 $registryInstance->registerSocket($connectionInstance, $socketResource, $packageData);
232 // We enqueue it again, but now in the out-going queue
233 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_OUTGOING, $packageData);
237 * Sends waiting packages
239 * @param $packageData Raw package data
242 private function sendOutgoingPackage (array $packageData) {
243 // Get the right connection instance
244 $connectionInstance = SocketRegistry::createSocketRegistry()->getHandlerInstanceFromPackageData($packageData);
246 // Sent it away (we catch exceptions one method above
247 $connectionInstance->sendRawPackageData($packageData);
251 * "Enqueues" raw content into this delivery class by reading the raw content
252 * from given template instance and pushing it on the 'undeclared' stack.
254 * @param $helperInstance A BaseHubHelper instance
257 public function enqueueRawDataFromTemplate (BaseHubHelper $helperInstance) {
258 // Get the raw content ...
259 $content = $helperInstance->getTemplateInstance()->getRawTemplateData();
261 // ... and compress it
262 $content = $this->getCompressorInstance()->compressStream($content);
264 // Add magic in front of it and hash behind it, including BASE64 encoding
265 $content = sprintf(self::PACKAGE_MASK,
266 // 1.) Compressor's extension
267 $this->getCompressorInstance()->getCompressorExtension(),
268 // 2.) Raw package content, encoded with BASE64
269 base64_encode($content),
271 implode(self::PACKAGE_TAGS_SEPERATOR, $helperInstance->getPackageTags()),
273 $this->getHashFromContent($content, $helperInstance)
276 // Now prepare the temporary array and push it on the 'undeclared' stack
277 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_UNDECLARED, array(
278 'sender' => $helperInstance->getNodeInstance()->getSessionId(),
279 'recipient' => self::NETWORK_TARGET_UPPER_HUBS,
280 'content' => $content,
285 * Checks wether a package has been enqueued for delivery.
287 * @return $isEnqueued Wether a package is enqueued
289 public function isPackageEnqueued () {
290 // Check wether the stacker is not empty
291 $isEnqueued = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_UNDECLARED)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_UNDECLARED)));
298 * Checks wether a package has been declared
300 * @return $isDeclared Wether a package is declared
302 public function isPackageDeclared () {
303 // Check wether the stacker is not empty
304 $isDeclared = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_DECLARED)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECLARED)));
311 * Checks wether a package should be sent out
313 * @return $isWaitingDelivery Wether a package is waiting for delivery
315 public function isPackageWaitingDelivery () {
316 // Check wether the stacker is not empty
317 $isWaitingDelivery = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_OUTGOING)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_OUTGOING)));
320 return $isWaitingDelivery;
324 * Delivers an enqueued package to the stated destination. If a non-session
325 * id is provided, recipient resolver is being asked (and instanced once).
326 * This allows that a single package is being delivered to multiple targets
327 * without enqueueing it for every target. If no target is provided or it
328 * can't be determined a NoTargetException is being thrown.
331 * @throws NoTargetException If no target can't be determined
333 public function declareEnqueuedPackage () {
334 // Make sure this method isn't working if there is no package enqueued
335 if (!$this->isPackageEnqueued()) {
336 // This is not fatal but should be avoided
337 // @TODO Add some logging here
341 // Now we know for sure there are packages to deliver, we can start
342 // with the first one.
343 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_UNDECLARED);
345 // Finally, deliver the package
346 $this->deliverPackage($packageData);
348 // And remove it finally
349 $this->getStackerInstance()->popNamed(self::STACKER_NAME_UNDECLARED);
353 * Delivers the next declared package. Only one package per time will be sent
354 * because this may take time and slows down the whole delivery
359 public function deliverDeclaredPackage () {
360 // Sanity check if we have packages declared
361 if (!$this->isPackageDeclared()) {
362 // This is not fatal but should be avoided
363 // @TODO Add some logging here
367 // Get the package again
368 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_DECLARED);
371 $this->sendRawPackage($packageData);
373 // And remove it finally
374 $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECLARED);
378 * Sends waiting packages out for delivery
382 public function sentWaitingPackage () {
383 // Sanity check if we have packages waiting for delivery
384 if (!$this->isPackageWaitingDelivery()) {
385 // This is not fatal but should be avoided
386 // @TODO Add some logging here
390 // Get the package again
391 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_OUTGOING);
393 // Now try to send it
395 $this->sendOutgoingPackage($packageData);
397 // And remove it finally when it has been fully delivered
398 $this->getStackerInstance()->popNamed(self::STACKER_NAME_OUTGOING);
399 } catch (InvalidSocketException $e) {
400 // Output exception message
401 $this->debugOutput('PACKAGE: Package was not delivered: ' . $e->getMessage());