3 * A general hub system class
5 * @author Roland Haeder <webmaster@ship-simu.org>
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
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.
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.
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/>.
24 class BaseHubSystem extends BaseFrameworkSystem {
26 const EXCEPTION_UNSUPPORTED_ERROR_HANDLER = 0x900;
27 const EXCEPTION_CHUNK_ALREADY_ASSEMBLED = 0x901;
30 * Separator for all bootstrap node entries
32 const BOOTSTRAP_NODES_SEPARATOR = ';';
35 * An instance of a node
37 private $nodeInstance = NULL;
40 * An instance of a cruncher
42 private $cruncherInstance = NULL;
47 private $listenerInstance = NULL;
50 * A network package handler instance
52 private $packageInstance = NULL;
55 * A Receivable instance
57 private $receiverInstance = NULL;
62 private $stateInstance = NULL;
65 * Listener pool instance
67 private $listenerPoolInstance = NULL;
72 private $fragmenterInstance = NULL;
77 private $decoderInstance = NULL;
80 * Protected constructor
82 * @param $className Name of the class
85 protected function __construct ($className) {
86 // Call parent constructor
87 parent::__construct($className);
91 * Getter for node instance
93 * @return $nodeInstance An instance of a node node
95 public final function getNodeInstance () {
96 return $this->nodeInstance;
100 * Setter for node instance
102 * @param $nodeInstance An instance of a node node
105 protected final function setNodeInstance (NodeHelper $nodeInstance) {
106 $this->nodeInstance = $nodeInstance;
110 * Getter for cruncher instance
112 * @return $cruncherInstance An instance of a cruncher cruncher
114 public final function getCruncherInstance () {
115 return $this->cruncherInstance;
119 * Setter for cruncher instance
121 * @param $cruncherInstance An instance of a cruncher cruncher
124 protected final function setCruncherInstance (CruncherHelper $cruncherInstance) {
125 $this->cruncherInstance = $cruncherInstance;
129 * Setter for listener instance
131 * @param $listenerInstance A Listenable instance
134 protected final function setListenerInstance (Listenable $listenerInstance) {
135 $this->listenerInstance = $listenerInstance;
139 * Getter for listener instance
141 * @return $listenerInstance A Listenable instance
143 protected final function getListenerInstance () {
144 return $this->listenerInstance;
148 * Setter for network package handler instance
150 * @param $packageInstance The network package instance we shall set
153 protected final function setPackageInstance (Deliverable $packageInstance) {
154 $this->packageInstance = $packageInstance;
158 * Getter for network package handler instance
160 * @return $packageInstance The network package handler instance we shall set
162 protected final function getPackageInstance () {
163 return $this->packageInstance;
167 * Setter for receiver instance
169 * @param $receiverInstance A Receivable instance we shall set
172 protected final function setReceiverInstance (Receivable $receiverInstance) {
173 $this->receiverInstance = $receiverInstance;
177 * Getter for receiver instance
179 * @return $receiverInstance A Receivable instance we shall get
181 protected final function getReceiverInstance () {
182 return $this->receiverInstance;
186 * Setter for state instance
188 * @param $stateInstance A Stateable instance
191 public final function setStateInstance (Stateable $stateInstance) {
192 $this->stateInstance = $stateInstance;
196 * Getter for state instance
198 * @return $stateInstance A Stateable instance
200 public final function getStateInstance () {
201 return $this->stateInstance;
205 * Setter for listener pool instance
207 * @param $listenerPoolInstance Our new listener pool instance
210 protected final function setListenerPoolInstance (PoolableListener $listenerPoolInstance) {
211 $this->listenerPoolInstance = $listenerPoolInstance;
215 * Getter for listener pool instance
217 * @return $listenerPoolInstance Our current listener pool instance
219 public final function getListenerPoolInstance () {
220 return $this->listenerPoolInstance;
224 * Setter for fragmenter instance
226 * @param $fragmenterInstance A Fragmentable instance
229 protected final function setFragmenterInstance (Fragmentable $fragmenterInstance) {
230 $this->fragmenterInstance = $fragmenterInstance;
234 * Getter for fragmenter instance
236 * @return $fragmenterInstance A Fragmentable instance
238 protected final function getFragmenterInstance () {
239 return $this->fragmenterInstance;
243 * Setter for decoder instance
245 * @param $decoderInstance A Decodeable instance
248 protected final function setDecoderInstance (Decodeable $decoderInstance) {
249 $this->decoderInstance = $decoderInstance;
253 * Getter for decoder instance
255 * @return $decoderInstance A Decodeable instance
257 protected final function getDecoderInstance () {
258 return $this->decoderInstance;
262 * Constructs a callable method name from given socket error code. If the
263 * method is not found, a generic one is used.
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
269 protected function getSocketErrorHandlerFromCode ($errorCode) {
270 // Create a name from translated error code
271 $handlerName = 'socketError' . $this->convertToClassName($this->translateSocketErrorCodeToName($errorCode)) . 'Handler';
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);
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.
289 * @param $socketResource A valid socket resource
290 * @param $recipientData An array with two elements: 0=IP number, 1=port number
292 * @throws InvalidSocketException If $socketResource is no socket resource
293 * @throws NoSocketErrorDetectedException If socket_last_error() gives zero back
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);
302 // Check count of array, should be two
303 assert(count($recipientData) == 2);
305 // Get error code for first validation (0 is not an error)
306 $errorCode = socket_last_error($socketResource);
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);
314 // Get handler (method) name
315 $handlerName = $this->getSocketErrorHandlerFromCode($errorCode);
317 // Call-back the error handler method
318 call_user_func(array($this, $handlerName), $socketResource);
320 // Finally clear the error because it has been handled
321 socket_clear_error($socketResource);
325 * Checks whether the final (last) chunk is valid
327 * @param $chunks An array with chunks and (hopefully) a valid final chunk
328 * @return $isValid Whether the final (last) chunk is valid
330 protected function isValidFinalChunk (array $chunks) {
331 // Default is all fine
334 // Split the (possible) EOP chunk
335 $chunkSplits = explode(PackageFragmenter::CHUNK_DATA_HASH_SEPARATOR, $chunks[count($chunks) - 1]);
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);
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) {
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
355 * Translates socket error codes into our own internal names which can be
356 * used for call-backs.
358 * @param $errorCode The error code from socket_last_error() to be translated
359 * @return $errorName The translated name (all lower-case, with underlines)
361 public function translateSocketErrorCodeToName ($errorCode) {
362 // Nothing bad happened by default
363 $errorName = BaseRawDataHandler::SOCKET_CONNECTED;
365 // Is the code a number, then we have to change it
366 switch ($errorCode) {
367 case 0: // Silently ignored, the socket is connected
370 case 11: // "Resource temporary unavailable"
371 $errorName = BaseRawDataHandler::SOCKET_ERROR_RESOURCE_UNAVAILABLE;
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;
380 case 110: // "Connection timed out"
381 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_TIMED_OUT;
384 case 111: // "Connection refused"
385 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_REFUSED;
388 case 113: // "No route to host"
389 $errorName = BaseRawDataHandler::SOCKET_ERROR_NO_ROUTE_TO_HOST;
392 case 114: // "Operation already in progress"
393 $errorName = BaseRawDataHandler::SOCKET_ERROR_OPERATION_ALREADY_PROGRESS;
396 case 115: // "Operation now in progress"
397 $errorName = BaseRawDataHandler::SOCKET_ERROR_OPERATION_IN_PROGRESS;
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));
404 // Change it only in this class
405 $errorName = BaseRawDataHandler::SOCKET_ERROR_UNKNOWN;
409 // Return translated name
414 * Shuts down a given socket resource. This method does only ease calling
417 * @param $socketResource A valid socket resource
420 public function shutdownSocket ($socketResource) {
422 $this->debugOutput('HUB-SYSTEM: Shutting down socket resource ' . $socketResource . ' with state ' . $this->getPrintableState() . ' ...');
424 // Set socket resource
425 $this->setSocketResource($socketResource);
427 // Get a visitor instance
428 $visitorInstance = ObjectFactory::createObjectByConfiguredName('shutdown_socket_visitor_class');
431 $this->debugOutput('HUB-SYSTEM:' . $this->__toString() . ': visitorInstance=' . $visitorInstance->__toString());
434 $this->accept($visitorInstance);
438 * Half-shuts down a given socket resource. This method does only ease calling
439 * an other visitor than shutdownSocket() does.
441 * @param $socketResource A valid socket resource
444 public function halfShutdownSocket ($socketResource) {
446 $this->debugOutput('HUB-SYSTEM: Half-shutting down socket resource ' . $socketResource . ' with state ' . $this->getPrintableState() . ' ...');
448 // Set socket resource
449 $this->setSocketResource($socketResource);
451 // Get a visitor instance
452 $visitorInstance = ObjectFactory::createObjectByConfiguredName('half_shutdown_socket_visitor_class');
455 $this->debugOutput('HUB-SYSTEM:' . $this->__toString() . ': visitorInstance=' . $visitorInstance->__toString());
458 $this->accept($visitorInstance);
462 * "Getter" for a printable state name
464 * @return $stateName Name of the node's state in a printable format
466 public final function getPrintableState () {
470 // Get the state instance
471 $stateInstance = $this->getStateInstance();
473 // Is it an instance of Stateable?
474 if ($stateInstance instanceof Stateable) {
475 // Then use that state name
476 $stateName = $stateInstance->getStateName();