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