]> git.mxchange.org Git - hub.git/blob - application/hub/main/package/class_NetworkPackage.php
Typo fixed, visitor introduced, SVN property set:
[hub.git] / application / hub / main / package / class_NetworkPackage.php
1 <?php
2 /**
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
7  * packages.
8  *
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
13  * Internet.
14  *
15  * For performance reasons, this class should only be instanciated once and then
16  * used as a "pipe-through" class.
17  *
18  * @author              Roland Haeder <webmaster@ship-simu.org>
19  * @version             0.0.0
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
24  *
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.
29  *
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.
34  *
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/>.
37  */
38 class NetworkPackage extends BaseFrameworkSystem implements Deliverable, Receivable, Registerable {
39         /**
40          * Package mask for compressing package data:
41          * 0: Compressor extension
42          * 1: Raw package data
43          * 2: Tags, seperated by semicolons, no semicolon is required if only one tag is needed
44          * 3: Checksum
45          *                     0  1  2  3
46          */
47         const PACKAGE_MASK = '%s:%s:%s:%s';
48
49         /**
50          * Seperator for the above mask
51          */
52         const PACKAGE_MASK_SEPERATOR = ':';
53
54         /**
55          * Seperator for checksum
56          */
57         const PACKAGE_CHECKSUM_SEPERATOR = ':';
58
59         /**
60          * Array indexes for above mask, start with zero
61          */
62         const INDEX_COMPRESSOR_EXTENSION = 0;
63         const INDEX_PACKAGE_DATA         = 1;
64         const INDEX_TAGS                 = 2;
65         const INDEX_CHECKSUM             = 3;
66
67         /**
68          * Array indexes for raw package array
69          */
70         const INDEX_PACKAGE_SENDER    = 0;
71         const INDEX_PACKAGE_RECIPIENT = 1;
72         const INDEX_PACKAGE_CONTENT   = 2;
73
74         /**
75          * Named array elements for package data
76          */
77         const PACKAGE_DATA_RECIPIENT = 'recipient';
78         const PACKAGE_DATA_SENDER    = 'sender';
79         const PACKAGE_DATA_CONTENT   = 'content';
80
81         /**
82          * Tags seperator
83          */
84         const PACKAGE_TAGS_SEPERATOR = ';';
85
86         /**
87          * Raw package data seperator
88          */
89         const PACKAGE_DATA_SEPERATOR = '|';
90
91         /**
92          * Stacker name for "undeclared" packages
93          */
94         const STACKER_NAME_UNDECLARED = 'undeclared';
95
96         /**
97          * Stacker name for "declared" packages (which are ready to send out)
98          */
99         const STACKER_NAME_DECLARED = 'declared';
100
101         /**
102          * Stacker name for "out-going" packages
103          */
104         const STACKER_NAME_OUTGOING = 'outgoing';
105
106         /**
107          * Stacker name for "back-buffered" packages
108          */
109         const STACKER_NAME_BACK_BUFFER = 'backbuffer';
110
111         /**
112          * Network target (alias): 'upper hubs'
113          */
114         const NETWORK_TARGET_UPPER_HUBS = 'upper';
115
116         /**
117          * Network target (alias): 'self'
118          */
119         const NETWORK_TARGET_SELF = 'self';
120
121         /**
122          * TCP package size in bytes
123          */
124         const TCP_PACKAGE_SIZE = 512;
125
126         /**
127          * Protected constructor
128          *
129          * @return      void
130          */
131         protected function __construct () {
132                 // Call parent constructor
133                 parent::__construct(__CLASS__);
134         }
135
136         /**
137          * Creates an instance of this class
138          *
139          * @param       $compressorInstance             A Compressor instance for compressing the content
140          * @return      $packageInstance                An instance of a Deliverable class
141          */
142         public static final function createNetworkPackage (Compressor $compressorInstance) {
143                 // Get new instance
144                 $packageInstance = new NetworkPackage();
145
146                 // Now set the compressor instance
147                 $packageInstance->setCompressorInstance($compressorInstance);
148
149                 // We need to initialize a stack here for our packages even those
150                 // which have no recipient address and stamp... ;-)
151                 $stackerInstance = ObjectFactory::createObjectByConfiguredName('network_package_stacker_class');
152
153                 // At last, set it in this class
154                 $packageInstance->setStackerInstance($stackerInstance);
155
156                 // Get a visitor instance for speeding up things
157                 $visitorInstance = ObjectFactory::createObjectByConfiguredName('node_raw_data_monitor_visitor_class', array($packageInstance));
158
159                 // Set it in this package
160                 $packageInstance->setVisitorInstance($visitorInstance);
161
162                 // Return the prepared instance
163                 return $packageInstance;
164         }
165
166         /**
167          * "Getter" for hash from given content and helper instance
168          *
169          * @param       $content        Raw package content
170          * @param       $helperInstance         An instance of a BaseHubHelper class
171          * @param       $nodeInstance           An instance of a NodeHelper class
172          * @return      $hash   Hash for given package content
173          * @todo        $helperInstance is unused
174          */
175         private function getHashFromContent ($content, BaseHubHelper $helperInstance, NodeHelper $nodeInstance) {
176                 // Create the hash
177                 // @TODO crc32 is not very strong, but it needs to be fast
178                 $hash = crc32(
179                         $content .
180                         self::PACKAGE_CHECKSUM_SEPERATOR .
181                         $nodeInstance->getSessionId() .
182                         self::PACKAGE_CHECKSUM_SEPERATOR .
183                         $this->getCompressorInstance()->getCompressorExtension()
184                 );
185
186                 // And return it
187                 return $hash;
188         }
189
190         ///////////////////////////////////////////////////////////////////////////
191         //                   Delivering packages / raw data
192         ///////////////////////////////////////////////////////////////////////////
193
194         /**
195          * Delivers the given raw package data.
196          *
197          * @param       $packageData    Raw package data in an array
198          * @return      void
199          */
200         private function declareRawPackageData (array $packageData) {
201                 /*
202                  * We need to disover every recipient, just in case we have a
203                  * multi-recipient entry like 'upper' is. 'all' may be a not so good
204                  * target because it causes an overload on the network and may be
205                  * abused for attacking the network with large packages.
206                  */
207                 $discoveryInstance = PackageDiscoveryFactory::createPackageDiscoveryInstance();
208
209                 // Discover all recipients, this may throw an exception
210                 $discoveryInstance->discoverRecipients($packageData);
211
212                 // Now get an iterator
213                 $iteratorInstance = $discoveryInstance->getIterator();
214
215                 // ... and begin iteration
216                 while ($iteratorInstance->valid()) {
217                         // Get current entry
218                         $currentRecipient = $iteratorInstance->current();
219
220                         // Debug message
221                         $this->debugOutput('PACKAGE: Package declared for recipient ' . $currentRecipient);
222
223                         // Set the recipient
224                         $packageData[self::PACKAGE_DATA_RECIPIENT] = $currentRecipient;
225
226                         // And enqueue it to the writer class
227                         $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECLARED, $packageData);
228
229                         // Skip to next entry
230                         $iteratorInstance->next();
231                 } // END - while
232
233                 // Clean-up the list
234                 $discoveryInstance->clearRecipients();
235         }
236
237         /**
238          * Delivers raw package data. In short, this will discover the raw socket
239          * resource through a discovery class (which will analyse the receipient of
240          * the package), register the socket with the connection (handler/helper?)
241          * instance and finally push the raw data on our outgoing queue.
242          *
243          * @param       $packageData    Raw package data in an array
244          * @return      void
245          */
246         private function deliverRawPackageData (array $packageData) {
247                 /*
248                  * This package may become big, depending on the shared object size or
249                  * delivered message size which shouldn't be so long (to save
250                  * bandwidth). Because of the nature of the used protocol (TCP) we need
251                  * to split it up into smaller pieces to fit it into a TCP frame.
252                  *
253                  * So first we need (again) a discovery class but now a protocol
254                  * discovery to choose the right socket resource. The discovery class
255                  * should take a look at the raw package data itself and then decide
256                  * which (configurable!) protocol should be used for that type of
257                  * package.
258                  */
259                 $discoveryInstance = SocketDiscoveryFactory::createSocketDiscoveryInstance();
260
261                 // Now discover the right protocol
262                 $socketResource = $discoveryInstance->discoverSocket($packageData);
263
264                 // We have to put this socket in our registry, so get an instance
265                 $registryInstance = SocketRegistry::createSocketRegistry();
266
267                 // Get the listener from registry
268                 $connectionInstance = Registry::getRegistry()->getInstance('connection');
269
270                 // Is it not there?
271                 if (!$registryInstance->isSocketRegistered($connectionInstance, $socketResource)) {
272                         // Then register it
273                         $registryInstance->registerSocket($connectionInstance, $socketResource, $packageData);
274                 } // END - if
275
276                 // We enqueue it again, but now in the out-going queue
277                 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_OUTGOING, $packageData);
278         }
279
280         /**
281          * Sends waiting packages
282          *
283          * @param       $packageData    Raw package data
284          * @return      void
285          */
286         private function sendOutgoingRawPackageData (array $packageData) {
287                 // Get the right connection instance
288                 $connectionInstance = SocketRegistry::createSocketRegistry()->getHandlerInstanceFromPackageData($packageData);
289
290                 // Is this connection still alive?
291                 if ($connectionInstance->isShuttedDown()) {
292                         // This connection is shutting down
293                         // @TODO We may want to do somthing more here?
294                         return;
295                 } // END - if
296
297                 // Sent it away (we catch exceptions one method above)
298                 $sentBytes = $connectionInstance->sendRawPackageData($packageData);
299
300                 // Remember unsent raw bytes in back-buffer, if any
301                 $this->storeUnsentBytesInBackBuffer($packageData, $sentBytes);
302         }
303
304         /**
305          * "Enqueues" raw content into this delivery class by reading the raw content
306          * from given template instance and pushing it on the 'undeclared' stack.
307          *
308          * @param       $helperInstance         An instance of a  BaseHubHelper class
309          * @param       $nodeInstance           An instance of a NodeHelper class
310          * @return      void
311          */
312         public function enqueueRawDataFromTemplate (BaseHubHelper $helperInstance, NodeHelper $nodeInstance) {
313                 // Get the raw content ...
314                 $content = $helperInstance->getTemplateInstance()->getRawTemplateData();
315
316                 // ... and compress it
317                 $content = $this->getCompressorInstance()->compressStream($content);
318
319                 // Add magic in front of it and hash behind it, including BASE64 encoding
320                 $content = sprintf(self::PACKAGE_MASK,
321                         // 1.) Compressor's extension
322                         $this->getCompressorInstance()->getCompressorExtension(),
323                         // 2.) Raw package content, encoded with BASE64
324                         base64_encode($content),
325                         // 3.) Tags
326                         implode(self::PACKAGE_TAGS_SEPERATOR, $helperInstance->getPackageTags()),
327                         // 4.) Checksum
328                         $this->getHashFromContent($content, $helperInstance, $nodeInstance)
329                 );
330
331                 // Now prepare the temporary array and push it on the 'undeclared' stack
332                 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_UNDECLARED, array(
333                         self::PACKAGE_DATA_SENDER    => $nodeInstance->getSessionId(),
334                         self::PACKAGE_DATA_RECIPIENT => $helperInstance->getRecipientType(),
335                         self::PACKAGE_DATA_CONTENT   => $content,
336                 ));
337         }
338
339         /**
340          * Checks wether a package has been enqueued for delivery.
341          *
342          * @return      $isEnqueued             Wether a package is enqueued
343          */
344         public function isPackageEnqueued () {
345                 // Check wether the stacker is not empty
346                 $isEnqueued = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_UNDECLARED)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_UNDECLARED)));
347
348                 // Return the result
349                 return $isEnqueued;
350         }
351
352         /**
353          * Checks wether a package has been declared
354          *
355          * @return      $isDeclared             Wether a package is declared
356          */
357         public function isPackageDeclared () {
358                 // Check wether the stacker is not empty
359                 $isDeclared = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_DECLARED)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECLARED)));
360
361                 // Return the result
362                 return $isDeclared;
363         }
364
365         /**
366          * Checks wether a package should be sent out
367          *
368          * @return      $isWaitingDelivery      Wether a package is waiting for delivery
369          */
370         public function isPackageWaitingForDelivery () {
371                 // Check wether the stacker is not empty
372                 $isWaitingDelivery = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_OUTGOING)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_OUTGOING)));
373
374                 // Return the result
375                 return $isWaitingDelivery;
376         }
377
378         /**
379          * Delivers an enqueued package to the stated destination. If a non-session
380          * id is provided, recipient resolver is being asked (and instanced once).
381          * This allows that a single package is being delivered to multiple targets
382          * without enqueueing it for every target. If no target is provided or it
383          * can't be determined a NoTargetException is being thrown.
384          *
385          * @return      void
386          * @throws      NoTargetException       If no target can't be determined
387          */
388         public function declareEnqueuedPackage () {
389                 // Make sure this method isn't working if there is no package enqueued
390                 if (!$this->isPackageEnqueued()) {
391                         // This is not fatal but should be avoided
392                         // @TODO Add some logging here
393                         return;
394                 } // END - if
395
396                 // Now we know for sure there are packages to deliver, we can start
397                 // with the first one.
398                 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_UNDECLARED);
399
400                 // Declare the raw package data for delivery
401                 $this->declareRawPackageData($packageData);
402
403                 // And remove it finally
404                 $this->getStackerInstance()->popNamed(self::STACKER_NAME_UNDECLARED);
405         }
406
407         /**
408          * Delivers the next declared package. Only one package per time will be sent
409          * because this may take time and slows down the whole delivery
410          * infrastructure.
411          *
412          * @return      void
413          */
414         public function deliverDeclaredPackage () {
415                 // Sanity check if we have packages declared
416                 if (!$this->isPackageDeclared()) {
417                         // This is not fatal but should be avoided
418                         // @TODO Add some logging here
419                         return;
420                 } // END - if
421
422                 // Get the package again
423                 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_DECLARED);
424
425                 // And send it
426                 $this->deliverRawPackageData($packageData);
427
428                 // And remove it finally
429                 $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECLARED);
430         }
431
432         /**
433          * Sends waiting packages out for delivery
434          *
435          * @return      void
436          */
437         public function sendWaitingPackage () {
438                 // Send any waiting bytes in the back-buffer before sending a new package
439                 $this->sendBackBufferBytes();
440
441                 // Sanity check if we have packages waiting for delivery
442                 if (!$this->isPackageWaitingForDelivery()) {
443                         // This is not fatal but should be avoided
444                         $this->debugOutput('PACKAGE: No package is waiting for delivery, but ' . __METHOD__ . ' was called.');
445                         return;
446                 } // END - if
447
448                 // Get the package again
449                 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_OUTGOING);
450
451                 try {
452                         // Now try to send it
453                         $this->sendOutgoingRawPackageData($packageData);
454
455                         // And remove it finally
456                         $this->getStackerInstance()->popNamed(self::STACKER_NAME_OUTGOING);
457                 } catch (InvalidSocketException $e) {
458                         // Output exception message
459                         $this->debugOutput('PACKAGE: Package was not delivered: ' . $e->getMessage());
460                 }
461         }
462
463         ///////////////////////////////////////////////////////////////////////////
464         //                   Receiving packages / raw data
465         ///////////////////////////////////////////////////////////////////////////
466
467         /**
468          * Checks wether new raw package data has arrived at a socket
469          *
470          * @param       $poolInstance   An instance of a PoolableListener class
471          * @return      $hasArrived             Wether new raw package data has arrived for processing
472          */
473         public function isNewRawDataPending (PoolableListener $poolInstance) {
474                 // By default no new data has arrived
475                 $hasArrived = false;
476
477                 // Visit the pool
478                 $poolInstance->accept($this->getVisitorInstance());
479                 // @TODO Check for if new data has arrived
480
481                 // Return the status
482                 return $hasArrived;
483         }
484
485         /**
486          * Checks wether a new package has arrived
487          *
488          * @return      $hasArrived             Wether a new package has arrived for processing
489          */
490         public function isNewPackageArrived () {
491                 // @TODO Add some content here
492         }
493 }
494
495 // [EOF]
496 ?>