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