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;
30 // Message status codes
31 const MESSAGE_STATUS_CODE_OKAY = 'OKAY';
34 * Separator for all bootstrap node entries
36 const BOOTSTRAP_NODES_SEPARATOR = ';';
39 * An instance of a node
41 private $nodeInstance = NULL;
44 * An instance of a cruncher
46 private $cruncherInstance = NULL;
51 private $listenerInstance = NULL;
54 * A network package handler instance
56 private $packageInstance = NULL;
59 * A Receivable instance
61 private $receiverInstance = NULL;
66 private $stateInstance = NULL;
69 * Listener pool instance
71 private $listenerPoolInstance = NULL;
76 private $fragmenterInstance = NULL;
81 private $decoderInstance = NULL;
86 private $assemblerInstance = NULL;
89 * Protected constructor
91 * @param $className Name of the class
94 protected function __construct ($className) {
95 // Call parent constructor
96 parent::__construct($className);
100 * Getter for node instance
102 * @return $nodeInstance An instance of a node node
104 public final function getNodeInstance () {
105 return $this->nodeInstance;
109 * Setter for node instance
111 * @param $nodeInstance An instance of a node node
114 protected final function setNodeInstance (NodeHelper $nodeInstance) {
115 $this->nodeInstance = $nodeInstance;
119 * Getter for cruncher instance
121 * @return $cruncherInstance An instance of a cruncher cruncher
123 public final function getCruncherInstance () {
124 return $this->cruncherInstance;
128 * Setter for cruncher instance
130 * @param $cruncherInstance An instance of a cruncher cruncher
133 protected final function setCruncherInstance (CruncherHelper $cruncherInstance) {
134 $this->cruncherInstance = $cruncherInstance;
138 * Setter for listener instance
140 * @param $listenerInstance A Listenable instance
143 protected final function setListenerInstance (Listenable $listenerInstance) {
144 $this->listenerInstance = $listenerInstance;
148 * Getter for listener instance
150 * @return $listenerInstance A Listenable instance
152 protected final function getListenerInstance () {
153 return $this->listenerInstance;
157 * Setter for network package handler instance
159 * @param $packageInstance The network package instance we shall set
162 protected final function setPackageInstance (Deliverable $packageInstance) {
163 $this->packageInstance = $packageInstance;
167 * Getter for network package handler instance
169 * @return $packageInstance The network package handler instance we shall set
171 protected final function getPackageInstance () {
172 return $this->packageInstance;
176 * Setter for receiver instance
178 * @param $receiverInstance A Receivable instance we shall set
181 protected final function setReceiverInstance (Receivable $receiverInstance) {
182 $this->receiverInstance = $receiverInstance;
186 * Getter for receiver instance
188 * @return $receiverInstance A Receivable instance we shall get
190 protected final function getReceiverInstance () {
191 return $this->receiverInstance;
195 * Setter for state instance
197 * @param $stateInstance A Stateable instance
200 public final function setStateInstance (Stateable $stateInstance) {
201 $this->stateInstance = $stateInstance;
205 * Getter for state instance
207 * @return $stateInstance A Stateable instance
209 public final function getStateInstance () {
210 return $this->stateInstance;
214 * Setter for listener pool instance
216 * @param $listenerPoolInstance Our new listener pool instance
219 protected final function setListenerPoolInstance (PoolableListener $listenerPoolInstance) {
220 $this->listenerPoolInstance = $listenerPoolInstance;
224 * Getter for listener pool instance
226 * @return $listenerPoolInstance Our current listener pool instance
228 public final function getListenerPoolInstance () {
229 return $this->listenerPoolInstance;
233 * Setter for fragmenter instance
235 * @param $fragmenterInstance A Fragmentable instance
238 protected final function setFragmenterInstance (Fragmentable $fragmenterInstance) {
239 $this->fragmenterInstance = $fragmenterInstance;
243 * Getter for fragmenter instance
245 * @return $fragmenterInstance A Fragmentable instance
247 protected final function getFragmenterInstance () {
248 return $this->fragmenterInstance;
252 * Setter for decoder instance
254 * @param $decoderInstance A Decodeable instance
257 protected final function setDecoderInstance (Decodeable $decoderInstance) {
258 $this->decoderInstance = $decoderInstance;
262 * Getter for decoder instance
264 * @return $decoderInstance A Decodeable instance
266 protected final function getDecoderInstance () {
267 return $this->decoderInstance;
271 * Setter for assembler instance
273 * @param $assemblerInstance A Decodeable instance
276 protected final function setAssemblerInstance (Assembler $assemblerInstance) {
277 $this->assemblerInstance = $assemblerInstance;
281 * Getter for assembler instance
283 * @return $assemblerInstance A Decodeable instance
285 protected final function getAssemblerInstance () {
286 return $this->assemblerInstance;
292 * @param $nodeId Our new node id
295 protected final function setNodeId ($nodeId) {
297 $this->getConfigInstance()->setConfigEntry('node_id', (string) $nodeId);
303 * @return $nodeId Current node id
305 public final function getNodeId () {
306 // Get it from config
307 return $this->getConfigInstance()->getConfigEntry('node_id');
311 * Setter for session id
313 * @param $sessionId Our new session id
316 protected final function setSessionId ($sessionId) {
317 $this->getConfigInstance()->setConfigEntry('session_id', (string) $sessionId);
321 * Getter for session id
323 * @return $sessionId Current session id
325 public final function getSessionId () {
326 return $this->getConfigInstance()->getConfigEntry('session_id');
330 * Constructs a callable method name from given socket error code. If the
331 * method is not found, a generic one is used.
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
337 protected function getSocketErrorHandlerFromCode ($errorCode) {
338 // Create a name from translated error code
339 $handlerName = 'socketError' . $this->convertToClassName($this->translateSocketErrorCodeToName($errorCode)) . 'Handler';
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);
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.
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
362 * @throws InvalidSocketException If $socketResource is no socket resource
363 * @throws NoSocketErrorDetectedException If socket_last_error() gives zero back
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);
372 // Check count of array, should be two
373 assert(count($recipientData) == 2);
375 // Get error code for first validation (0 is not an error)
376 $errorCode = socket_last_error($socketResource);
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);
384 // Get handler (method) name
385 $handlerName = $this->getSocketErrorHandlerFromCode($errorCode);
387 // Call-back the error handler method
388 call_user_func(array($this, $handlerName), $socketResource);
390 // Finally clear the error because it has been handled
391 socket_clear_error($socketResource);
395 * Checks whether the final (last) chunk is valid
397 * @param $chunks An array with chunks and (hopefully) a valid final chunk
398 * @return $isValid Whether the final (last) chunk is valid
400 protected function isValidFinalChunk (array $chunks) {
401 // Default is all fine
404 // Split the (possible) EOP chunk
405 $chunkSplits = explode(PackageFragmenter::CHUNK_DATA_HASH_SEPARATOR, $chunks[count($chunks) - 1]);
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);
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) {
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
425 * Translates socket error codes into our own internal names which can be
426 * used for call-backs.
428 * @param $errorCode The error code from socket_last_error() to be translated
429 * @return $errorName The translated name (all lower-case, with underlines)
431 public function translateSocketErrorCodeToName ($errorCode) {
432 // Nothing bad happened by default
433 $errorName = BaseRawDataHandler::SOCKET_CONNECTED;
435 // Is the code a number, then we have to change it
436 switch ($errorCode) {
437 case 0: // Silently ignored, the socket is connected
440 case 11: // "Resource temporary unavailable"
441 $errorName = BaseRawDataHandler::SOCKET_ERROR_RESOURCE_UNAVAILABLE;
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;
450 case 110: // "Connection timed out"
451 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_TIMED_OUT;
454 case 111: // "Connection refused"
455 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_REFUSED;
458 case 113: // "No route to host"
459 $errorName = BaseRawDataHandler::SOCKET_ERROR_NO_ROUTE_TO_HOST;
462 case 114: // "Operation already in progress"
463 $errorName = BaseRawDataHandler::SOCKET_ERROR_OPERATION_ALREADY_PROGRESS;
466 case 115: // "Operation now in progress"
467 $errorName = BaseRawDataHandler::SOCKET_ERROR_OPERATION_IN_PROGRESS;
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));
474 // Change it only in this class
475 $errorName = BaseRawDataHandler::SOCKET_ERROR_UNKNOWN;
479 // Return translated name
484 * Shuts down a given socket resource. This method does only ease calling
487 * @param $socketResource A valid socket resource
490 public function shutdownSocket ($socketResource) {
492 $this->debugOutput('HUB-SYSTEM: Shutting down socket resource ' . $socketResource . ' with state ' . $this->getPrintableState() . ' ...');
494 // Set socket resource
495 $this->setSocketResource($socketResource);
497 // Get a visitor instance
498 $visitorInstance = ObjectFactory::createObjectByConfiguredName('shutdown_socket_visitor_class');
501 $this->debugOutput('HUB-SYSTEM:' . $this->__toString() . ': visitorInstance=' . $visitorInstance->__toString());
504 $this->accept($visitorInstance);
508 * Half-shuts down a given socket resource. This method does only ease calling
509 * an other visitor than shutdownSocket() does.
511 * @param $socketResource A valid socket resource
514 public function halfShutdownSocket ($socketResource) {
516 $this->debugOutput('HUB-SYSTEM: Half-shutting down socket resource ' . $socketResource . ' with state ' . $this->getPrintableState() . ' ...');
518 // Set socket resource
519 $this->setSocketResource($socketResource);
521 // Get a visitor instance
522 $visitorInstance = ObjectFactory::createObjectByConfiguredName('half_shutdown_socket_visitor_class');
525 $this->debugOutput('HUB-SYSTEM:' . $this->__toString() . ': visitorInstance=' . $visitorInstance->__toString());
528 $this->accept($visitorInstance);
532 * "Getter" for a printable state name
534 * @return $stateName Name of the node's state in a printable format
536 public final function getPrintableState () {
540 // Get the state instance
541 $stateInstance = $this->getStateInstance();
543 // Is it an instance of Stateable?
544 if ($stateInstance instanceof Stateable) {
545 // Then use that state name
546 $stateName = $stateInstance->getStateName();