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