3 * A general hub system class
5 * @author Roland Haeder <webmaster@ship-simu.org>
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
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;
28 const EXCEPTION_ANNOUNCEMENT_NOT_ACCEPTED = 0x902;
31 * Separator for all bootstrap node entries
33 const BOOTSTRAP_NODES_SEPARATOR = ';';
36 * An instance of a node
38 private $nodeInstance = NULL;
41 * An instance of a cruncher
43 private $cruncherInstance = NULL;
48 private $listenerInstance = NULL;
51 * A network package handler instance
53 private $packageInstance = NULL;
56 * A Receivable instance
58 private $receiverInstance = NULL;
63 private $stateInstance = NULL;
66 * Listener pool instance
68 private $listenerPoolInstance = NULL;
73 private $fragmenterInstance = NULL;
78 private $decoderInstance = NULL;
83 private $assemblerInstance = NULL;
86 * Protected constructor
88 * @param $className Name of the class
91 protected function __construct ($className) {
92 // Call parent constructor
93 parent::__construct($className);
97 * Getter for node instance
99 * @return $nodeInstance An instance of a node node
101 public final function getNodeInstance () {
102 return $this->nodeInstance;
106 * Setter for node instance
108 * @param $nodeInstance An instance of a node node
111 protected final function setNodeInstance (NodeHelper $nodeInstance) {
112 $this->nodeInstance = $nodeInstance;
116 * Getter for cruncher instance
118 * @return $cruncherInstance An instance of a cruncher cruncher
120 public final function getCruncherInstance () {
121 return $this->cruncherInstance;
125 * Setter for cruncher instance
127 * @param $cruncherInstance An instance of a cruncher cruncher
130 protected final function setCruncherInstance (CruncherHelper $cruncherInstance) {
131 $this->cruncherInstance = $cruncherInstance;
135 * Setter for listener instance
137 * @param $listenerInstance A Listenable instance
140 protected final function setListenerInstance (Listenable $listenerInstance) {
141 $this->listenerInstance = $listenerInstance;
145 * Getter for listener instance
147 * @return $listenerInstance A Listenable instance
149 protected final function getListenerInstance () {
150 return $this->listenerInstance;
154 * Setter for network package handler instance
156 * @param $packageInstance The network package instance we shall set
159 protected final function setPackageInstance (Deliverable $packageInstance) {
160 $this->packageInstance = $packageInstance;
164 * Getter for network package handler instance
166 * @return $packageInstance The network package handler instance we shall set
168 protected final function getPackageInstance () {
169 return $this->packageInstance;
173 * Setter for receiver instance
175 * @param $receiverInstance A Receivable instance we shall set
178 protected final function setReceiverInstance (Receivable $receiverInstance) {
179 $this->receiverInstance = $receiverInstance;
183 * Getter for receiver instance
185 * @return $receiverInstance A Receivable instance we shall get
187 protected final function getReceiverInstance () {
188 return $this->receiverInstance;
192 * Setter for state instance
194 * @param $stateInstance A Stateable instance
197 public final function setStateInstance (Stateable $stateInstance) {
198 $this->stateInstance = $stateInstance;
202 * Getter for state instance
204 * @return $stateInstance A Stateable instance
206 public final function getStateInstance () {
207 return $this->stateInstance;
211 * Setter for listener pool instance
213 * @param $listenerPoolInstance Our new listener pool instance
216 protected final function setListenerPoolInstance (PoolableListener $listenerPoolInstance) {
217 $this->listenerPoolInstance = $listenerPoolInstance;
221 * Getter for listener pool instance
223 * @return $listenerPoolInstance Our current listener pool instance
225 public final function getListenerPoolInstance () {
226 return $this->listenerPoolInstance;
230 * Setter for fragmenter instance
232 * @param $fragmenterInstance A Fragmentable instance
235 protected final function setFragmenterInstance (Fragmentable $fragmenterInstance) {
236 $this->fragmenterInstance = $fragmenterInstance;
240 * Getter for fragmenter instance
242 * @return $fragmenterInstance A Fragmentable instance
244 protected final function getFragmenterInstance () {
245 return $this->fragmenterInstance;
249 * Setter for decoder instance
251 * @param $decoderInstance A Decodeable instance
254 protected final function setDecoderInstance (Decodeable $decoderInstance) {
255 $this->decoderInstance = $decoderInstance;
259 * Getter for decoder instance
261 * @return $decoderInstance A Decodeable instance
263 protected final function getDecoderInstance () {
264 return $this->decoderInstance;
268 * Setter for assembler instance
270 * @param $assemblerInstance A Decodeable instance
273 protected final function setAssemblerInstance (Assembler $assemblerInstance) {
274 $this->assemblerInstance = $assemblerInstance;
278 * Getter for assembler instance
280 * @return $assemblerInstance A Decodeable instance
282 protected final function getAssemblerInstance () {
283 return $this->assemblerInstance;
289 * @param $nodeId Our new node id
292 protected final function setNodeId ($nodeId) {
294 $this->getConfigInstance()->setConfigEntry('node_id', (string) $nodeId);
300 * @return $nodeId Current node id
302 public final function getNodeId () {
303 // Get it from config
304 return $this->getConfigInstance()->getConfigEntry('node_id');
308 * Setter for session id
310 * @param $sessionId Our new session id
313 protected final function setSessionId ($sessionId) {
314 $this->getConfigInstance()->setConfigEntry('session_id', (string) $sessionId);
318 * Getter for session id
320 * @return $sessionId Current session id
322 public final function getSessionId () {
323 return $this->getConfigInstance()->getConfigEntry('session_id');
327 * Constructs a callable method name from given socket error code. If the
328 * method is not found, a generic one is used.
330 * @param $errorCode Error code from socket_last_error()
331 * @return $handlerName Call-back method name for the error handler
332 * @throws UnsupportedSocketErrorHandlerException If the error handler is not implemented
334 protected function getSocketErrorHandlerFromCode ($errorCode) {
335 // Create a name from translated error code
336 $handlerName = 'socketError' . $this->convertToClassName($this->translateSocketErrorCodeToName($errorCode)) . 'Handler';
338 // Is the call-back method there?
339 if (!method_exists($this, $handlerName)) {
340 // Please implement this
341 throw new UnsupportedSocketErrorHandlerException(array($this, $handlerName, $errorCode), self::EXCEPTION_UNSUPPORTED_ERROR_HANDLER);
349 * Handles socket error for given socket resource and peer data. This method
350 * validates $socketResource if it is a valid resource (see is_resource())
351 * but assumes valid data in array $recipientData, except that
352 * count($recipientData) is always 2.
354 * @param $socketResource A valid socket resource
355 * @param $recipientData An array with two elements: 0=IP number, 1=port number
357 * @throws InvalidSocketException If $socketResource is no socket resource
358 * @throws NoSocketErrorDetectedException If socket_last_error() gives zero back
360 protected final function handleSocketError ($socketResource, array $recipientData) {
361 // This method handles only socket resources
362 if (!is_resource($socketResource)) {
363 // No resource, abort here
364 throw new InvalidSocketException(array($this, $socketResource), BaseListener::EXCEPTION_INVALID_SOCKET);
367 // Check count of array, should be two
368 assert(count($recipientData) == 2);
370 // Get error code for first validation (0 is not an error)
371 $errorCode = socket_last_error($socketResource);
373 // If the error code is zero, someone called this method without an error
374 if ($errorCode == 0) {
375 // No error detected (or previously cleared outside this method)
376 throw new NoSocketErrorDetectedException(array($this, $socketResource), BaseListener::EXCEPTION_NO_SOCKET_ERROR);
379 // Get handler (method) name
380 $handlerName = $this->getSocketErrorHandlerFromCode($errorCode);
382 // Call-back the error handler method
383 call_user_func(array($this, $handlerName), $socketResource);
385 // Finally clear the error because it has been handled
386 socket_clear_error($socketResource);
390 * Checks whether the final (last) chunk is valid
392 * @param $chunks An array with chunks and (hopefully) a valid final chunk
393 * @return $isValid Whether the final (last) chunk is valid
395 protected function isValidFinalChunk (array $chunks) {
396 // Default is all fine
399 // Split the (possible) EOP chunk
400 $chunkSplits = explode(PackageFragmenter::CHUNK_DATA_HASH_SEPARATOR, $chunks[count($chunks) - 1]);
402 // Make sure chunks with only 3 elements are parsed (for details see ChunkHandler)
403 //* NOISY-DEBUG: */ $this->debugOutput('eopChunk=' . $chunks[count($chunks) - 1] . ',chunkSplits=' . print_r($chunkSplits,true));
404 assert(count($chunkSplits) == 3);
406 // Validate final chunk
407 if (substr($chunkSplits[ChunkHandler::CHUNK_SPLITS_INDEX_RAW_DATA], 0, strlen(PackageFragmenter::END_OF_PACKAGE_IDENTIFIER)) != PackageFragmenter::END_OF_PACKAGE_IDENTIFIER) {
410 } elseif (substr_count($chunkSplits[ChunkHandler::CHUNK_SPLITS_INDEX_RAW_DATA], PackageFragmenter::CHUNK_HASH_SEPARATOR) != 1) {
411 // CHUNK_HASH_SEPARATOR shall only be found once
420 * Translates socket error codes into our own internal names which can be
421 * used for call-backs.
423 * @param $errorCode The error code from socket_last_error() to be translated
424 * @return $errorName The translated name (all lower-case, with underlines)
426 public function translateSocketErrorCodeToName ($errorCode) {
427 // Nothing bad happened by default
428 $errorName = BaseRawDataHandler::SOCKET_CONNECTED;
430 // Is the code a number, then we have to change it
431 switch ($errorCode) {
432 case 0: // Silently ignored, the socket is connected
435 case 11: // "Resource temporary unavailable"
436 $errorName = BaseRawDataHandler::SOCKET_ERROR_RESOURCE_UNAVAILABLE;
439 case 107: // "Transport end-point not connected"
440 case 134: // On some (?) systems for 'transport end-point not connected'
441 // @TODO On some systems it is 134, on some 107?
442 $errorName = BaseRawDataHandler::SOCKET_ERROR_TRANSPORT_ENDPOINT;
445 case 110: // "Connection timed out"
446 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_TIMED_OUT;
449 case 111: // "Connection refused"
450 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_REFUSED;
453 case 113: // "No route to host"
454 $errorName = BaseRawDataHandler::SOCKET_ERROR_NO_ROUTE_TO_HOST;
457 case 114: // "Operation already in progress"
458 $errorName = BaseRawDataHandler::SOCKET_ERROR_OPERATION_ALREADY_PROGRESS;
461 case 115: // "Operation now in progress"
462 $errorName = BaseRawDataHandler::SOCKET_ERROR_OPERATION_IN_PROGRESS;
465 default: // Everything else <> 0
466 // Unhandled error code detected, so first debug it because we may want to handle it like the others
467 $this->debugOutput('[' . __METHOD__ . ':' . __LINE__ . '] UNKNOWN ERROR CODE = ' . $errorCode . ', MESSAGE = ' . socket_strerror($errorCode));
469 // Change it only in this class
470 $errorName = BaseRawDataHandler::SOCKET_ERROR_UNKNOWN;
474 // Return translated name
479 * Shuts down a given socket resource. This method does only ease calling
482 * @param $socketResource A valid socket resource
485 public function shutdownSocket ($socketResource) {
487 $this->debugOutput('HUB-SYSTEM: Shutting down socket resource ' . $socketResource . ' with state ' . $this->getPrintableState() . ' ...');
489 // Set socket resource
490 $this->setSocketResource($socketResource);
492 // Get a visitor instance
493 $visitorInstance = ObjectFactory::createObjectByConfiguredName('shutdown_socket_visitor_class');
496 $this->debugOutput('HUB-SYSTEM:' . $this->__toString() . ': visitorInstance=' . $visitorInstance->__toString());
499 $this->accept($visitorInstance);
503 * Half-shuts down a given socket resource. This method does only ease calling
504 * an other visitor than shutdownSocket() does.
506 * @param $socketResource A valid socket resource
509 public function halfShutdownSocket ($socketResource) {
511 $this->debugOutput('HUB-SYSTEM: Half-shutting down socket resource ' . $socketResource . ' with state ' . $this->getPrintableState() . ' ...');
513 // Set socket resource
514 $this->setSocketResource($socketResource);
516 // Get a visitor instance
517 $visitorInstance = ObjectFactory::createObjectByConfiguredName('half_shutdown_socket_visitor_class');
520 $this->debugOutput('HUB-SYSTEM:' . $this->__toString() . ': visitorInstance=' . $visitorInstance->__toString());
523 $this->accept($visitorInstance);
527 * "Getter" for a printable state name
529 * @return $stateName Name of the node's state in a printable format
531 public final function getPrintableState () {
535 // Get the state instance
536 $stateInstance = $this->getStateInstance();
538 // Is it an instance of Stateable?
539 if ($stateInstance instanceof Stateable) {
540 // Then use that state name
541 $stateName = $stateInstance->getStateName();