]> git.mxchange.org Git - hub.git/blob - application/hub/main/package/class_NetworkPackage.php
Continued with package fragmenter (a lot new, but unfinished code)
[hub.git] / application / hub / main / package / class_NetworkPackage.php
1 <?php
2 /**
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.
7  *
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
12  * Internet.
13  *
14  * For performance reasons, this class should only be instanciated once and then
15  * used as a "pipe-through" class.
16  *
17  * @author              Roland Haeder <webmaster@ship-simu.org>
18  * @version             0.0.0
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
23  *
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.
28  *
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.
33  *
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/>.
36  */
37 class NetworkPackage extends BaseFrameworkSystem implements Deliverable, Registerable {
38         /**
39          * Package mask for compressing package data:
40          * 0: Compressor extension
41          * 1: Raw package data
42          * 2: Tags, seperated by semicolons, no semicolon is required if only one tag is needed
43          * 3: Checksum
44          *                     0  1  2  3
45          */
46         const PACKAGE_MASK = '%s:%s:%s:%s';
47
48         /**
49          * Seperator for the above mask
50          */
51         const PACKAGE_MASK_SEPERATOR = ':';
52
53         /**
54          * Array indexes for above mask, start with zero
55          */
56         const INDEX_COMPRESSOR_EXTENSION = 0;
57         const INDEX_PACKAGE_DATA         = 1;
58         const INDEX_TAGS                 = 2;
59         const INDEX_CHECKSUM             = 3;
60
61         /**
62          * Array indexes for raw package array
63          */
64         const INDEX_PACKAGE_SENDER    = 0;
65         const INDEX_PACKAGE_RECIPIENT = 1;
66         const INDEX_PACKAGE_CONTENT   = 2;
67
68         /**
69          * Tags seperator
70          */
71         const PACKAGE_TAGS_SEPERATOR = ';';
72
73         /**
74          * Raw package data seperator
75          */
76         const PACKAGE_DATA_SEPERATOR = '|';
77
78         /**
79          * Stacker name for "undeclared" packages
80          */
81         const STACKER_NAME_UNDECLARED = 'undeclared';
82
83         /**
84          * Stacker name for "declared" packages (which are ready to send out)
85          */
86         const STACKER_NAME_DECLARED = 'declared';
87
88         /**
89          * Stacker name for "out-going" packages
90          */
91         const STACKER_NAME_OUTGOING = 'outgoing';
92
93         /**
94          * Stacker name for "back-buffered" packages
95          */
96         const STACKER_NAME_BACK_BUFFER = 'backbuffer';
97
98         /**
99          * Network target (alias): 'upper hubs'
100          */
101         const NETWORK_TARGET_UPPER_HUBS = 'upper';
102
103         /**
104          * Network target (alias): 'self'
105          */
106         const NETWORK_TARGET_SELF = 'self';
107
108         /**
109          * TCP package size
110          */
111         const TCP_PACKAGE_SIZE = 512;
112
113         /**
114          * Protected constructor
115          *
116          * @return      void
117          */
118         protected function __construct () {
119                 // Call parent constructor
120                 parent::__construct(__CLASS__);
121
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');
125
126                 // At last, set it in this class
127                 $this->setStackerInstance($stackerInstance);
128         }
129
130         /**
131          * Creates an instance of this class
132          *
133          * @param       $compressorInstance             A Compressor instance for compressing the content
134          * @return      $packageInstance                An instance of a Deliverable class
135          */
136         public static final function createNetworkPackage (Compressor $compressorInstance) {
137                 // Get new instance
138                 $packageInstance = new NetworkPackage();
139
140                 // Now set the compressor instance
141                 $packageInstance->setCompressorInstance($compressorInstance);
142
143                 // Return the prepared instance
144                 return $packageInstance;
145         }
146
147         /**
148          * "Getter" for hash from given content and helper instance
149          *
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
154          */
155         private function getHashFromContent ($content, BaseHubHelper $helperInstance, NodeHelper $nodeInstance) {
156                 // Create the hash
157                 // @TODO crc32 is not good, but it needs to be fast
158                 $hash = crc32(
159                         $content .
160                         ':' .
161                         $nodeInstance->getSessionId() .
162                         ':' .
163                         $this->getCompressorInstance()->getCompressorExtension()
164                 );
165
166                 // And return it
167                 return $hash;
168         }
169
170         /**
171          * Delivers the given raw package data.
172          *
173          * @param       $packageData    Raw package data in an array
174          * @return      void
175          */
176         private function declareRawPackageData (array $packageData) {
177                 /*
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.
182                  */
183                 $discoveryInstance = PackageDiscoveryFactory::createPackageDiscoveryInstance();
184
185                 // Discover all recipients, this may throw an exception
186                 $discoveryInstance->discoverRecipients($packageData);
187
188                 // Now get an iterator
189                 $iteratorInstance = $discoveryInstance->getIterator();
190
191                 // ... and begin iteration
192                 while ($iteratorInstance->valid()) {
193                         // Get current entry
194                         $currentRecipient = $iteratorInstance->current();
195
196                         // Debug message
197                         $this->debugOutput('PACKAGE: Package declared for recipient ' . $currentRecipient);
198
199                         // Set the recipient
200                         $packageData['recipient'] = $currentRecipient;
201
202                         // And enqueue it to the writer class
203                         $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECLARED, $packageData);
204
205                         // Skip to next entry
206                         $iteratorInstance->next();
207                 } // END - while
208
209                 // Clean-up the list
210                 $discoveryInstance->clearRecipients();
211         }
212
213         /**
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.
218          *
219          * @param       $packageData    Raw package data in an array
220          * @return      void
221          */
222         private function deliverRawPackageData (array $packageData) {
223                 /*
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.
228                  *
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
233                  * package.
234                  */
235                 $discoveryInstance = SocketDiscoveryFactory::createSocketDiscoveryInstance();
236
237                 // Now discover the right protocol
238                 $socketResource = $discoveryInstance->discoverSocket($packageData);
239
240                 // We have to put this socket in our registry, so get an instance
241                 $registryInstance = SocketRegistry::createSocketRegistry();
242
243                 // Get the listener from registry
244                 $connectionInstance = Registry::getRegistry()->getInstance('connection');
245
246                 // Is it not there?
247                 if (!$registryInstance->isSocketRegistered($connectionInstance, $socketResource)) {
248                         // Then register it
249                         $registryInstance->registerSocket($connectionInstance, $socketResource, $packageData);
250                 } // END - if
251
252                 // We enqueue it again, but now in the out-going queue
253                 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_OUTGOING, $packageData);
254         }
255
256         /**
257          * Sends waiting packages
258          *
259          * @param       $packageData    Raw package data
260          * @return      void
261          */
262         private function sendOutgoingRawPackageData (array $packageData) {
263                 // Get the right connection instance
264                 $connectionInstance = SocketRegistry::createSocketRegistry()->getHandlerInstanceFromPackageData($packageData);
265
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?
270                         return;
271                 } // END - if
272
273                 // Sent it away (we catch exceptions one method above
274                 $sentBytes = $connectionInstance->sendRawPackageData($packageData);
275
276                 // Remember unsent raw bytes in back-buffer, if any
277                 $this->storeUnsentBytesInBackBuffer($packageData, $sentBytes);
278         }
279
280         /**
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.
283          *
284          * @param       $helperInstance         An instance of a  BaseHubHelper class
285          * @param       $nodeInstance           An instance of a NodeHelper class
286          * @return      void
287          */
288         public function enqueueRawDataFromTemplate (BaseHubHelper $helperInstance, NodeHelper $nodeInstance) {
289                 // Get the raw content ...
290                 $content = $helperInstance->getTemplateInstance()->getRawTemplateData();
291
292                 // ... and compress it
293                 $content = $this->getCompressorInstance()->compressStream($content);
294
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),
301                         // 3.) Tags
302                         implode(self::PACKAGE_TAGS_SEPERATOR, $helperInstance->getPackageTags()),
303                         // 4.) Checksum
304                         $this->getHashFromContent($content, $helperInstance, $nodeInstance)
305                 );
306
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,
312                 ));
313         }
314
315         /**
316          * Checks wether a package has been enqueued for delivery.
317          *
318          * @return      $isEnqueued             Wether a package is enqueued
319          */
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)));
323
324                 // Return the result
325                 return $isEnqueued;
326         }
327
328         /**
329          * Checks wether a package has been declared
330          *
331          * @return      $isDeclared             Wether a package is declared
332          */
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)));
336
337                 // Return the result
338                 return $isDeclared;
339         }
340
341         /**
342          * Checks wether a package should be sent out
343          *
344          * @return      $isWaitingDelivery      Wether a package is waiting for delivery
345          */
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)));
349
350                 // Return the result
351                 return $isWaitingDelivery;
352         }
353
354         /**
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.
360          *
361          * @return      void
362          * @throws      NoTargetException       If no target can't be determined
363          */
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
369                         return;
370                 } // END - if
371
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);
375
376                 // Declare the raw package data for delivery
377                 $this->declareRawPackageData($packageData);
378
379                 // And remove it finally
380                 $this->getStackerInstance()->popNamed(self::STACKER_NAME_UNDECLARED);
381         }
382
383         /**
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
386          * infrastructure.
387          *
388          * @return      void
389          */
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
395                         return;
396                 } // END - if
397
398                 // Get the package again
399                 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_DECLARED);
400
401                 // And send it
402                 $this->deliverRawPackageData($packageData);
403
404                 // And remove it finally
405                 $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECLARED);
406         }
407
408         /**
409          * Sends waiting packages out for delivery
410          *
411          * @return      void
412          */
413         public function sendWaitingPackage () {
414                 // Send any waiting bytes in the back-buffer before sending a new package
415                 $this->sendBackBufferBytes();
416
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.');
421                         return;
422                 } // END - if
423
424                 // Get the package again
425                 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_OUTGOING);
426
427                 try {
428                         // Now try to send it
429                         $this->sendOutgoingRawPackageData($packageData);
430                         die("O!\n");
431
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());
437                 }
438         }
439 }
440
441 // [EOF]
442 ?>