]> git.mxchange.org Git - hub.git/blob - application/hub/main/class_BaseHubSystem.php
Copyright notice updated
[hub.git] / application / hub / main / class_BaseHubSystem.php
1 <?php
2 /**
3  * A general hub system class
4  *
5  * @author              Roland Haeder <webmaster@ship-simu.org>
6  * @version             0.0.0
7  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2012 Hub Developer Team
8  * @license             GNU GPL 3.0 or any newer version
9  * @link                http://www.ship-simu.org
10  *
11  * This program is free software: you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation, either version 3 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
23  */
24 class BaseHubSystem extends BaseFrameworkSystem {
25         // Exception codes
26         const EXCEPTION_UNSUPPORTED_ERROR_HANDLER = 0x900;
27         const EXCEPTION_CHUNK_ALREADY_ASSEMBLED   = 0x901;
28
29         /**
30          * Separator for all bootstrap node entries
31          */
32         const BOOTSTRAP_NODES_SEPARATOR = ';';
33
34         /**
35          * An instance of a node
36          */
37         private $nodeInstance = NULL;
38
39         /**
40          * An instance of a cruncher
41          */
42         private $cruncherInstance = NULL;
43
44         /**
45          * Listener instance
46          */
47         private $listenerInstance = NULL;
48
49         /**
50          * A network package handler instance
51          */
52         private $packageInstance = NULL;
53
54         /**
55          * A Receivable instance
56          */
57         private $receiverInstance = NULL;
58
59         /**
60          * State instance
61          */
62         private $stateInstance = NULL;
63
64         /**
65          * Listener pool instance
66          */
67         private $listenerPoolInstance = NULL;
68
69         /**
70          * Fragmenter instance
71          */
72         private $fragmenterInstance = NULL;
73
74         /**
75          * Decoder instance
76          */
77         private $decoderInstance = NULL;
78
79         /**
80          * Assembler instance
81          */
82         private $assemblerInstance = NULL;
83
84         /**
85          * Protected constructor
86          *
87          * @param       $className      Name of the class
88          * @return      void
89          */
90         protected function __construct ($className) {
91                 // Call parent constructor
92                 parent::__construct($className);
93         }
94
95         /**
96          * Getter for node instance
97          *
98          * @return      $nodeInstance   An instance of a node node
99          */
100         public final function getNodeInstance () {
101                 return $this->nodeInstance;
102         }
103
104         /**
105          * Setter for node instance
106          *
107          * @param       $nodeInstance   An instance of a node node
108          * @return      void
109          */
110         protected final function setNodeInstance (NodeHelper $nodeInstance) {
111                 $this->nodeInstance = $nodeInstance;
112         }
113
114         /**
115          * Getter for cruncher instance
116          *
117          * @return      $cruncherInstance       An instance of a cruncher cruncher
118          */
119         public final function getCruncherInstance () {
120                 return $this->cruncherInstance;
121         }
122
123         /**
124          * Setter for cruncher instance
125          *
126          * @param       $cruncherInstance       An instance of a cruncher cruncher
127          * @return      void
128          */
129         protected final function setCruncherInstance (CruncherHelper $cruncherInstance) {
130                 $this->cruncherInstance = $cruncherInstance;
131         }
132
133         /**
134          * Setter for listener instance
135          *
136          * @param       $listenerInstance       A Listenable instance
137          * @return      void
138          */
139         protected final function setListenerInstance (Listenable $listenerInstance) {
140                 $this->listenerInstance = $listenerInstance;
141         }
142
143         /**
144          * Getter for listener instance
145          *
146          * @return      $listenerInstance       A Listenable instance
147          */
148         protected final function getListenerInstance () {
149                 return $this->listenerInstance;
150         }
151
152         /**
153          * Setter for network package handler instance
154          *
155          * @param       $packageInstance        The network package instance we shall set
156          * @return      void
157          */
158         protected final function setPackageInstance (Deliverable $packageInstance) {
159                 $this->packageInstance = $packageInstance;
160         }
161
162         /**
163          * Getter for network package handler instance
164          *
165          * @return      $packageInstance        The network package handler instance we shall set
166          */
167         protected final function getPackageInstance () {
168                 return $this->packageInstance;
169         }
170
171         /**
172          * Setter for receiver instance
173          *
174          * @param       $receiverInstance       A Receivable instance we shall set
175          * @return      void
176          */
177         protected final function setReceiverInstance (Receivable $receiverInstance) {
178                 $this->receiverInstance = $receiverInstance;
179         }
180
181         /**
182          * Getter for receiver instance
183          *
184          * @return      $receiverInstance       A Receivable instance we shall get
185          */
186         protected final function getReceiverInstance () {
187                 return $this->receiverInstance;
188         }
189
190         /**
191          * Setter for state instance
192          *
193          * @param       $stateInstance  A Stateable instance
194          * @return      void
195          */
196         public final function setStateInstance (Stateable $stateInstance) {
197                 $this->stateInstance = $stateInstance;
198         }
199
200         /**
201          * Getter for state instance
202          *
203          * @return      $stateInstance  A Stateable instance
204          */
205         public final function getStateInstance () {
206                 return $this->stateInstance;
207         }
208
209         /**
210          * Setter for listener pool instance
211          *
212          * @param       $listenerPoolInstance   Our new listener pool instance
213          * @return      void
214          */
215         protected final function setListenerPoolInstance (PoolableListener $listenerPoolInstance) {
216                 $this->listenerPoolInstance = $listenerPoolInstance;
217         }
218
219         /**
220          * Getter for listener pool instance
221          *
222          * @return      $listenerPoolInstance   Our current listener pool instance
223          */
224         public final function getListenerPoolInstance () {
225                 return $this->listenerPoolInstance;
226         }
227
228         /**
229          * Setter for fragmenter instance
230          *
231          * @param       $fragmenterInstance             A Fragmentable instance
232          * @return      void
233          */
234         protected final function setFragmenterInstance (Fragmentable $fragmenterInstance) {
235                 $this->fragmenterInstance = $fragmenterInstance;
236         }
237
238         /**
239          * Getter for fragmenter instance
240          *
241          * @return      $fragmenterInstance             A Fragmentable instance
242          */
243         protected final function getFragmenterInstance () {
244                 return $this->fragmenterInstance;
245         }
246
247         /**
248          * Setter for decoder instance
249          *
250          * @param       $decoderInstance        A Decodeable instance
251          * @return      void
252          */
253         protected final function setDecoderInstance (Decodeable $decoderInstance) {
254                 $this->decoderInstance = $decoderInstance;
255         }
256
257         /**
258          * Getter for decoder instance
259          *
260          * @return      $decoderInstance        A Decodeable instance
261          */
262         protected final function getDecoderInstance () {
263                 return $this->decoderInstance;
264         }
265
266         /**
267          * Setter for assembler instance
268          *
269          * @param       $assemblerInstance      A Decodeable instance
270          * @return      void
271          */
272         protected final function setAssemblerInstance (Assembler $assemblerInstance) {
273                 $this->assemblerInstance = $assemblerInstance;
274         }
275
276         /**
277          * Getter for assembler instance
278          *
279          * @return      $assemblerInstance      A Decodeable instance
280          */
281         protected final function getAssemblerInstance () {
282                 return $this->assemblerInstance;
283         }
284
285         /**
286          * Setter for node id
287          *
288          * @param       $nodeId         Our new node id
289          * @return      void
290          */
291         protected final function setNodeId ($nodeId) {
292                 // Set it config now
293                 $this->getConfigInstance()->setConfigEntry('node_id', (string) $nodeId);
294         }
295
296         /**
297          * Getter for node id
298          *
299          * @return      $nodeId         Current node id
300          */
301         public final function getNodeId () {
302                 // Get it from config
303                 return $this->getConfigInstance()->getConfigEntry('node_id');
304         }
305
306         /**
307          * Setter for session id
308          *
309          * @param       $sessionId              Our new session id
310          * @return      void
311          */
312         protected final function setSessionId ($sessionId) {
313                 $this->getConfigInstance()->setConfigEntry('session_id', (string) $sessionId);
314         }
315
316         /**
317          * Getter for session id
318          *
319          * @return      $sessionId              Current session id
320          */
321         public final function getSessionId () {
322                 return $this->getConfigInstance()->getConfigEntry('session_id');
323         }
324
325         /**
326          * Constructs a callable method name from given socket error code. If the
327          * method is not found, a generic one is used.
328          *
329          * @param       $errorCode              Error code from socket_last_error()
330          * @return      $handlerName    Call-back method name for the error handler
331          * @throws      UnsupportedSocketErrorHandlerException If the error handler is not implemented
332          */
333         protected function getSocketErrorHandlerFromCode ($errorCode) {
334                 // Create a name from translated error code
335                 $handlerName = 'socketError' . $this->convertToClassName($this->translateSocketErrorCodeToName($errorCode)) . 'Handler';
336
337                 // Is the call-back method there?
338                 if (!method_exists($this, $handlerName)) {
339                         // Please implement this
340                         throw new UnsupportedSocketErrorHandlerException(array($this, $handlerName, $errorCode), self::EXCEPTION_UNSUPPORTED_ERROR_HANDLER);
341                 } // END - if
342
343                 // Return it
344                 return $handlerName;
345         }
346
347         /**
348          * Handles socket error for given socket resource and peer data. This method
349          * validates $socketResource if it is a valid resource (see is_resource())
350          * but assumes valid data in array $recipientData, except that
351          * count($recipientData) is always 2.
352          *
353          * @param       $socketResource         A valid socket resource
354          * @param       $recipientData          An array with two elements: 0=IP number, 1=port number
355          * @return      void
356          * @throws      InvalidSocketException  If $socketResource is no socket resource
357          * @throws      NoSocketErrorDetectedException  If socket_last_error() gives zero back
358          */
359         protected final function handleSocketError ($socketResource, array $recipientData) {
360                 // This method handles only socket resources
361                 if (!is_resource($socketResource)) {
362                         // No resource, abort here
363                         throw new InvalidSocketException(array($this, $socketResource), BaseListener::EXCEPTION_INVALID_SOCKET);
364                 } // END - if
365
366                 // Check count of array, should be two
367                 assert(count($recipientData) == 2);
368
369                 // Get error code for first validation (0 is not an error)
370                 $errorCode = socket_last_error($socketResource);
371
372                 // If the error code is zero, someone called this method without an error
373                 if ($errorCode == 0) {
374                         // No error detected (or previously cleared outside this method)
375                         throw new NoSocketErrorDetectedException(array($this, $socketResource), BaseListener::EXCEPTION_NO_SOCKET_ERROR);
376                 } // END - if
377
378                 // Get handler (method) name
379                 $handlerName = $this->getSocketErrorHandlerFromCode($errorCode);
380
381                 // Call-back the error handler method
382                 call_user_func(array($this, $handlerName), $socketResource);
383
384                 // Finally clear the error because it has been handled
385                 socket_clear_error($socketResource);
386         }
387
388         /**
389          * Checks whether the final (last) chunk is valid
390          *
391          * @param       $chunks         An array with chunks and (hopefully) a valid final chunk
392          * @return      $isValid        Whether the final (last) chunk is valid
393          */
394         protected function isValidFinalChunk (array $chunks) {
395                 // Default is all fine
396                 $isValid = true;
397
398                 // Split the (possible) EOP chunk
399                 $chunkSplits = explode(PackageFragmenter::CHUNK_DATA_HASH_SEPARATOR, $chunks[count($chunks) - 1]);
400
401                 // Make sure chunks with only 3 elements are parsed (for details see ChunkHandler)
402                 //* NOISY-DEBUG: */ $this->debugOutput('eopChunk=' . $chunks[count($chunks) - 1] . ',chunkSplits=' . print_r($chunkSplits,true));
403                 assert(count($chunkSplits) == 3);
404
405                 // Validate final chunk
406                 if (substr($chunkSplits[ChunkHandler::CHUNK_SPLITS_INDEX_RAW_DATA], 0, strlen(PackageFragmenter::END_OF_PACKAGE_IDENTIFIER)) != PackageFragmenter::END_OF_PACKAGE_IDENTIFIER) {
407                         // Not fine
408                         $isValid = false;
409                 } elseif (substr_count($chunkSplits[ChunkHandler::CHUNK_SPLITS_INDEX_RAW_DATA], PackageFragmenter::CHUNK_HASH_SEPARATOR) != 1) {
410                         // CHUNK_HASH_SEPARATOR shall only be found once
411                         $isValid = false;
412                 }
413
414                 // Return status
415                 return $isValid;
416         }
417
418         /**
419          * Translates socket error codes into our own internal names which can be
420          * used for call-backs.
421          *
422          * @param       $errorCode      The error code from socket_last_error() to be translated
423          * @return      $errorName      The translated name (all lower-case, with underlines)
424          */
425         public function translateSocketErrorCodeToName ($errorCode) {
426                 // Nothing bad happened by default
427                 $errorName = BaseRawDataHandler::SOCKET_CONNECTED;
428
429                 // Is the code a number, then we have to change it
430                 switch ($errorCode) {
431                         case 0: // Silently ignored, the socket is connected
432                                 break;
433
434                         case 11:  // "Resource temporary unavailable"
435                                 $errorName = BaseRawDataHandler::SOCKET_ERROR_RESOURCE_UNAVAILABLE;
436                                 break;
437
438                         case 107: // "Transport end-point not connected"
439                         case 134: // On some (?) systems for 'transport end-point not connected'
440                                 // @TODO On some systems it is 134, on some 107?
441                                 $errorName = BaseRawDataHandler::SOCKET_ERROR_TRANSPORT_ENDPOINT;
442                                 break;
443
444                         case 110: // "Connection timed out"
445                                 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_TIMED_OUT;
446                                 break;
447
448                         case 111: // "Connection refused"
449                                 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_REFUSED;
450                                 break;
451
452                         case 113: // "No route to host"
453                                 $errorName = BaseRawDataHandler::SOCKET_ERROR_NO_ROUTE_TO_HOST;
454                                 break;
455
456                         case 114: // "Operation already in progress"
457                                 $errorName = BaseRawDataHandler::SOCKET_ERROR_OPERATION_ALREADY_PROGRESS;
458                                 break;
459
460                         case 115: // "Operation now in progress"
461                                 $errorName = BaseRawDataHandler::SOCKET_ERROR_OPERATION_IN_PROGRESS;
462                                 break;
463
464                         default: // Everything else <> 0
465                                 // Unhandled error code detected, so first debug it because we may want to handle it like the others
466                                 $this->debugOutput('[' . __METHOD__ . ':' . __LINE__ . '] UNKNOWN ERROR CODE = ' . $errorCode . ', MESSAGE = ' . socket_strerror($errorCode));
467
468                                 // Change it only in this class
469                                 $errorName = BaseRawDataHandler::SOCKET_ERROR_UNKNOWN;
470                                 break;
471                 }
472
473                 // Return translated name
474                 return $errorName;
475         }
476
477         /**
478          * Shuts down a given socket resource. This method does only ease calling
479          * the right visitor.
480          *
481          * @param       $socketResource         A valid socket resource
482          * @return      void
483          */
484         public function shutdownSocket ($socketResource) {
485                 // Debug message
486                 $this->debugOutput('HUB-SYSTEM: Shutting down socket resource ' . $socketResource . ' with state ' . $this->getPrintableState() . ' ...');
487
488                 // Set socket resource
489                 $this->setSocketResource($socketResource);
490
491                 // Get a visitor instance
492                 $visitorInstance = ObjectFactory::createObjectByConfiguredName('shutdown_socket_visitor_class');
493
494                 // Debug output
495                 $this->debugOutput('HUB-SYSTEM:' . $this->__toString() . ': visitorInstance=' . $visitorInstance->__toString());
496
497                 // Call the visitor
498                 $this->accept($visitorInstance);
499         }
500
501         /**
502          * Half-shuts down a given socket resource. This method does only ease calling
503          * an other visitor than shutdownSocket() does.
504          *
505          * @param       $socketResource         A valid socket resource
506          * @return      void
507          */
508         public function halfShutdownSocket ($socketResource) {
509                 // Debug message
510                 $this->debugOutput('HUB-SYSTEM: Half-shutting down socket resource ' . $socketResource . ' with state ' . $this->getPrintableState() . ' ...');
511
512                 // Set socket resource
513                 $this->setSocketResource($socketResource);
514
515                 // Get a visitor instance
516                 $visitorInstance = ObjectFactory::createObjectByConfiguredName('half_shutdown_socket_visitor_class');
517
518                 // Debug output
519                 $this->debugOutput('HUB-SYSTEM:' . $this->__toString() . ': visitorInstance=' . $visitorInstance->__toString());
520
521                 // Call the visitor
522                 $this->accept($visitorInstance);
523         }
524
525         /**
526          * "Getter" for a printable state name
527          *
528          * @return      $stateName      Name of the node's state in a printable format
529          */
530         public final function getPrintableState () {
531                 // Default is 'null'
532                 $stateName = 'null';
533
534                 // Get the state instance
535                 $stateInstance = $this->getStateInstance();
536
537                 // Is it an instance of Stateable?
538                 if ($stateInstance instanceof Stateable) {
539                         // Then use that state name
540                         $stateName = $stateInstance->getStateName();
541                 } // END - if
542
543                 // Return result
544                 return $stateName;
545         }
546 }
547
548 // [EOF]
549 ?>